<?php

namespace Hura8\Components\Product\Model;

use Hura8\Interfaces\AppResponse;
use Hura8\System\Model\aEntityBaseModel;
use Hura8\Interfaces\EntityType;
use Hura8\System\Security\DataClean;
use Hura8\System\Security\DataType;


class ProductAttributeValueModel extends aEntityBaseModel
{

    const MAX_VALUE_PER_ATTRIBUTE = 100; // one attribute should not have more that this number of values

    protected $attribute_id = 0;

    protected $tb_attribute             = 'tb_attribute';
    protected $tb_product_attribute = 'tb_product_attribute';

    public function __construct($attribute_id) {
        parent::__construct(EntityType::PRODUCT_ATTRIBUTE_VALUE);
        $this->attribute_id = $attribute_id;
    }


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


    public function getProductAttributes($product_id) {

        $query = $this->db->runQuery(
            "SELECT `attr_id`, `attr_value_id` FROM `".$this->tb_product_attribute."` WHERE `pro_id` = ? ",
            ['d'], [ $product_id]
        );

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


    protected function getAttributeValueCount() {
        $query = $this->db->runQuery(
            "SELECT `value_count` FROM `".$this->tb_attribute."`  WHERE `id` = ? LIMIT 1  ",
            ['d'], [$this->attribute_id]
        );

        if($info = $this->db->fetchAssoc($query)) {
            return $info['value_count'];
        }

        return 0;
    }

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

        $catCondition = [" AND `attribute_id` = ? "];
        $bind_types = ["d"];
        $bind_values = [$this->attribute_id];


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


    public function getInfoByCode($filter_code)
    {
        $query = $this->db->runQuery(
            "SELECT * FROM `".$this->tb_entity."` WHERE `attribute_id` = ? AND `filter_code` = ? LIMIT 1",
            ['d', 's'], [$this->attribute_id, $filter_code ]
        );

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


}
