<?php

namespace Hura8\Components\Deal\Model;

use Hura8\Interfaces\AppResponse;
use Hura8\System\Model\aEntityBaseModel;
use Hura8\System\Security\DataValidator;
use Hura8\System\TimeManager;

class DealModel extends aEntityBaseModel
{

    protected $tb_collection_item = "tb_deal_collection_item";

    public function __construct()
    {
        parent::__construct('deal');
    }


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


    public function getAllAutoRenewableDeal() {
        $query = $this->db->runQuery(
            "SELECT `id`, `from_time`, `to_time` FROM `". $this->tb_entity ."`
				    WHERE `to_time` < '".CURRENT_TIME."' AND `to_time` > 0 AND `auto_renew` = 1 "
        );

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

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

        $where_clause = [];
        $bind_types = [];
        $bind_values = [];

        $limit_by_time = false;
        $limit_by_time_condition = '';

        // get deal by start time
        // require format: YY-mm-dd h:m:i or YY-mm-dd h:m or timestamp
        $datetime_pattern = '/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}\s[0-9]{1,2}:[0-9]{1,2}(:[0-9]{1,2})?$/i';

        if(isset($filter_condition['start_time']) && $filter_condition['start_time'] ) {
            $limit_by_time = true;
            if(preg_match($datetime_pattern, trim($filter_condition['start_time']))) {
                $check_time = strtotime($filter_condition['start_time']);
            }else{
                $check_time = intval($filter_condition['start_time']);
            }

            $limit_by_time_condition .= " AND `from_time` >= '".$check_time."' ";

            $bind_types[] = 'd';
            $bind_values[] = $check_time;
        }

        // get deal by end time
        // require format: YY-mm-dd h:m:i or YY-mm-dd h:m or timestamp
        if(isset($filter_condition['end_time']) && $filter_condition['end_time'] ) {
            $limit_by_time = true;
            if(preg_match($datetime_pattern, trim($filter_condition['end_time']))) {
                $check_time = strtotime($filter_condition['end_time']);
            }else{
                $check_time = intval($filter_condition['end_time']);
            }

            $limit_by_time_condition .= " AND `to_time` <= '".$check_time."' ";
            $bind_types[] = 'd';
            $bind_values[] = $check_time;
        }

        if($limit_by_time) {
            $where_clause[] = " AND `status`= 1 ".$limit_by_time_condition;
        }

        //type expire
        if(isset($filter_condition['type']) && $filter_condition['type'] == 'expire' ) {
            $where_clause[] = "AND `status`= 1 AND `to_time` < ? ";
            $bind_types[] = 'd';
            $bind_values[] = CURRENT_TIME;
        }

        //type active: might not have begun yet
        if(isset($filter_condition['type']) && $filter_condition['type'] == 'active' && !$limit_by_time ) {
            $where_clause[] = " AND `status` = 1 AND `to_time` >= ? ";
            $bind_types[] = 'd';
            $bind_values[] = CURRENT_TIME;
        }

        // Đang bắt đầu
        if(isset($filter_condition['type']) && $filter_condition['type'] == 'started' && !$limit_by_time ) {
            $where_clause[] = " AND `status` = 1 AND `to_time` >= ? AND from_time < ? ";
            $bind_types[] = 'd';
            $bind_values[] = CURRENT_TIME;
            $bind_types[] = 'd';
            $bind_values[] = CURRENT_TIME;
        }

        // Chưa bắt đầu
        if(isset($filter_condition['type']) && $filter_condition['type'] == 'coming' && !$limit_by_time ) {
            $where_clause[] = " AND `status` = 1 AND `from_time` >= ? ";
            $bind_types[] = 'd';
            $bind_values[] = CURRENT_TIME;
        }

        //deal collection
        if(isset($filter_condition['collection_id']) && $filter_condition['collection_id'] > 0) {
            $where_clause[] = " AND `id` IN (  SELECT `deal_id` FROM `".$this->tb_collection_item."` WHERE `collection_id` = ? ) ";
            $bind_types[] = 'd';
            $bind_values[] = $filter_condition['collection_id'];
        }

        // exclude from collection
        if(isset($filter_condition['add_to_collection']) && $filter_condition['add_to_collection'] > 0) {
            $where_clause[] = " AND `id` NOT IN (  SELECT `deal_id` FROM `".$this->tb_collection_item."`  WHERE `collection_id` = ? ) ";
            $bind_types[] = 'd';
            $bind_values[] = $filter_condition['add_to_collection'];
        }

        // by word filter
        $filter = $filter_condition['filter'] ?? '';
        switch ($filter) {
            case "not-started": // Chưa bắt đầu
                $where_clause[] = " AND ( ? - `from_time` ) < 0 ";
                $bind_types[] = 'd';
                $bind_values[] = CURRENT_TIME;
                break;

            case "started": // Đang bắt đầu
                $where_clause[] = " AND ( ? - `from_time` ) > 0 AND ( `to_time` - ?) > 0 ";
                $bind_types[] = 'd';
                $bind_types[] = 'd';
                $bind_values[] = CURRENT_TIME;
                $bind_values[] = CURRENT_TIME;
                break;

            case "ended": // Hết thời gian
                $where_clause[] = " AND (`to_time` - ?) < 0  ";
                $bind_types[] = 'd';
                $bind_values[] = CURRENT_TIME;
                break;

            case "hidden": // Ẩn hiển thị
                $where_clause[] = " AND `status` = 0 ";
                break;

            case "featured": // Đang nổi bật
                $where_clause[] = " AND `is_featured` =  1 ";
                break;
        }


        return [
            join(" ", $where_clause),
            $bind_types,
            $bind_values
        ];
    }


    protected function formatItemInList(array $item_info): array
    {
        $copy = $item_info;

        $copy['deal_time_happen'] = CURRENT_TIME - $item_info['from_time'];
        $copy['deal_time_left']   = $item_info['to_time'] - CURRENT_TIME;
        $copy['is_start']         = (CURRENT_TIME - $item_info['from_time'] > 0) ? 1 : 0;
        $copy['is_end']           = ($item_info['to_time'] - CURRENT_TIME > 0) ? 0 : 1;

        return $copy;
    }

    protected function formatItemInfo(array $item_info): array
    {
        $copy = $item_info;

        $copy['deal_time_happen'] = CURRENT_TIME - $item_info['from_time'];
        $copy['deal_time_left']   = $item_info['to_time'] - CURRENT_TIME;
        $copy['is_start']         = (CURRENT_TIME - $item_info['from_time'] > 0) ? 1 : 0;
        $copy['is_end']           = ($item_info['to_time'] - CURRENT_TIME > 0) ? 0 : 1;

        return $copy;
    }



}
