<?php

if ( ! defined( 'ABSPATH' ) ) exit;

require_once __DIR__ ."/../../../Kernel/API/Entity/DigitalSignage4_LotEntity.php";
require_once __DIR__ ."/../../../Kernel/API/Linker/DigitalSignage4_CMS_Linker.php";
require_once __DIR__ ."/../../../Kernel/Translations/DigitalSignage4_Translate.php";
require_once "DigitalSignage4_Manager.php";

class DigitalSignage4_LotManager extends DigitalSignage4_Manager
{
    /**
     * @var DigitalSignage4_CMS_Linker|null
     */
    private $cms = null;
    private $entity_name = "DigitalSignage_lot";

    /**
     * @param DigitalSignage4_CMS_Linker $cms_linker
     * @throws DigitalSignage4_Exception
     */
    public function __construct($cms_linker)
    {
        if (!$cms_linker instanceof DigitalSignage4_CMS_Linker) {
            throw new DigitalSignage4_Exception(esc_html(DigitalSignage4_Translate::getTraduction('mauvais_cms_linker')));
        } else {
            $this->cms = $cms_linker;
        }
    }

    /**
     * @throws DigitalSignage4_Exception
     */
    public static function set($cms_linker)
    {
        if (!$cms_linker instanceof DigitalSignage4_CMS_Linker) {
            throw new DigitalSignage4_Exception(esc_html(DigitalSignage4_Translate::getTraduction('mauvais_cms_linker')));
        } else {
            return new DigitalSignage4_LotManager($cms_linker);
        }
    }

    /**
     * @param DigitalSignage4_LotEntity $lot
     * @throws DigitalSignage4_Exception
     */
    public function add_lot($lot)
    {
        if ($lot instanceof DigitalSignage4_LotEntity) {
            $lot_existants  = $this->cms->get_data($this->entity_name);

            if (!$lot_existants) {
                $lot_existants = array();
            }

            $lot_existants[] = $lot;
            if ($this->cms->save_data($this->entity_name, $lot_existants)) {
                return true;
            }
        } else {
            throw new DigitalSignage4_Exception(esc_html(DigitalSignage4_Translate::getTraduction('mauvais_parametre_type', 'add_lot', 'DigitalSignage4_LotEntity')));
        }

        return false;
    }

    /**
     * @param DigitalSignage4_LotEntity $lot
     * @throws DigitalSignage4_Exception
     */
    public function remove_lot($lot)
    {
        if ($lot instanceof DigitalSignage4_LotEntity) {
            $lot_existants  = $this->cms->get_data($this->entity_name);

            foreach ($lot_existants  as $key => $lot_existant) {
                if ($lot_existant->getId() == $lot->getId()) {
                    unset($lot_existants[$key]);
                }
            }

            if ($this->cms->save_data($this->entity_name, $lot_existants)) {
                return true;
            }
        } else {
            throw new DigitalSignage4_Exception(esc_html(DigitalSignage4_Translate::getTraduction('mauvais_parametre_type', 'remove_lot', 'DigitalSignage4_LotEntity')));
        }

        return false;
    }

    public function get_products($liste_categories, $prix_mini, $prix_max)
    {
        global $wpdb;
        $liste_products=array();
        $args = array(
            'limit' => -1,
            'status' => 'publish',

        );
        //'return' => 'ids',
        if (isset($liste_categories) && ($liste_categories!='')) {
            $args['product_category_id']=explode(',', $liste_categories);
        }

        $products = wc_get_products($args);

        foreach ($products as $product) {
            $hasGoodCategory = false;
            if (isset($liste_categories) && ($liste_categories!='')) {
                foreach ($product->category_ids as $id_category) {
                    if (in_array($id_category, $args['product_category_id'])) {
                        $hasGoodCategory = true;
                    }
                }
            } else {
                $hasGoodCategory = true; // Si pas de categorie cherchée, on prend tous les produits
            }
            if (!$hasGoodCategory) {
                continue;
            }

            $autoPriceMin = intval($prix_mini);
            $autoPirceMax = intval($prix_max);

            if ($autoPriceMin == -1 && $autoPirceMax == -1) {
                $liste_products[]= $product->get_id();
            } elseif ($autoPriceMin >= 0 && $autoPirceMax == -1) {
                if ($product->get_price() >= $autoPriceMin) {
                    $liste_products[]= $product->get_id();
                }
            } elseif ($autoPriceMin >= 0 && $autoPirceMax >= 0) {
                if (($product->get_price() >= $autoPriceMin) && ($product->get_price() <= $autoPirceMax)) {
                    $liste_products[]= $product->get_id();
                }
            }
        }

        return $liste_products;
    }

    /**
     * @return DigitalSignage4_LotEntity[]
     */
    public function get_lots()
    {
        $lot_existants  = $this->cms->get_data($this->entity_name);

        if (!$lot_existants) {
            $lot_existants = array();
        }


        //determiner si video en cours de traitement si oui retourner "etat" en cours sinon terminé
        //determnier le nombre de video a generer et généré
        foreach ($lot_existants as $lot_existant) {
            $nb_videos=0;
            $nb_videos_cree=0;
            //rechercher les id_lot correspondants dans la liste des videos a créer
			$sql="SELECT * FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE `automatique` = %d";
			global $wpdb;
			$sql=$wpdb->prepare($sql,($lot_existant->getId()+1));
            
            $videos = DigitalSignage4_DemandeManager::set(DigitalSignage4_caller::getInstance())->getLocalDemandes($sql);
            if ($videos) {
                foreach ($videos as $video) {
                    $nb_videos++;
                }
            }
			$sql="SELECT * FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE flag='completed' AND `automatique` = %d";
			global $wpdb;
			$sql=$wpdb->prepare($sql,($lot_existant->getId()+1));
            $videos = DigitalSignage4_DemandeManager::set(DigitalSignage4_caller::getInstance())->getLocalDemandes($sql);
            if ($videos) {
                foreach ($videos as $video) {
                    $nb_videos_cree++;
                }
            }
            if ($nb_videos_cree==$nb_videos) {
                $lot_existant->setEtat('Terminé');
            } else {
                $lot_existant->setEtat('En cours');
            }


            $lot_existant->setCreated($nb_videos_cree.'/'.$nb_videos);
        }



        return $lot_existants;
    }

    /**
     * @param $id
     * @return array|mixed
     */
    public function get_lot($id)
    {

        /**
         * @var DigitalSignage4_LotEntity[] $lot_existants
         */
        $lot_existants  = $this->cms->get_data($this->entity_name);

        if (!$lot_existants) {
            $lot_existants = array();
        }

        foreach ($lot_existants as $lot_existant) {
            if ($lot_existant->getId() == $id) {
                return $lot_existant;
            }
        }

        return false;
    }

    public function get_last_id()
    {
        $lot_existants  = $this->cms->get_data($this->entity_name);
        $last_id = 0;
        foreach ($lot_existants as $lot_existant) {
            if ($lot_existant->getId() > $last_id) {
                $last_id = $lot_existant->getId();
            }
        }
        return $last_id;
    }



    public function update_lot($lot)
    {
        $lot_existants  = $this->cms->get_data($this->entity_name);

        foreach ($lot_existants as $key => $lot_existant) {
            if ($lot->getId() == $lot_existant->getId()) {
                $lot_existants[$key] = $lot;
            }
        }

        return $this->cms->save_data($this->entity_name, $lot_existants);
    }
}
