<?php

namespace Hura8\Components\Brand\Model;

use Hura8\Interfaces\AppResponse;
use Hura8\System\Config;
use Hura8\System\Controller\UrlManagerController;
use Hura8\System\Model\aEntityBaseModel;
use Hura8\Interfaces\iEntityModel;
use Hura8\Interfaces\EntityType;
use Hura8\Interfaces\TableName;


class BrandModel extends aEntityBaseModel implements iEntityModel
{

    static $url_type  = "brand:detail";

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


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


    public function getGroupByFirstLetter() {
        $query = $this->db->runQuery(
            "SELECT `letter`, COUNT(*) AS item_count FROM `".$this->tb_entity."` GROUP BY `letter` ORDER BY `letter` ASC "
        );
        return $this->db->fetchAll($query);
    }


    protected function _buildQueryConditionExtend(array $filter_condition): ?array
    {
        /*$condition = array(
            "letter" => "",
        );*/

        $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);
    }

    public function getInfoByUrl($brand_index) : ?array
    {
        $brand_index = preg_replace("/[^a-z0-9\.\-\_]/i", '', $brand_index);

        $query = $this->db->runQuery("SELECT * FROM `".$this->tb_entity."` WHERE `brand_index` = ? LIMIT 1 ", ['s'], [$brand_index]);
        if($item_info = $this->db->fetchAssoc($query)){
            return $this->formatItemInfo($item_info);
        }

        return null;
    }

}
