<?php

namespace Hura8\System\Model;

use Hura8\Interfaces\AppResponse;
use Hura8\Interfaces\TableName;

class UrlModel extends aEntityBaseModel
{

    private  $tb_url         = TableName::URL; ///
    private  $tb_url_meta    = TableName::URL_META; ///

    public function __construct() {
        parent::__construct("url");
    }


    public function getUrlByIdPath($id_path) {
        $query = $this->db->runQuery(
            "SELECT * FROM `".$this->tb_url."` WHERE `id_path` = ?  LIMIT 1 ",
            ['s'], [ $id_path ]
        );

        return $this->db->fetchAssoc($query);
    }


    public function deleteByType(string $url_type) {
        $this->db->runQuery(
            "DELETE FROM `".$this->tb_url."` WHERE `url_type` = ?  ",
            ['s'], [ $url_type ]
        );
    }


    public function deleteByRequestPath($request_path) {
        $this->db->runQuery(
            "DELETE FROM `".$this->tb_url."` WHERE `request_path_index` = ?  LIMIT 1 ",
            ['s'], [ md5($request_path) ]
        );
    }


    public function getUrlByRequestPath($request_path) {
        $query = $this->db->runQuery(
            "SELECT * FROM `".$this->tb_url."` WHERE `request_path_index` = ?  LIMIT 1 ",
            ['s'], [ md5($request_path) ]
        );

        return $this->db->fetchAssoc($query);
    }


    //02-12-2015
    public function getUrlMetaInfo($request_path){
        return $this->db->getItemInfo($this->tb_url_meta, md5($request_path), 'request_path_index');
    }


    public function getUrlMetaInfoById($id){
        return $this->db->getItemInfo($this->tb_url_meta, $id, 'id');
    }


    public function getEmptyUrlMetaInfo() {
        return array(
            'id'            => 0,
            'request_path'  => '',
            'h1'            => '',
            'meta_title'    => '',
            'meta_keyword'  => '',
            'meta_description' => '',
            'og_image'       => '',
            'summary'       => '',
            'description'   => '',
        );
    }


    //02-12-2015
    public function createUrlMeta(array $info){

        //prevent duplication
        if($this->getUrlMetaInfo($info['request_path'])) return false;

        if(!defined("ADMIN_NAME")) define("ADMIN_NAME", "system");

        $copy = $info;
        $copy['request_path_index'] = md5($info['request_path']);
        $copy['last_update']     = CURRENT_TIME;
        $copy['last_update_by']  = ADMIN_NAME;

        return $this->db->insert(
            $this->tb_url_meta ,
            $copy
        );
    }


    public function updateUrlMeta($id, array $info){
        $copy = $info;
        $copy['last_update']    = CURRENT_TIME;
        $copy['last_update_by'] = ADMIN_NAME;

        return $this->db->update(
            $this->tb_url_meta ,
            $copy,
            [
                'id' => $id,
            ]
        );
    }


    protected function _buildQueryConditionExtend(array $condition): ?array
    {

        /*$condition = array(
            "letter" => "",
        );*/

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

        //loc theo is_redirect
        if(isset($condition["request_path"]) && $condition["request_path"]) {
            $path = preg_replace("/[^a-z0-9_\.\/\-]/i", '', $condition["request_path"]);
            if($path) $catCondition[] = " AND `request_path` LIKE '%".$path."%' ";
        }

        //loc theo is_redirect
        if(isset($condition["is_redirect"]) && $condition["is_redirect"]) {
            if($condition["is_redirect"] == 1) $catCondition[] = " AND `url_type` = 'redirect' ";
            else if($condition["is_redirect"] == -1) $catCondition[] = " AND `url_type` != 'redirect' ";
        }

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


    protected function beforeCreateItem(array $input_info): AppResponse
    {
        $request_path = $input_info['request_path'] ?? '';
        $id_path      = $input_info['id_path'] ?? '';

        if(!$request_path || $this->getUrlByRequestPath($request_path)) {
            return new AppResponse('error', "request_path exist");
        }

        if($id_path && $this->getUrlByIdPath($id_path)) {
            return new AppResponse('error', "id path exist");
        }

        $admin_name = (defined("ADMIN_NAME")) ? ADMIN_NAME : "system";

        $info = $input_info;

        $info['request_path_index'] = md5($info['request_path']);

        $info['create_time'] = CURRENT_TIME;
        $info['create_by'] = $admin_name;

        $info['last_update'] = CURRENT_TIME;
        $info['last_update_by'] = $admin_name;

        return new AppResponse('ok', null, $info);
    }


    protected function afterCreateItem($new_item_id, $new_item_info)
    {
        // TODO: Implement afterCreateItem() method.
    }


    protected function beforeUpdateItem($item_id, $current_item_info, $new_input_info): AppResponse
    {
        $info = $new_input_info;
        unset($info['id_path']);

        if(isset($info['request_path']) && $info['request_path']) {
            $info['request_path_index'] = md5($info['request_path']);
        }

        $info['last_update'] = CURRENT_TIME;
        $info['last_update_by'] = ADMIN_NAME;

        return new AppResponse('ok', null, $info);
    }


    protected function afterUpdateItem($item_id, $old_item_info, $new_item_info)
    {
        // TODO: Implement afterUpdateItem() method.
    }


    protected function beforeDeleteItem($item_id, $item_info): AppResponse
    {
        return new AppResponse('ok');
    }


    protected function afterDeleteItem($item_id, $item_info)
    {
        // TODO: Implement afterDeleteItem() method.
    }


    protected function extendedFilterOptions(): array
    {
        return [];
    }
}
