<?php

namespace Hura8\Components\Product\Model;


use Hura8\Interfaces\iEntityCategoryModel;
use Hura8\System\Model\aCategoryBaseModel;
use Hura8\Interfaces\EntityType;


class ProductCategoryModel extends aCategoryBaseModel implements iEntityCategoryModel
{
    static $url_module  = "product";
    static $url_view    = "category";
    static $url_type    = "product:category";

    protected $tb_category_info         = "tb_product_category_info";
    protected $tb_product_per_category  = "tb_product_per_category";
    protected $tb_attribute_per_category = "tb_attribute_per_category";
    protected $tb_attribute_value        = "tb_attribute_value";
    protected $tb_attribute              = "tb_attribute";


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


    public function getAttributeList($catId) {
        $query = $this->db->runQuery("SELECT  
                                                   a.id , 
                                                   a.filter_code , 
                                                   a.title , 
                                                   a.value_count , 
                                                   a.is_filter , 
                                                   c.ordering , 
                                                   c.status , 
                                                   a.is_header
											FROM ".$this->tb_attribute." a
											LEFT JOIN ".$this->tb_attribute_per_category." c ON a.id = c.attr_id
											WHERE c.category_id = ?
											ORDER BY c.ordering desc	
										", ['d'], [ $catId ]) ; // AND isSearch = 1

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


    public function getFullInfo($id) : ?array {
        $query = $this->db->runQuery(
            "SELECT * FROM `".$this->tb_entity."` basic, `".$this->tb_category_info."` info 
                    WHERE basic.`id` = info.`id` AND basic.id = ? 
                    LIMIT 1 ",
            ['d'], [$id]
        );

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

        return null;
    }


    public function getEmptyInfo($addition_field_value = []) : array
    {
        // basic table
        $basic_empty = parent::getEmptyInfo($addition_field_value);

        // info table
        foreach ($this->db->getTableInfo($this->tb_category_info) as $field => $field_info) {
            $basic_empty[$field] = ( in_array($field_info['DATA_TYPE'], ['int', 'float']) ) ? 0 : '' ;
        }

        if(sizeof($addition_field_value)) {
            return array_merge($basic_empty, $addition_field_value);
        }

        return $basic_empty;
    }

}
