<?php

namespace Hura8\Components\Product\Model;

use Hura8\Components\Product\Controller\ProductController;
use Hura8\Interfaces\AppResponse;
use Hura8\System\Model\aEntityBaseModel;
use Hura8\System\Security\DataClean;
use Hura8\System\Security\DataType;


class ProductVariantModel extends aEntityBaseModel
{

    protected $product_id = 0;

    protected $tb_product = "tb_product";
    protected $tb_variant_option_sample = "tb_product_variant_option_sample";

    public function __construct($product_id) {
        parent::__construct('product_variant');
        $this->product_id = $product_id;
    }


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


    public function getProductVariantOption($product_id){
        $query = $this->db->runQuery("SELECT `variant_option` FROM `".$this->tb_product."` WHERE `id` = ? LIMIT 1", ['d'], [ $product_id ]) ;

        if($rs = $this->db->fetchAssoc($query)) {
            return ($rs['variant_option']) ? \json_decode($rs['variant_option'], true) : null;
        }

        return null;
    }


    //use a product's variant-option to create a sample, so next product can select without recreate from beginning
    public function createVariantOptionSample($use_from_pro_id, $sample_title) {

        if( !$use_from_pro_id || strlen($sample_title) < 3 ) return false;

        $pro_variant_option = $this->getProductVariantOption($use_from_pro_id);
        if(!$pro_variant_option) {
            return false;
        }

        $pro_variant_option_index = md5(\json_encode($pro_variant_option));

        $check_duplicate = $this->db->runQuery(
            "SELECT `id` FROM ".$this->tb_variant_option_sample." WHERE `variant_option_index` = ? LIMIT 1 ",
            ['s'], [ $pro_variant_option_index ]
        );

        if($this->db->fetchAssoc($check_duplicate)) {
            return false;
        }

        // ok to save
        $this->db->insert(
            $this->tb_variant_option_sample,
            [
                "title" => $sample_title,
                "variant_option" => \json_encode($pro_variant_option),
                "variant_option_index" => $pro_variant_option_index,
                "create_time" => CURRENT_TIME,
            ]
        );

        return true;
    }

    public function getVariantOptionSample() {
        $query = $this->db->runQuery("SELECT * FROM ".$this->tb_variant_option_sample." ORDER BY `id` DESC LIMIT 500 ");

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

    public function getProductVariantPriceRange(){
        $result = [
            "sale_price" => [
                "min" => 0,
                "max" => 0,
            ],
            "market_price" => [
                "min" => 0,
                "max" => 0,
            ],
        ];

        $query = $this->db->runQuery(
            " SELECT `sale_price`, `market_price`, `extend` FROM `".$this->tb_entity."` WHERE `product_id` = ? ",
            ['d'], [$this->product_id]
        );

        foreach ( $this->db->fetchAll($query) as $info) {

            // find min
            if($info["sale_price"] > 0 && ( $info["sale_price"] < $result["sale_price"]["min"] || $result["sale_price"]["min"] == 0 ) ) {
                $result["sale_price"]["min"] = $info["sale_price"];
            }

            // find max
            if($info["sale_price"] > 0 && $info["sale_price"] > $result["sale_price"]["max"] ) {
                $result["sale_price"]["max"] = $info["sale_price"];
            }

            // market_price
            $market_price = $info["market_price"];
            if($info['extend']) {
                $extend = unserialize($info['extend']);
                if(isset($extend['market_price'])) $market_price = clean_price($extend['market_price'], "vnd");
            }

            if($market_price > 0 && ( $market_price < $result["market_price"]["min"] || $result["market_price"]["min"] == 0 ) ) {
                $result["market_price"]["min"] = $market_price;
            }

            if($market_price > 0 && $market_price > $result["market_price"]["max"] ) {
                $result["market_price"]["max"] = $market_price;
            }
        }

        return $result;
    }


    protected function _buildQueryConditionExtend(array $filter_condition) : ?array
    {
        $where_condition = " AND `product_id` = ? ";
        $bind_types = ["d"];
        $bind_values = [$this->product_id];

        return [
            $where_condition,
            $bind_types,
            $bind_values
        ];
    }

    protected function _buildQueryOrderBy($sort_by = "new")
    {
        return " `ordering` DESC, `id` DESC ";
    }

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

        if($item_info['attribute'])  $info['attribute'] = \json_decode($item_info['attribute'], true);

        return $info;
    }

    protected function updateProductVariantCount() {
        $this->db->runQuery(
            "UPDATE  ".$this->tb_product." SET 
                      `config_count` = ( SELECT COUNT(*) AS total FROM  `".$this->tb_entity."` WHERE `product_id` = ?  AND `status` = 1 ) 
                   WHERE `id` = ? ",
            ['d', 'd'], [ $this->product_id, $this->product_id]
        ) ;
    }

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

        if($info['attribute'])  $info['attribute'] = \json_decode($info['attribute'], true);

        return $info;
    }


}
