<?php

namespace Mnv\Models\Shop;

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

//INSERT INTO `ls_product_features` (`id`, `sectionIds`, `name`, `fileName`, `orderBy`, `status`, `isFilter`, `content`) VALUES
//(1, '[\"3\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"13\"]', 'Год выпуска', 'year', 1, 'hidden', 0, ''),
//(2, '[\"3\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"13\"]', 'Цвет', 'color', 2, 'visible', 0, ''),
//(3, '[\"3\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"13\"]', 'КПП', 'kpp', 3, 'visible', 0, ''),
//(4, '[\"3\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"13\"]', 'Двигатель', 'engine', 4, 'visible', 0, ''),
//(5, '[\"3\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"13\"]', 'Кондиционер', 'conditioner', 5, 'visible', 0, ''),
//(6, '[\"3\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"13\"]', 'Топливо', 'fuel', 6, 'visible', 0, ''),
//(7, '[\"3\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"13\"]', 'Расход топлива', 'fuelConsumption', 7, 'visible', 0, ''),
//(8, '[\"3\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"13\"]', 'Количество сидений', 'numberSeats', 8, 'visible', 0, ''),
//(9, '[\"3\",\"7\",\"8\",\"9\",\"10\",\"11\"]', 'Количество дверей', 'numberDoors', 9, 'visible', 0, '');

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

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

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

    public $featureIds = [];
    public $params;

    public function __construct(Request $request)
    {
        $this->id           = $request->get('id');
        $this->data         = $request->get('feature', '');
        $this->featureIds   = $request->get('ids', '');
        $this->params       = $request->get('params', '');
    }

    private function sorting(): void
    {
        if (!empty($this->filter['query'])) {
            connect()->grouped(function($q) {
                $q->like('name', "%" . $this->filter['query'] . "%");
            });
        }
        if (!empty($this->filter['status'])) connect()->where('status', $this->filter['status']);

        if (!empty($this->filter['sectionIds'])) {
            connect()->grouped(function($q) {
                foreach ($this->filter['sectionIds'] as $key => $sectionId) {
                    if ($key === array_key_first($this->filter['sectionIds'])) {
                        $q->like('sectionIds', "%" . $sectionId . "%");
                    } else {
                        $q->orLike('sectionIds', "%" . $sectionId . "%");
                    }
                }
            });
        }
        connect()->whereNull('parentId',  false);
    }


    public function all($limit, $page)
    {
        $this->sorting();

        return parent::all($limit, $page);

    }

    public function total(): void
    {
        $this->sorting();

        parent::total();
    }


    /**
     * @param string|null $fileName
     * @return mixed|string|null
     */
    public function checkFileName(?string $fileName)
    {
        return connect()->table($this->table)->select('id')->where('name', $fileName)->getValue();

    }

    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)) {
                return true;
            }
        }
        else {
            return $this->update($data);
        }

        return false;
    }

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

            return true;
        }

        return false;
    }

    /** SPECIFICATIONS */

    /**
     * Функция возвращает варианты товара
     * @return array|null
     */
    public function features(): ?array
    {
        if (!empty($this->id)) {
            return connect($this->table)->where('parentId', $this->id)->orderBy('orderBy')->indexKey($this->primaryKey)->getAllIndexes('array');
        }

        return [];
    }

    public function feature(int $featureId)
    {
        if (!empty($featureId)) {
            return connect($this->table)->where($this->primaryKey, $featureId)->get('array');
        }

        return null;
    }

    public function addFeature(array $feature, $managerId): int
    {
        $feature['parentId'] = $this->id;
        $feature['orderBy'] = 0;
        $feature['addedBy'] = $managerId;
        $feature['addedOn'] = gmdate('Y-m-d H:i:s');
        $feature['modifiedBy']   = $managerId;
        $feature['modifiedOn']   = gmdate('Y-m-d H:i:s');

        return connect($this->table)->insert($feature);
    }


    /**
     * @param int $featureId
     * @param array $feature
     * @param $managerId
     */
    public function updateFeature(int $featureId, array $feature, $managerId): void
    {
        $feature['modifiedBy']   = $managerId;
        $feature['modifiedOn']   = gmdate('Y-m-d H:i:s');
        connect($this->table)->where($this->primaryKey, $featureId)->update($feature);
    }

    public function removeFeature(int $featureId): void
    {
        connect($this->table)->where($this->primaryKey, $featureId)->delete();
    }


}