<?php

namespace Mnv\Models;


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

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

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

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

    protected string $orderBy = 'orderBy ASC';

    protected string $columns = 'brandId, name, url, publishedOn, orderBy, status';


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

    /**
     * @return array
     */
    public static function getBrands(): array
    {
        $brandList = array();
        if ($brands = connect()->table('brands')->orderBy('name')->getAll('array')) {
            foreach ($brands as $key => $brand) {
                $letter = mb_substr(mb_strtolower($brand['name']), 0, 1);
                $brandList[$letter][] = $brand;

            }
            ksort($brandList);
            //print_r($brandList);
        }
        return $brandList;
    }

    /**
     * фильтрация / сортировка контента
     */
    protected function sorting(): void
    {

        if (!empty($this->filter['status'])) {
            connect()->where('status', $this->filter['status']);
        }

        if (!empty($this->filter['query'])) {
            connect()->grouped(function($q) {
                $q->like('name', "%" . $this->filter['query'] . "%")->orLike('content', "%" . $this->filter['query'] . "%")->orLike('keywords',"%" . $this->filter['query'] . "%");
            });
        }
    }

    public function all($limit, $page)
    {
        /** фильтрация / сортировка */
        $this->sorting();
        return parent::all($limit, $page);
    }

    public function total(): void
    {
        /** фильтрация / сортировка */
        $this->sorting();
        parent::total();
    }

    /**
     * Проверка на совпадение и получение fileName
     *
     * @param string|null $fileName
     * @return int|mixed|string|null
     */
    public function checkFileName(?string $fileName)
    {
        if (empty($fileName)) {
            $maxId = $this->getMaxValue($this->primaryKey);
            return $maxId ? $maxId + 1 : 1;
        }

        if (!empty($this->id)) connect()->where($this->primaryKey,'<>', $this->id);
        if ($fileName = connect()->table($this->table)->select('fileName')->where('LOWER(fileName)', strtolower($fileName))->getValue()) {
            return $fileName;
        }

        return null;
    }

    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['name'] . "»", $managerId)->save();
                return true;
            }
            Logger::init()->error("Ошибка при создание бренда «" . $data['name'] . "»", $managerId)->save();
        }
        else {
            if ($this->update($data)) {
                Logger::init()->info("Бренд «" . $data['name'] . "» отредактирован", $managerId)->save();
                return true;
            }
            Logger::init()->error("Ошибка при редактирование бренда «" . $data['name'] . "»", $managerId)->save();
        }

        return false;
    }

    /**
     * Удаление
     *
     * @return bool
     */
    public function remove(): bool
    {
        if (parent::remove()) {
            connect()->table('brand_images')->where($this->primaryKey, $this->id)->delete();
            return true;
        }

        return false;
    }

    /**
     * Утверждение
     * @return bool
     */
    public function approve(): bool
    {
        if (connect()->table($this->table)->where($this->primaryKey, $this->id)->update(['status' => 'V'])) {
            return true;
        }

       return false;

    }

}