<?php

namespace CCDN\Helpers\Entities;

use CCDN\Helpers\CustomFields;
use CCDN\Helpers\DB\Model;
use mysqli_result;

/**
 * Class Post entity
 *
 * @property-read int $id
 * @property string $autor
 * @property string $date
 * @property string $short_story
 * @property string $full_story
 * @property string $xfields
 * @property string $title
 * @property string $descr
 * @property string $keywords
 * @property string $category
 * @property string $alt_name
 * @property string $comm_num
 * @property string $allow_comm
 * @property string $allow_main
 * @property string $approve
 * @property string $fixed
 * @property string $allow_br
 * @property string $symbol
 * @property string $tags
 * @property string $metatitle
 *
 * @package CCDN\Helpers\DB
 */
class Post extends Model
{

    use CustomFields;

    /**
     * @var array
     */
    private $fieldFilter = [
        'id',
        'autor',
        'date',
        'short_story',
        'full_story',
        'xfields',
        'title',
        'descr',
        'keywords',
        'category',
        'alt_name',
        'comm_num',
        'allow_comm',
        'allow_main',
        'approve',
        'fixed',
        'allow_br',
        'symbol',
        'metatitle',
    ];


    public function __construct($post = [])
    {
        parent::__construct();
        foreach ($post as $field => $value) {
            if (in_array($field, $this->fieldFilter, true)) {
                $this->$field = $value;
            }
        }

        if (isset($this->id)) {
            $this->id = (int)$this->id;
        }

        if (isset($this->date) && is_numeric($this->date)) {
            $this->date = date('Y-m-d H:i:s', $this->date);
        }

        $this->customFields = $this->xFieldsToArray();
    }

    /**
     * Update post
     *
     * @return bool|mysqli_result
     */
    public function updatePost()
    {
        $this->xfields = $this->convertToDLEXFieldsFormat();
        $this->title = $this->getDb()->safesql($this->title);
        $this->alt_name = $this->getDb()->safesql($this->alt_name);
        $this->metatitle = $this->getDb()->safesql($this->metatitle);

        if (isset($this->full_story)) {
            $this->full_story = $this->getDb()->safesql($this->full_story);
        }

        if (isset($this->short_story)) {
            $this->short_story = $this->getDb()->safesql($this->short_story);
        }

        $this->alt_name = str_replace("{$this->id}-", '', $this->alt_name);
        $condition = $this->update("{$this->getPrefix()}_post", $this->toArray(), ['id' => $this->id]);
        if ($condition) {
            clear_cache(['news_', 'related_', 'tagscloud_', 'archives_', 'calendar_', 'topnews_', 'informer_', 'rss', 'stats']);
        }
        return $condition;
    }

    public function toArray()
    {
        $array = [];
        foreach ($this as $field => $value) {
            if (in_array($field, $this->fieldFilter, true)) {
                $array[$field] = $value;
            }
        }

        return $array;
    }

    /**
     * Update post
     *
     * @param array $categoryPost
     * @return bool|mysqli_result
     */
    public function insertPost($categoryPost)
    {
        $this->id = null;
        global $member_id;
        $this->xfields = $this->convertToDLEXFieldsFormat();
        $this->title = $this->getDb()->safesql($this->title);
        $this->alt_name = $this->getDb()->safesql($this->alt_name);
        $this->metatitle = $this->getDb()->safesql($this->metatitle);

        if (isset($this->full_story)) {
            $this->full_story = $this->getDb()->safesql($this->full_story);
        }

        if (isset($this->short_story)) {
            $this->short_story = $this->getDb()->safesql($this->short_story);
        }

        $condition = $this->insert($this->getPrefix() . '_post', $this->toArray());

        $this->id = $this->getDb()->insert_id();

        $defaultExtrasField = [
            'news_id' => $this->id,
            'news_read' => '0',
            'allow_rate' => '1',
            'rating' => '0',
            'vote_num' => '0',
            'votes' => '0',
            'view_edit' => '0',
            'disable_index' => '0',
            'related_ids' => '',
            'access' => '',
            'editdate' => '0',
            'editor' => '',
            'reason' => '',
            'user_id' => $member_id['user_id'],
            'disable_search' => '0',
            'need_pass' => '0',
            'allow_rss' => '1',
            'allow_rss_turbo' => '1',
            'allow_rss_dzen' => '1',
        ];

        if ($condition) {
            clear_cache(['news_', 'related_', 'tagscloud_', 'archives_', 'calendar_', 'topnews_', 'informer_', 'rss', 'stats']);
            $extrasFields = $this->select("SHOW COLUMNS FROM {$this->getPrefix()}_post_extras;", true);
            $extrasFields = array_column($extrasFields, 'Field');
            foreach ($defaultExtrasField as $key => $value) {
                if (!in_array($key, $extrasFields, true)) {
                    unset($defaultExtrasField[$key]);
                }
            }
            $this->insert($this->getPrefix() . '_post_extras', $defaultExtrasField);

            global $config;
            if ((float)$config['version_id'] > 13.1) {
                $categoryPost = array_filter($categoryPost);
                foreach ($categoryPost as $catId) {
                    $this->insert($this->getPrefix() . '_post_extras_cats', [
                        'news_id' => $this->id,
                        'cat_id' => $catId,
                    ]);
                }
            }
        }

        return $condition;
    }

    /**
     * @param array $categoryPost
     */
    public function updateCategories($categoryPost)
    {
        $categoryPost = array_filter($categoryPost);
        $this->category = implode(',', $categoryPost);
        global $config;
        if ((float)$config['version_id'] >= 13.1) {
            $this->delete($this->getPrefix() . '_post_extras_cats', [
                'news_id' => $this->id
            ]);
            foreach ($categoryPost as $catId) {
                $this->insert($this->getPrefix() . '_post_extras_cats', [
                    'news_id' => $this->id,
                    'cat_id' => $catId,
                ]);
            }
        }
    }

    /**
     * @param int|null $postId
     * @return bool
     */
    public function postHasImage($postId = null)
    {

        $postId = $postId !== null ? $postId : $this->id;
        if ($postId === null) {
            return false;
        }
        $images = $this->select("SELECT `images`  FROM `{$this->getPrefix()}_images` WHERE  `news_id` ={$postId}");
        return !empty($images);
    }

    /**
     * @return string
     */
    public function createUlr()
    {
        global $config;

        $category_id = (int)$this->category;

        if ($config['allow_alt_url']) {
            if ($config['seo_type'] === '1' || $config['seo_type'] === '2') {
                if ($category_id && $config['seo_type'] === '2') {
                    $c_url = get_url($category_id);
                    $full_link = "/{$c_url}/{$this->id}-{$this->alt_name}.html";

                } else {
                    $full_link = "/{$this->id}-{$this->alt_name}.html";
                }
            } else {
                $this->date = is_numeric($this->date) ? $this->date : strtotime($this->date);
                $date = date('Y/m/d/', $this->date);
                $full_link = '/' . $date . $this->alt_name . '.html';
            }
        } else {
            $full_link = '/index.php?newsid=' . $this->id;
        }


        return $full_link;
    }

}
