<?php

namespace Mnv\Models;

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

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

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

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

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

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

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


    public function __construct(Request $request)
    {
        $this->id       = $request->get('id');
        $this->data     = $request->get('dealer', '');
        $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']);

    }

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

    }

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

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


}