<?php

namespace Hura8\Components\Banner\Model;

use Hura8\System\Model\aEntityBaseModel;
use Hura8\Interfaces\iEntityModel;
use Hura8\Interfaces\EntityType;


class BannerModel extends aEntityBaseModel implements iEntityModel
{

    protected $tb_banner_location       = "tb_banner_location";
    protected $tb_banner_per_category   = "tb_banner_per_category";

    public function __construct() {
        parent::__construct(
            EntityType::BANNER, "", new BannerSearchModel()
        );
    }

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

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

        return false;
    }

    public function getBannerPerTemplate(array $template_list, $numberOfBannerPerTpl=100){

        $all_bind_types     = [];
        $all_bind_values    = [];

        $view_id = 0;

        $build_query = [];
        foreach($template_list as $tpl) {

            list($where_condition, $bind_types, $bind_values) = $this->buildQueryPerTpl($tpl, $view_id, $numberOfBannerPerTpl);

            $build_query[] = " (".$where_condition.") ";
            $all_bind_types = array_merge($all_bind_types, $bind_types);
            $all_bind_values = array_merge($all_bind_values, $bind_values);
        }

        if(!sizeof($build_query)) return [];

        $query = $this->db->runQuery(join(" UNION ALL ", $build_query), $all_bind_types, $all_bind_values);

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

    protected function _buildQueryConditionExtend(array $filter_condition) : ?array
    {
        /*$condition = array(
            [location] => 2
            [category] => 0
        );*/

        $catCondition   = [];
        $bind_types     = [];
        $bind_values    = [];

        if(isset($filter_condition['location']) && $filter_condition['location']) {
            $catCondition[] = " AND `location` = ? ";
            $bind_types[] = 'd';
            $bind_values[] = $filter_condition['location'];
        }

        if(isset($filter_condition['category']) && $filter_condition['category']) {
            $catCondition[] = " AND `id` IN ( SELECT `banner_id` FROM  `".$this->tb_banner_per_category."` WHERE  `category_id` = ? ) ";
            $bind_types[]   = 'd';
            $bind_values[]  = $filter_condition['category'];
        }

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


}
