<?php

namespace Mnv\Models;

use Mnv\Core\Model;
use Mnv\Core\Test\Logger;
use Mnv\Http\Request;

/**
 * Class Banners
 * @package Mnv\Models
 */
class Banners extends Model
{
    /** @var string */
    protected string $table = 'banners';

    /** @var string  */
    protected string $table_image = 'banner_images';

    /** @var string  */
    protected string $primaryKey = 'bannerId';

    /** @var string  */
    protected string $orderBy = 'orderBy ASC';

    public $bannerIds;

    public function __construct(Request $request)
    {
        $this->id           = $request->get('id');                 // getRequestVar('id', ''),
        $this->data         = $request->get('banner', '');  // getRequestVar('banner', '',  true)
        $this->bannerIds    = $request->get('ids', '');     // getRequestVar('ids', '', true);
    }

    public function prepare(array $data, int $managerId): bool
    {

        $data['modifiedBy']   = $managerId;
        $data['modifiedOn']   = gmdate('Y-m-d H:i:s');

        if (empty($this->id)) {

            $data['addedBy'] = $managerId;
            $data['addedOn'] = gmdate('Y-m-d H:i:s');
            $data['orderBy'] = $this->getMaxValue('orderBy') + 1;
            if ($this->id = $this->insert($data)) {
                Logger::init()->info("Добавлен новый банер «" . $data['title'] . "»", $managerId)->save();
                return true;
            }
        }
        else {
            if ($this->update($data)) {
                Logger::init()->info("Банер «" . $data['title'] . "» отредактирован", $managerId)->save();
                return true;
            }
        }

        return false;
    }

    public function remove(): bool
    {
        if (!empty($this->id) && connect($this->table)->where($this->primaryKey, $this->id)->delete()) {
            connect()->table('banner_images')->where($this->primaryKey, $this->id)->delete();

            return true;
        }

        return false;
    }

    public function checkFileName(?string $fileName)
    {
        // TODO: Implement checkFileName() method.
    }

}