<?php

namespace Hura8\Components\Product\Model;

use Hura8\Components\Product\AdminController\AProductHotController;
use Hura8\Database\iConnectDB;
use Hura8\System\Config;


class ProductHotModel
{

    /* @var $db iConnectDB */
    protected $db;

    protected $tb_product = "tb_product";
    protected $tb_product_hot = "tb_product_hot";

    public function __construct() {
        $this->db = get_db();
    }

    public function updateProductHot($pro_id, array $new_types) {

        $this->db->runQuery("DELETE FROM " . $this->tb_product_hot . " WHERE `pro_id` = ? ", ['d'], [ $pro_id ]);
        $this->db->update(
            $this->tb_product,
            [
                "hot_type" => '',
            ],
            [
                'id' => $pro_id,
            ]
        );


        $config_hottype = Config::getProductHotTypeList();

        //insert what good
        $batch_insert   = array();
        $accepted_types = array();
        foreach ($new_types as $hot_type) {
            if (!isset($config_hottype[$hot_type])) continue;

            $batch_insert[] = [
                "pro_id" => $pro_id,
                "hot_type" => $hot_type,
            ];

            $accepted_types[] = $hot_type;
        }

        if (sizeof($batch_insert)) {

            $this->db->bulk_insert($this->tb_product_hot, $batch_insert );

            $this->db->update(
                $this->tb_product,
                [
                    "hot_type" => join(",", $accepted_types),
                ],
                [
                    "id" => $pro_id,
                ]
            );
        }

        return true;
    }


    public function getProductHot(array $product_ids) {

        if(!sizeof($product_ids)){
            return [];
        }

        list($parameterized_ids, $bind_types) = create_bind_sql_parameter_from_value_list($product_ids, 'int');

        $query = $this->db->runQuery(
            "SELECT `pro_id`, `hot_type` FROM ".$this->tb_product_hot." WHERE `pro_id` IN (".$parameterized_ids.") ",
            $bind_types,
            $product_ids
        );

        $result = [];
        foreach ( $this->db->fetchAll($query) as $rs ) {
            $result[$rs['pro_id']][] = $rs['hot_type'];
        }

        return $result;
    }


}
