<?php

namespace Mnv\Models;

use Mnv\Core\Model;
use Mnv\Core\Test\Logger;
use Mnv\Http\Request;
use Mnv\Models\Exceptions\NoContentException;
use Mnv\Models\Exceptions\NotInsertContentException;
use Mnv\Models\Exceptions\NotUpdateContentException;
use Mnv\Models\Exceptions\NotContentApproveException;


/**
 * Class Project
 * @package Mnv\Models\Contents
 */
class Station extends Model
{
    /** @var string */
    protected string $table = 'stations';

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

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

    /** @var string  */
    protected string $orderBy = 'publishedOn DESC';

    /** @var string  */
    protected string $columns = 'stationId, sectionId, countryId, title, alias, url, publishedOn, orderBy, isFeatured, status, typeContent, summary';

    public $field;

    /** @var array $image */
    public $image = [];

    /** @var int $imageId */
    public int $imageId;

    public string $typeContent;

    public $stationIds;


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

    /** фильтрация / сортировка */
    protected function sorting(): void
    {
        global $SECTIONS;

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

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

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


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

        if (!empty($this->filter['section']) && !empty($SECTIONS[$this->filter['section']])) {
            $sectionIds = array($this->filter['section']);
            if (!empty($SECTIONS[$this->filter['section']]['allChildren'])) {
                $sectionIds = array_merge($sectionIds, $SECTIONS[$this->filter['section']]['allChildren']);
            }
            connect()->in('sectionId', $sectionIds);
        }


    }

    /** Получение всех статей */
    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;
    }

    /**
     * @throws NotUpdateContentException
     * @throws NotInsertContentException
     */
    public function prepare(array $data, int $managerId): bool
    {

        $data['modifiedBy']   = $managerId;
        $data['modifiedOn']   = gmdate('Y-m-d H:i:s');
        $data['publishedOn']  = adjustTime(date('Y-m-d H:i:s', strtotime($data['publishedOn'])),  true);

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

            $data['addedBy'] = $managerId;
            $data['addedOn'] = gmdate('Y-m-d H:i:s');
            $data['orderBy'] = connect()->table($this->table)->max('orderBy')->where('typeContent', $data['typeContent'])->getValue() + 1;
            if ($this->id = $this->insert($data)) {
                return true;
            }

            throw new NotInsertContentException();
        }
        else {

            if ($this->update($data)) {
                return true;
            }

            throw new NotUpdateContentException();
        }

    }


    /** Удаление контента */
    public function remove(): bool
    {
        if (parent::remove()) {
            connect()->table($this->table_image)->where($this->primaryKey, $this->id)->delete();

            return true;
        }

        return false;
    }

    /**
     * Обновление статуса
     *
     * @return bool
     * @throws NoContentException
     * @throws NotContentApproveException
     */
    public function approve(): bool
    {
        if (!empty($this->id) && $this->data = $this->get()) {
            if (connect()->table($this->table)->where($this->primaryKey,$this->id)->update(['status' => 'V'])) {
                return true;
            }
            throw new NotContentApproveException();
        }

        throw new NoContentException();
    }

    /**
     * Сортировка контента
     *
     * @param $ids
     * @param $articleIds
     */
    public function reorder($ids, $articleIds): void
    {
        foreach ($articleIds as $i => $articleId) {
            connect()->table($this->table)->where($this->primaryKey, $ids[$i])->update(['orderBy' => $articleId]);
        }
    }

    /**
     * Групповые действия
     * @param $group_action
     */
    public function group($group_action): void
    {
        if ($group_action === 'status') {
            if ($this->data = $this->get()) {
                $contentUpdate['status'] = ($this->data['status'] === 'V') ? 'H' : 'V';
                $this->statusContent($contentUpdate);
            }

        } else if ($group_action === 'remove') {
            if ($this->data = $this->get()) {
                $this->removeContent();
            }
        }
    }

    /**
     * Обновление статуса контента
     *
     * @param $contentUpdate
     * @return bool
     */
    public function statusContent($contentUpdate): bool
    {
        if (connect()->table($this->table)->where($this->primaryKey, $this->id)->update($contentUpdate)) {
            return true;
        }

        return false;
    }

    /** Групповое удаление контента */
    public function removeContent(): bool
    {
        /** Удаление контента и удаление записей из базы данных прикрепленных картинок и комментариев к этому контенту */
        if (connect()->table($this->table)->where($this->primaryKey, $this->id)->delete()) {
            connect()->table($this->table_image)->where($this->primaryKey, $this->id)->delete();

            return true;
        }

        return false;
    }



}