<?php

namespace Hura8\Components\Marketing\Model;

use Hura8\Components\Product\Model\ProductModel;
use Hura8\Interfaces\AppResponse;
use Hura8\Interfaces\EntityType;
use Hura8\System\IDGenerator;
use Hura8\System\Model\aEntityBaseModel;
use Hura8\System\Security\DataClean;
use Hura8\System\Security\DataType;
use Hura8\System\TimeManager;


class CouponModel extends aEntityBaseModel
{

    protected $tb_coupon_product = "tb_coupon_product";

    public function __construct() {
        parent::__construct(EntityType::COUPON);
    }


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


    public function getTotalProduct($coupon_id, array $condition = [])
    {
        $query = $this->db->runQuery(
            " SELECT COUNT(*) as total FROM `".$this->tb_coupon_product."` WHERE `coupon_id` = ? ",
            ['d'], [$coupon_id]
        );

        $total = 0;
        if ($rs = $this->db->fetchAssoc($query)) {
            $total = $rs['total'];
        }

        return $total;
    }


    public function getListProduct($coupon_id, array $condition = [])
    {
        $numPerPage = (isset($condition['numPerPage']) && $condition['numPerPage'] > 0 ) ? intval($condition['numPerPage']) : 20 ;
        $page = (isset($condition['page']) && $condition['page'] > 0 ) ? intval($condition['page']) : 1 ;
        $order_by = " `ordering` DESC, `id` DESC";

        $query = $this->db->runQuery(
            "SELECT `product_id` FROM ".$this->tb_coupon_product." WHERE `coupon_id` = ?  
                    ORDER BY ".$order_by."
                    LIMIT  ".(($page-1) * $numPerPage).", ".$numPerPage ,
            ['d'], [$coupon_id]
        ) ;

        $item_list = array();
        $counter = ($page-1) * $numPerPage;
        foreach ( $this->db->fetchAll($query) as $item ) {
            $counter += 1;

            $item_list[$item['product_id']] = [
                'counter' => $counter,
            ];
        }

        $objProductModel = new ProductModel();
        $product_list_info = $objProductModel->getListByIds(array_keys($item_list));

        // final list
        $final_list = [];
        foreach ($item_list as $_pro_id => $_pro_info_in_collection) {
            $pro_basic = $product_list_info[$_pro_id] ?? null;
            if($pro_basic) {
                $final_list[] = array_merge($pro_basic, $_pro_info_in_collection);
            }
        }

        return $final_list;
    }


    protected function _buildQueryConditionExtend(array $filter_condition) : ?array
    {
        /*$condition = array(
                "q" => getRequest("q", ''),
                "featured" => (int) getRequest("featured"),
                "status" => (int) getRequest("status"),
            );*/

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


        if(isset($filter_condition["letter"]) && strlen($filter_condition["letter"]) == 1){
            $catCondition[] = " AND `letter` = ?  ";
            $bind_types[] = 's';
            $bind_values[] = $filter_condition["letter"];
        }

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


    protected function createUniqueCode($current_item_id, $wanted_code = ''){
        if(!$wanted_code) $wanted_code = IDGenerator::createStringId(10);

        $clean_code = DataClean::makeInputSafe($wanted_code, DataType::ID);
        $clean_code = strtoupper($clean_code);

        //if exist and belong other id, create a new one
        $query = $this->db->runQuery("SELECT `id` FROM `".$this->tb_entity."` WHERE `code` = ? LIMIT 1 ", ['s'], [$clean_code]) ;
        if($info = $this->db->fetchAssoc($query)){
            if($info['id'] != $current_item_id) {
                $new_code = IDGenerator::createStringId(6);
                return $this->createUniqueCode($current_item_id, $new_code);
            }
        }

        return $clean_code;
    }


}
