<?php

    if ( ! defined( 'ABSPATH' ) ) exit; //It was a ajax file

    if (file_exists('./../../../../../wp-load.php')) {
        define('WP_USE_THEMES', false); // Don't load theme support functionality
        require('./../../../../../wp-load.php');
    } else {
        require('./../../../../../config/config.inc.php');
        require('./../../../../../init.php');
        require_once "./../../../digitalsignage4.php";
        DigitalSignage4_Translate::setLang(substr(get_bloginfo('language'), 0, 2));
        refresh_local_token();
    }

    require_once __DIR__ . "/../../Kernel/Translations/DigitalSignage4_Translate.php";
    require_once __DIR__ . "/../../Classes/DigitalSignage4_caller.php";
    require_once __DIR__ . "/../../controllers/DigitalSignage4_VideoController.php";
    require_once __DIR__ . "/../../Kernel/API/Entity/DigitalSignage4_DemandeEntity.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__ . "/../../Classes/DigitalSignage4_CreationVideoSpecialDataProvider.php";

    new DigitalSignage4_AddVideoHandler();

    class DigitalSignage4_AddVideoHandler
    {
        private $responde = array(
            "statut" => "ok",
            'error'  => array(),
            'data'   => array()
        );

        public function __construct()
        {
            $this->initContent();
        }

        public function initContent()
        {
            if (isset($_POST)) {
                
		$datas['gabarit']=isset($_POST['gabarit'])?sanitize_text_field(wp_unslash($_POST['gabarit'])):"";

                if ($this->gabaritReachable($datas)) {
                    $gabaritChamps = $this->getGabaritChamps(sanitize_text_field(wp_unslash($datas['gabarit'])));

                    $haveRequiredChampEmpty = false;

                    foreach ($gabaritChamps as $champ) {
                        //$isHideChamp = strval($champ['hide'] ) == "1";
                        $isRequiredChamp = strval($champ['canBeNull']) == "0";
                        $champName = $champ['name'];
                        $champLabel = $champ['label'];
						
			$datas[$champName]=isset($_POST[$champName])?sanitize_text_field(wp_unslash($_POST[$champName])):"";
						
						
                        if ($isRequiredChamp) {
                            if (!isset($datas[$champName]) || sanitize_text_field(wp_unslash($datas[$champName])) === "") {
                                $haveRequiredChampEmpty = true;
                                $this->responde['error'][] = DigitalSignage4_Translate::getTraduction("Le_champ_ne_peut_pas_etre_vide", $champLabel);
                                $this->responde['data'][] = $champName;
                            }
                        }
                    }

                    if ($haveRequiredChampEmpty) {
                        $this->responde['statut'] = "ko";
                        exit(wp_json_encode($this->responde));
                    }

                    $video = new DigitalSignage4_DemandeEntity();

                    $demandeManager = new DigitalSignage4_DemandeManager(DigitalSignage4_caller::getInstance());

                    if (isset($_POST['produit_libelle'])) {
                        $videoName = sanitize_text_field(wp_unslash($_POST['produit_libelle']));
                    } elseif (isset($_POST['product_id'])) {
                        $videoName = sanitize_text_field(wp_unslash($_POST['product_id']));
                    } else {
                        $videoName = DigitalSignage4_Translate::getTraduction("Default_video_name")  ;
                    }

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


                    $specialChampsManager = new DigitalSignage4_CreationVideoSpecialDataProvider();


                    $data_youtube = $specialChampsManager->getyoutubevideo(sanitize_text_field(wp_unslash($_POST['product_id'])));
                    $video->setYoutubeData(wp_json_encode($data_youtube));


                    //poste la création de video
                    try {
                        $demande = $demandeManager->postDemande($video);
                        if ($demande) {
                            global $wpdb;
							$sql="INSERT INTO ".DigitalSignage4_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());
							$id =DigitalSignage4_caller::getInstance()->execute_video_insert($sql);


                            if ($id) {
                                $this->responde['statut'] = "ok";
                                $this->responde['data'] = $id;
                            } else {
                                $this->responde['statut'] = "ko";
                                $this->responde['error'][] = DigitalSignage4_Translate::getTraduction("Enregistrement_video_bdd_impossible");
                            }
                        } else {
                            $this->responde['statut'] = "ko";
                            $this->responde['error'] = array_merge($this->responde['error'], $demandeManager->getUserMessages());
                        }
                    } catch (DigitalSignage4_Exception $e) {
                        $this->responde['error'][] = $e->getMessage();
                    }
                } else {
                    $this->responde['error'][] = DigitalSignage4_Translate::getTraduction("choix_gabarit_vide");
                    $this->responde['statut'] = "ko";
                }
            }
            exit(wp_json_encode($this->responde));
        }


        /**
         * Verifie que le gabarit n'est pas vide
         *
         * @param array $datas
         *
         * @return bool
         */
        private function gabaritReachable(array $datas)
        {
            if (isset($datas['gabarit'])) {
                if ($datas['gabarit'] != "undefined" && !empty($datas['gabarit'])) {
                    return true;
                } else {
                    $this->responde['error'][] = DigitalSignage4_Translate::getTraduction("Gabarit_introuvable");

                    return false;
                }
            } else {
                return false;
            }
        }

        private function getGabaritChamps($gabarit)
        {
            $gabaritManager = new DigitalSignage4_GabaritManager();

            $gabarit = $gabaritManager->getGabarit($gabarit);

            return $gabarit->getChamps();
        }
    }

    echo esc_html('fin');
