<?php

namespace Hura8\Components\Product\Controller;


use Hura8\Components\Product\Model\ProductImageModel;
use Hura8\Components\Product\Model\ProductLanguageModel;
use Hura8\Components\Product\Model\ProductModel;
use Hura8\System\Controller\aEntityBaseController;
use Hura8\System\Security\DataClean;
use Hura8\System\Security\DataType;
use Hura8\System\Url;


abstract class bProductController extends aEntityBaseController
{

    static $image_folder = "media/product";

    static $resized_sizes = array(
        't' => ['width' => 100,] ,
        's' => ['width' => 300,] ,
        'l' => ['width' => 650,]
    );

    protected  $objProductModel;

    public function __construct()
    {
        $this->objProductModel = new ProductModel();

        if(!$this->isDefaultLanguage()) {
            $objProductLanguageModel = new ProductLanguageModel();
            // $this->objProductLanguageModel->createTableLang();
            parent::__construct($this->objProductModel, $objProductLanguageModel);
        }else{
            parent::__construct($this->objProductModel);
        }
    }


    //get product image list
    public function productImageList($proId){
        $objProductImageModel = new ProductImageModel($proId);
        $result = array();
        foreach ( $objProductImageModel->getList(["numPerPage" => 100]) as $rs ) {
            $result[] = [
                "size"   => static::getResizedImageCollection($rs['img_name']),
                "alt"    => $rs['alt'],
                "folder"    => $rs['folder'],
            ];
        }

        return $result;
    }


    public function getProductDisplayOptions($current_url) {
        $allowed_options = array(
            "list" => "Danh sách",
            "grid" => "Xem nhóm",
            "detail" => "Chi tiết"
        ) ;

        $collection = array();
        foreach($allowed_options as $option =>   $name){
            $url = Url::buildUrl($current_url, array("display" =>  ""));
            $collection[] = array(
                "url" => Url::buildUrl($url, array("display" =>  $option)) ,
                "key" => $option ,
                "name" => $name ,
            );
        }
        return $collection;
    }


    public function getProductOtherFilterOptions($current_url) {
        $allowed_options = array(
            //"order" => $global_language['sort_by_order'] ,
            "in-stock" 		=> 'Còn hàng' ,
        ) ;

        $_collection = array();
        foreach($allowed_options as $option => $_name){
            $_collection[] = array(
                "url" => Url::buildUrl($current_url, array("other_filter"   =>  $option, 'page' => '')) ,
                "key" => $option ,
                "name" => $_name ,
            );
        }
        return $_collection;
    }


    public function getProductSortOptions($current_url, array $options = []) {
        //global $global_language;

        if(!sizeof($options)) $options = array(
            //"order" => $global_language['sort_by_order'] ,
            "new" 			=> "Mới nhất" ,
            "price-asc" 	=> "Giá tăng dần", //$global_language['sort_by_price_asc'] ,
            "price-desc" 	=> "Giá giảm dần", //$global_language['sort_by_price_desc'] ,
            "view" 			=> "Lượt xem", //$global_language['sort_by_view'],
            "comment" 		=> "Trao đổi", //$global_language['sort_by_comment'] ,
            "rating" 		=> "Đánh giá", //$global_language['sort_by_rating'] ,
            "name" 			=> "Tên A->Z" ,
        ) ;

        $sort_by_collection = array();
        foreach($options as $sort_option=>$sort_name){
            // $url = build_url($current_url, array("sort" =>  ""));
            $sort_by_collection[] = array(
                "url" => Url::buildUrl($current_url, array("sort"   =>  $sort_option)) ,
                "key" => $sort_option ,
                "name" => $sort_name ,
            );
        }
        return $sort_by_collection;
    }


    public function getProductInfoBySKU($sku) {

        return self::getCache(md5("getFullInfo-".$sku), function () use ($sku) {

            $info = $this->objProductModel->getProductInfoBySKU($sku);

            return ($info) ? $this->formatItemInfo($info) : null;
        });
    }


    // get full info- basic with description
    public function getFullInfo($id)
    {
        return self::getCache("getFullInfo-".$id, function () use ($id) {

            $info = $this->objProductModel->getFullInfo($id);

            if($this->iEntityLanguageModel && $info) {
                $item_language_info = $this->iEntityLanguageModel->getInfo($id);
                if($item_language_info) {
                    return $this->formatItemInfo(array_merge($info, $item_language_info));
                }
            }

            return ($info) ? $this->formatItemInfo($info) : null;
        });
    }


    protected function validateAndCleanFilterCondition(array $raw_filter_condition): array
    {
        $clean_values = parent::validateAndCleanFilterCondition($raw_filter_condition);

        // special cases for 'price' which is in range
        if(array_key_exists('price', $raw_filter_condition)) {
            $value = $raw_filter_condition['price'];
            // expect $value = array('max' => 0, 'min'=> 0)
            if(isset($value['max']) && isset($value['min'])) {
                $clean_values['price'] = array(
                    'max' => DataClean::makeInputSafe($value['max'], DataType::INTEGER),
                    'min' => DataClean::makeInputSafe($value['min'], DataType::INTEGER),
                );
            }
        }

        return $clean_values;
    }


    protected function formatItemInList(array $item_info) : array
    {
        return $this->formatItemInfo($item_info);
    }


    protected function formatItemInfo(?array $item_info): ?array
    {
        if(!$item_info) return null;

        $info = $item_info;

        $info['image'] = static::getResizedImageCollection($info['thumbnail']);

        return $info;
    }


    public static function getResizedImageCollection($image_name) {

        $image = [];

        $size_in_full = [
            't' => 'thumb' ,
            's' => 'small' ,
            'l' => 'large' ,
        ];

        foreach (static::$resized_sizes as $size => $value) {
            $image[$size_in_full[$size]] = ($image_name) ? STATIC_DOMAIN . "/". static::$image_folder . "/". $size. IMAGE_FILE_SEPARATOR . $image_name : '';
        }

        $image['original'] = ($image_name) ? STATIC_DOMAIN . "/". static::$image_folder . "/". $image_name : '';

        return $image;
    }

}
