<?php

namespace Hura8\Components\Article\Model;

use Hura8\System\Controller\UrlManagerController;
use Hura8\System\Model\aEntityBaseModel;
use Hura8\System\ModuleManager;
use Hura8\Interfaces\iEntityModel;
use Hura8\Interfaces\EntityType;


class ArticleModel extends aEntityBaseModel implements iEntityModel
{

    static $url_type                    = "article:detail";

    protected $tb_article_info          = "tb_article_info";
    protected $tb_article_per_category  = 'tb_article_per_category';

    public function __construct() {
        parent::__construct(
            EntityType::ARTICLE,
            "",
            new ArticleSearchModel()
        );
    }

    protected function extendedFilterOptions() : array
    {
        return [
            // empty for now
        ];
    }


    public function getFullInfo($id) : ?array
    {
        $query = $this->db->runQuery(
            "SELECT * FROM `".$this->tb_entity."` basic, `".$this->tb_article_info."` info 
                    WHERE basic.`id` = info.`article_id` AND basic.id = ? 
                    LIMIT 1 ",
            ['d'], [$id]
        );

        if( $item_info = $this->db->fetchAssoc($query)){
            return $item_info;
        }

        return null;
    }


    protected function _buildQueryConditionExtend(array $filter_condition) : ?array
    {
        /*$condition = array(
           "category" => getRequestInt("category"),
           "no_image" => 0,//1
       );*/

        $catCondition = [];
        $bind_types = [];
        $bind_values = [];

        //Tim danh muc
        if(isset($filter_condition["category"]) && $filter_condition["category"]) {

            $objArticleCategoryModel = new ArticleCategoryModel();
            $category_info = $objArticleCategoryModel->getInfo($filter_condition["category"]);

            if($category_info) {
                if($category_info['is_parent']) {
                    $catCondition[] = " AND `id` IN (SELECT `item_id` FROM `".$this->tb_article_per_category."` WHERE `category_id` IN (".$category_info['child_ids'].") ) ";
                    //$bind_types[] = 'd';
                    //$bind_values[] = $filter_condition["category"];
                }else{
                    $catCondition[] = " AND `id` IN (SELECT `item_id` FROM `".$this->tb_article_per_category."` WHERE `category_id` = ? ) ";
                    $bind_types[] = 'd';
                    $bind_values[] = $filter_condition["category"];
                }
            }

        }


        return array( join(" ", $catCondition), $bind_types, $bind_values);
    }


    protected function addArticleToCategory($item_id, array $category_list_id) {
        $this->db->runQuery("DELETE FROM `".$this->tb_article_per_category."` WHERE `item_id` = ? ", ['d'], [$item_id]);

        $bulk_inserts = [];
        foreach($category_list_id as $cat_id) {
            if (! $cat_id) continue;

            $bulk_inserts[] = [
                'category_id' => $cat_id,
                'item_id' => $item_id,
                'status' => 1,
                'create_time' => CURRENT_TIME,
            ];
        }

        if(sizeof($bulk_inserts)) {
            $this->db->bulk_insert($this->tb_article_per_category, $bulk_inserts);
        }

        // update counter
        $objArticleCategoryModel = new ArticleCategoryModel();
        foreach($category_list_id as $cat_id) {
            $objArticleCategoryModel->updateItemCount($cat_id);
        }

    }


    public function updateUrl($id, $url_index): bool
    {

        $module_routing = ModuleManager::getModuleRouting("article");
        $request_path_config = isset($module_routing["detail"]) ? $module_routing["detail"]['url_manager']['request_path'] : '';

        if(!$request_path_config) {
            return false;
        }

        $request_path  = UrlManagerController::translateRequestPathConfig($request_path_config, $id, $url_index);
        $id_path       = UrlManagerController::createIdPath("article", "detail", $id);

        $objUrlManager = new UrlManagerController();
        $new_request_path = $objUrlManager->createUrl("article:detail", $request_path,  $id_path, 0);

        if($new_request_path) {
            $this->db->update(
                $this->tb_entity,
                [
                    'request_path' => $new_request_path,
                ],
                [
                    'id' => $id,
                ]
            );
        }

        return true;
    }



}
