<?php

namespace Hura8\Components\Product\Model;

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


class ProductCollectionModel extends aCategoryBaseModel
{

    protected $tb_collection_product  = "tb_collection_product";


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

    public function getInfoByUrl($url): ?array
    {
        $query = $this->db->runQuery(
            " SELECT * FROM `".$this->tb_entity."` WHERE `url_index` = ? LIMIT 1",
            ['s'], [$url]
        );

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

    public function getTotalProduct($collection_id, array $condition = [])
    {
        $query = $this->db->runQuery(
            " SELECT COUNT(*) as total FROM `".$this->tb_collection_product."` WHERE `collection_id` = ? ",
            ['d'], [$collection_id]
        );

        $total = 0;
        if ($rs = $this->db->fetchAssoc($query)) {
            $total = $rs['total'];
        }

        return $total;
    }


    public function getListProduct($collection_id, array $condition = [])
    {
        $numPerPage = (isset($condition['numPerPage']) && $condition['numPerPage'] > 0 ) ? intval($condition['numPerPage']) : 20 ;
        $page = (isset($condition['page']) && $condition['page'] > 0 ) ? intval($condition['page']) : 1 ;
        $order_by = " `ordering` DESC, `id` DESC";

        $query = $this->db->runQuery(
            "SELECT `product_id`, `ordering` FROM ".$this->tb_collection_product." WHERE `collection_id` = ?  
                    ORDER BY ".$order_by."
                    LIMIT  ".(($page-1) * $numPerPage).", ".$numPerPage ,
            ['d'], [$collection_id]
        ) ;

        $item_list = array();
        $counter = ($page-1) * $numPerPage;
        foreach ( $this->db->fetchAll($query) as $item ) {
            $counter += 1;

            $item_list[$item['product_id']] = [
                'counter' => $counter,
                'ordering' => $item['ordering'],
            ];
        }

        $objProductModel = new ProductModel();
        $product_list_info = $objProductModel->getListByIds(array_keys($item_list));

        // final list
        $final_list = [];
        foreach ($item_list as $_pro_id => $_pro_info_in_collection) {
            $pro_basic = $product_list_info[$_pro_id] ?? null;
            if($pro_basic) {
                $final_list[] = array_merge($pro_basic, $_pro_info_in_collection);
            }
        }

        return $final_list;
    }


}
