<?php

namespace Mnv\Models\Shop;

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

/**
 * Class CarModelBlocks
 * @package Mnv\Models\Contents
 */
class ProductBlocks extends Model
{

    /** @var string */
    protected string $table = 'product_blocks';

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

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

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

    /** @var array|mixed  */
    public $blockIds = [];

    public $backgrounds = array(
        '' => 'Выберите фон',
        'L' => 'Светлый',
        'D' => 'Темный'
    );

    public $positions = array(
        'L' => 'Слева картинка',
        'R' => 'Справа картинка',
        'B' => 'По центру картинка',
        'S' => 'Слайдер',
        'C' => 'Карусель',
        'P' => 'Карусель c preview',
        'V' => 'Видео'
    );

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

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

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

    }

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

    }

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

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

    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;
    }



}