<?php

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

    require_once __DIR__ . "/../../Classes/DigitalSignage4_caller.php";
    require_once __DIR__ . "/../../Kernel/API/Entity/DigitalSignage4_AutomatisationEntity.php";
    require_once __DIR__ . "/../../Kernel/API/Entity/DigitalSignage4_DemandeEntity.php";
    require_once __DIR__ . "/../../Kernel/API/Manager/DigitalSignage4_AutomatisationManager.php";
    require_once __DIR__ . "/../../Kernel/API/Manager/DigitalSignage4_DemandeManager.php";
    require_once __DIR__ . "/../../Kernel/API/Manager/DigitalSignage4_Exception.php";
    require_once __DIR__ . "/../../Kernel/API/Manager/DigitalSignage4_GabaritManager.php";
    require_once __DIR__ . "/../../Kernel/API/Manager/DigitalSignage4_PlaylistManager.php";
    require_once __DIR__ . "/../../Classes/DigitalSignage4_CreationVideoSpecialDataProvider.php";
	
    class DigitalSignage4_AutomatisationHookControllerCreation
    {
        private $ds4_caller = null;
        private $demande_manager = null;
        private $gabarit_manager = null;

        /**
         * @param null $ds4_caller
         */
        public function __construct()
        {
            $this->ds4_caller = new DigitalSignage4_caller();
            $this->demande_manager = new DigitalSignage4_DemandeManager($this->ds4_caller);
            $this->gabarit_manager = DigitalSignage4_GabaritManager::instance();
        }

        /**
         * @param string $newProductStatus
         * @param string $oldProductStatus
         * @param WP_Post $product
         *
         * @return void
         */
        public function handleProductChangeStatus($newProductStatus, $oldProductStatus, $product)
        {
            
            if ($product->post_type == "product" && $newProductStatus == "publish" && $oldProductStatus != "publish") { // a decommenter lors du passage en prod
                //if ( $product->post_type == "product" && $newProductStatus == "publish" ) {
                $automatisations = $this->getAutomatisation();
                foreach ($automatisations as $automatisation) {
                    $this->automatisationJob($automatisation, $product);
                }
            }
        }

        /**
         * @return DigitalSignage4_AutomatisationEntity[] array
         */
        private function getAutomatisation()
        {
            /**         * @var DigitalSignage4_AutomatisationEntity[] $allAutomatisations */
            $allAutomatisations = ($this->ds4_caller->get_data("DigitalSignage_automatisation")) ?: array();

            return array_filter(
                $allAutomatisations,
                function ($automatisation) {
                    $isHookCreation = filter_var($automatisation->getHookCreation(), FILTER_VALIDATE_BOOLEAN);
                    $isActive = filter_var($automatisation->isActive(), FILTER_VALIDATE_BOOLEAN);
                    return $isHookCreation && $isActive;
                }
            );
        }

        /**
         * @param DigitalSignage4_AutomatisationEntity $automatisation
         * @param WP_Post $wordPressPost
         *
         * @return boolean
         */
        public function automatisationJob($automatisation, $wordPressPost)
        {
            $wooCommerceProduct = new WC_Product($wordPressPost->ID);

            $priceIsGood = $this->checkAutomatisationPriceFilter($automatisation, $wooCommerceProduct);
            $categorieIsGood = $this->checkAutomatisationCategories($automatisation, $wooCommerceProduct);

            if ($priceIsGood && $categorieIsGood) {
				$sql="SELECT * FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE `gabarit` =%d AND `product_id` =%d ORDER BY `id_demande` DESC LIMIT 1;";
				global $wpdb;
                $sql=$wpdb->prepare($sql,$automatisation->getGabarit(),$wooCommerceProduct->get_id());
				$videoAlreadyCreated = $this->demande_manager->getLocalDemandes($sql);

                if (!empty($videoAlreadyCreated)) {
                    $this->addDemandeInPlaylist($videoAlreadyCreated[0], $automatisation->getPlaylist());
                    $this->ds4_caller->save_data(DigitalSignage4_caller::AUTOMATISATION_TRACE, date("Y-m-d H:i:s"));
                } else {
                    $datasForPostDemande = $this->getDatasForPostDemande($automatisation, $wooCommerceProduct, $wordPressPost);
                    $postDemandeResponse = $this->postVideoToApi($datasForPostDemande);

                    if ($postDemandeResponse && $this->addDemandeInPlaylist($postDemandeResponse, $automatisation->getPlaylist())) {
                        $automatisation->setCreated($automatisation->getCreated() + 1);
                        DigitalSignage4_AutomatisationManager::set($this->ds4_caller)->update_automatisation($automatisation);
                        $this->ds4_caller->save_data(DigitalSignage4_caller::AUTOMATISATION_TRACE, date("Y-m-d H:i:s"));
                    }
                }
            }
        }

        /**
         * @param DigitalSignage4_AutomatisationEntity $automatisation
         * @param WC_Product $wooCommerceProduct
         *
         * @return boolean
         */
        private function checkAutomatisationPriceFilter($automatisation, $wooCommerceProduct)
        {
            $autoPriceMin = intval($automatisation->getPriceMin());
            $autoPirceMax = intval($automatisation->getPriceMax());

            if ($autoPriceMin == -1 && $autoPirceMax == -1) {
                return true;
            } elseif ($autoPriceMin >= 0 && $autoPirceMax == -1) {
                return $wooCommerceProduct->get_price() >= $autoPriceMin;
            } elseif ($autoPriceMin >= 0 && $autoPirceMax >= 0) {
                return $wooCommerceProduct->get_price() >= $autoPriceMin && $wooCommerceProduct->get_price() <= $autoPirceMax;
            }

            return false;
        }

        /**
         * @param DigitalSignage4_AutomatisationEntity $automatisation
         * @param WC_Product $wooCommerceProduct
         *
         * @return boolean
         */
        private function checkAutomatisationCategories($automatisation, $wooCommerceProduct)
        {
            $productCategories = $wooCommerceProduct->get_category_ids();
            $automatisationCategorie = $automatisation->getCategorie();
            $categorieMatch = empty($automatisationCategorie); //Si aucune categorie n'est set dans l'automatisation alors le match par defaut et a true
            foreach ($productCategories as $productCategorie) {
                if (in_array($productCategorie, $automatisationCategorie)) {
                    $categorieMatch = true;
                }
            }

            return $categorieMatch;
        }

        /**
         * @param DigitalSignage4_DemandeEntity $demande
         * @param $playlistId
         *
         * @return boolean
         */
        private function addDemandeInPlaylist($demande, $playlistId)
        {
            try {
                $playlistManager = new DigitalSignage4_PlaylistManager($this->ds4_caller);
                $playlist = $playlistManager->get_playlist($playlistId);
                if ($playlist) {
                    $videosPlaylist = $playlist->get_videos();
                    $videoPlaylist = $this->removeArrayValue($videosPlaylist, $demande->getIdDemande());
                    array_unshift($videoPlaylist, $demande->getIdDemande());
                    $playlist->set_videos($videoPlaylist);
                    $playlistManager->update_playlist($playlist);
                }

                return true;
            } catch (DigitalSignage4_Exception $e) {
                return false;
            }
        }

        private function removeArrayValue($array, $value)
        {
            if (($key = array_search($value, $array)) !== false) {
                unset($array[$key]);
            }

            return $array;
        }

        /**
         * @param array $datas
         *
         * @return false|DigitalSignage4_DemandeEntity
           id_lot = id_lot+1
         */
        public function postVideoToApi($datas, $id_lot=1)
        {
            global $wpdb;

            $video = new DigitalSignage4_DemandeEntity();

            $video->setData($datas);
            $video->setGabarit($datas['gabarit']);
            $video->setDateBegin(date('y-m-d H:i:s'));
            $video->setDateEnd(date("y-m-d H:i:s"));
            $video->setVideoComment("");
            $video->setVideoName((isset($datas['produit_libelle'])) ? $datas['produit_libelle'] : DigitalSignage4_Translate::getTraduction("Default_video_name"));
            $video->setAutomatique($id_lot);
            $video->setDateDemande(date("Y-m-d H:i:s"));
            $video->setProductId($datas['product_id']);
            $video->setDownloaded("0");

            $specialChampsManager = new DigitalSignage4_CreationVideoSpecialDataProvider();
            $data_youtube = $specialChampsManager->getyoutubevideo($datas['product_id']);
            $video->setYoutubeData(wp_json_encode($data_youtube));
            
            //poste la création de video
            try {
                $demande = $this->demande_manager->postDemande($video);
                if ($demande) {
                    $sql="INSERT INTO ".$this->ds4_caller->get_video_table_name()." (`id_demande`,`data`,`flag`,`video_name`,`video_comment`,`date_begin`,`automatique`,`date_end`,`date_demande`,`gabarit`,`video_url`,`video_hash`,`product_id`,`youtube_data`) VALUES
                           (%d,%s,%s,%s,%s,%s,%d,%s,%s,%d,%s,%s,%d,%s) ";
                    $sql=$wpdb->prepare($sql, $demande->getIdDemande(),$demande->getData(),$demande->getFlag(),$demande->getVideoName(),$demande->getVideoComment(),$demande->getDateBegin(),
                    $demande->getAutomatique(),$demande->getDateEnd(),$demande->getDateDemande(),$demande->getGabarit(),$demande->getVideoUrl(),$demande->getVideoHash(),
                    $demande->getProductId(),$demande->getYoutubeData());
					  
                    if ($this->ds4_caller->execute_video_insert($sql)) {
                        return $demande;
                    }
                }

                return false;
            } catch (DigitalSignage4_Exception $e) {
                return false;
            }
        }


        /**
        * @param DigitalSignage4_AutomatisationEntity $automatisation
        * @param WC_Product $wooCommerceProduct
        * @param WP_Post $wordPressPost
        *
        * @return array
        */
        public function getDatasForPostDemandeAvecGabarit($Gabarit_param, $wooCommerceProduct, $wordPressPost, $forceIA = false)
        {
            //file_put_contents('debug_ag.txt','getDatasForPostDemandeAvecGabarit'."\r\n",FILE_APPEND);
            //detecter si personnalisation du gabarit
            //si oui modifie le datasForPostDemande!!!!!
            $gabarit = $this->gabarit_manager->getGabarit($Gabarit_param);




            $datas = array();
            $imageCompteur = 1;
            //foreach ($gabarit->getChamps() as $champ) {
            $champs__ =$gabarit->initCustomChamp();
            foreach ($champs__ as $champ) {
                if ($champ['type'] == 'picture') {
                    if (strpos($champ['default'], ';')!==false) {//AG je ne peux pas faire autrement
                        $datas[$champ['name']] = $champ['default'];
                        $tab_temp = array();
                        $tab_temp = explode(';', $champ['default']);
                        if (count($tab_temp)>=2) {
                            $datas[$champ['name']] =$tab_temp[1];
                        }


                        //file_put_contents('debug_ag.txt',$champ['name'].' '.$champ['default']."\r\n",FILE_APPEND);
                        //file_put_contents('debug_ag.txt','ICI RESULTAT:|'.$datas[$champ['name']]."|"."\r\n",FILE_APPEND);
                    } else {
                        if ($champ['default']!=="") {
                            //il faut detecter les mots clefs images!!! ex: product01PictureUrl01 !!!
                            //file_put_contents('debug_ag.txt',$champ['name'].' '.$champ['default']."\r\n",FILE_APPEND);
                            $specialChampsManager = new DigitalSignage4_CreationVideoSpecialDataProvider();
                            $callableFunctionData = array($specialChampsManager, $champ['default']);
                            if (is_callable($callableFunctionData)) {
                                $tab_temp = array();
                                $tab_temp = explode(';', call_user_func($callableFunctionData));
                                //$datas[$champ['name']] = call_user_func($callableFunctionData);
                                $datas[$champ['name']] =$this->getDatasPictureForPostDemande($wooCommerceProduct, $this->get_number_picture_from_name($champ['default']));
                                if (count($tab_temp)>=2) {
                                    $datas[$champ['name']] = $tab_temp[1];
                                }
                            } else {
                                $datas[$champ['name']] = $this->getDatasPictureForPostDemande($wooCommerceProduct, $this->get_number_picture_from_name($champ['default']));
                            }
                        } else {
                            $datas[$champ['name']] = $this->getDatasPictureForPostDemande($wooCommerceProduct, $imageCompteur);
                            $imageCompteur += 1;
                        }
                    }
                } else {
                    $champ_name = $champ['wordpress_champ_name'];
                    if ($champ_name == 'description' && $forceIA)
                    {
                        $champ_name = 'IA_description';
                        $lang = substr(get_bloginfo('language'), 0, 2);
                        if ($lang == 'fr')
                        {
                            $champ['ia_question'] = "Trouver un slogan pour vendre ce produit, le slogan doit faire 40 mots maximum";
                        }
                        else
                        {
                            $champ['ia_question'] = "Come up with a slogan in English to sell this product. The slogan should be no more than 40 words long.";
                        }
                    }
					
                    if ($champ_name=='IA_description') {
                            //il faut pousser dans $datas[$champ['name']] 
                            //le retour de l'api AI
                            $specialChampsManager = new DigitalSignage4_CreationVideoSpecialDataProvider();
                            $datas[$champ['name']] = $specialChampsManager->IA_description($champ['ia_question'],$wooCommerceProduct->get_id());

                    } else {
                            $datas[$champ['name']] = $this->get_data_from_champ_name($wooCommerceProduct, $champ_name, $champ['default']);
                    }
                }
            }

            $datas['gabarit'] = $Gabarit_param;
            $datas['produit_libelle'] = $wooCommerceProduct->get_name();
            $datas['product_id'] = $wooCommerceProduct->get_id();

            return $datas;
        }

        private function get_data_from_champ_name($wooCommerceProduct, $champ_name, $default)
        {
            $retour =$default;
            $callableFunctionData = array($wooCommerceProduct, 'get_' . $champ_name);
            if (is_callable($callableFunctionData)) {
                $retour = call_user_func($callableFunctionData);
            } else {
                if ($champ_name=='first_category') {
                    $terms =  get_the_terms($wooCommerceProduct->get_id(), 'product_cat');
                    if ($terms && ! is_wp_error($terms)) {
                        $retour = $terms[0]->name;
                    } else {
                        $retour = "";
                    }
                } else {
                    if ($champ_name=='pourcent_reduc') {
                        $retour="";
                        $productDatas = $wooCommerceProduct->get_data();
                        if ($productDatas['regular_price'] ==$productDatas['price']) {
                            $retour="0%";
                        } else {
                            if ($productDatas['regular_price'] >0) {
                                $retour = "-".round(($productDatas['price'] * 100) / $productDatas['regular_price'])."%";
                            }
                        }
                    } else {
                        $specialChampsManager = new DigitalSignage4_CreationVideoSpecialDataProvider();
                        $callableFunctionData = array($specialChampsManager, $champ_name);
                        if (is_callable($callableFunctionData)) {
                            $retour = call_user_func($callableFunctionData);
                        }
                    }
                }
            }
            return $retour;
        }



        /**
         * @param DigitalSignage4_AutomatisationEntity $automatisation
         * @param WC_Product $wooCommerceProduct
         * @param WP_Post $wordPressPost
         *
         * @return array
         */
        private function getDatasForPostDemande($automatisation, $wooCommerceProduct, $wordPressPost)
        {
            $gabarit = $this->gabarit_manager->getGabarit($automatisation->getGabarit());
            $datas = array();
            $imageCompteur = 1;
            $champs__ = $gabarit->initCustomChamp();
            foreach ($champs__ as $champ) {
                if ($champ['type'] == 'picture') {
                    if (strpos($champ['default'], ';')!==false) {//AG je ne peux pas faire autrement
                        $datas[$champ['name']] = $champ['default'];
                        $tab_temp = array();
                        $tab_temp = explode(';', $champ['default']);
                        if (count($tab_temp)>=2) {
                            $datas[$champ['name']] =$tab_temp[1];
                        }
                    } else {
                        //il faut detecter les mots clefs images!!! ex: product01PictureUrl01 !!!
                        if ($champ['default']!=="") {
                            //il faut detecter les mots clefs images!!! ex: product01PictureUrl01 !!!
                            $specialChampsManager = new DigitalSignage4_CreationVideoSpecialDataProvider();
                            $callableFunctionData = array($specialChampsManager, $champ['default']);
                            if (is_callable($callableFunctionData)) {
                                $tab_temp = array();
                                $tab_temp = explode(';', call_user_func($callableFunctionData));
                                $datas[$champ['name']] =$this->getDatasPictureForPostDemande($wooCommerceProduct, $this->get_number_picture_from_name($champ['default']));
                                if (count($tab_temp)>=2) {
                                    $datas[$champ['name']] = $tab_temp[1];
                                }
                            } else {
                                $datas[$champ['name']] = $this->getDatasPictureForPostDemande($wooCommerceProduct, $this->get_number_picture_from_name($champ['default']));
                            }
                        } else {
                            $datas[$champ['name']] = $this->getDatasPictureForPostDemande($wooCommerceProduct, $imageCompteur);
                            $imageCompteur += 1;
                        }
                    }
                } else {
                    $champ_name = $champ['wordpress_champ_name'];
					

					if ($champ_name=='IA_description') {
						
						//il faut pousser dans $datas[$champ['name']] 
						//le retour de l'api AI
						$specialChampsManager = new DigitalSignage4_CreationVideoSpecialDataProvider();
						$datas[$champ['name']] = $specialChampsManager->IA_description($champ['ia_question'],$wooCommerceProduct->get_id());
						
					} else {
						$datas[$champ['name']] = $this->get_data_from_champ_name($wooCommerceProduct, $champ_name, $champ['default']);
					}
                }
            }

            $datas['gabarit'] = $automatisation->getGabarit();
            $datas['produit_libelle'] = $wooCommerceProduct->get_name();
            $datas['product_id'] = $wooCommerceProduct->get_id();

            return $datas;
        }


        private function get_number_picture_from_name($name_picture)
        {
            switch ($name_picture) {
                case "product01PictureUrl01":
                    return 1;
                    break;
                case "product02PictureUrl01":
                    return 2;
                    break;
                case "product03PictureUrl01":
                    return 3;
                    break;
                case "product04PictureUrl01":
                    return 4;
                    break;
                case "product05PictureUrl01":
                    return 5;
                    break;
                case "product06PictureUrl01":
                    return 6;
                    break;
                case "product07PictureUrl01":
                    return 7;
                    break;
                case "product08PictureUrl01":
                    return 8;
                    break;
                case "product09PictureUrl01":
                    return 9;
                    break;
                case "product10PictureUrl01":
                    return 10;
                    break;
                default:
                    return 1;

            }
        }
        /**
         * cette function tourne en boucle, si une clé est superieur au nombre d'images alors elle renvois les images depuis le debut
         *
         * @param WC_Product $wooCommerceProduct
         * @param int $imageNumber
         *
         * @return string
         */

        private function getDatasPictureForPostDemande($wooCommerceProduct, $imageNumber)
        {
            $imagesIds = $wooCommerceProduct->get_gallery_image_ids();
            array_unshift($imagesIds, intval($wooCommerceProduct->get_image_id()));
            $imagesPaths = array_map(
                function ($id) {
                    get_attached_file($id);//2 fois sinon ca bug..
                    return get_attached_file($id);
                },
                $imagesIds
            );
            $nombreItems = (count($imagesPaths));
            $imageNumber = $imageNumber - 1;
            $key = $imageNumber % $nombreItems;

            return $imagesPaths[$key];
        }
    }
