<?php

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

    require_once __DIR__ . "/DigitalSignage4_CreationVideoSpecialDataProvider.php";
    require_once __DIR__ . "/../controllers/hook/DigitalSignage4_CronJobController.php";
	
    function digitalSignage4_ajax_CronJobControllerAjaxHandler()
    {
        if ( ! check_ajax_referer( 'ds4_ajax_nonce', 'nonce', false ) ) {
            wp_send_json_error( [ 'message' => 'Invalid Nonce' ] );
        }
        //echo 'coucou';die;
        new DigitalSignage4_CronJobController();
    }
    
    function digitalSignage4_ajax_FrontShortcodeVideoDisplayerAjaxHandler()
    {
        if ( ! check_ajax_referer( 'ds4_ajax_nonce', 'nonce', false ) ) {
            wp_send_json_error( [ 'message' => 'Invalid Nonce' ] );
        }
        
        if (isset($_GET['idPlaylist']))
        {
            $idPlaylist = sanitize_text_field(wp_unslash($_GET['idPlaylist']));
        }
        $playlist = DigitalSignage4_PlaylistManager::set(DigitalSignage4_caller::getInstance())->get_playlist($idPlaylist);
        $videos = $playlist->get_videos();

        $videos = array_slice($videos, 0, $playlist->get_limit());

        $videosMp4 = array_map(function ($id) {
                                    $sql="SELECT * FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE `id_demande` = %d";
                                    global $wpdb;
                                    $sql=$wpdb->prepare($sql,$id);

            $localDemandes = DigitalSignage4_DemandeManager::set(DigitalSignage4_caller::getInstance())->getLocalDemandes($sql);
            $localDemande = $localDemandes[0];

            return $localDemande->getVideoUrl();
        }, $videos);

        wp_send_json_success(['message' =>wp_json_encode($videosMp4)]);

    }
    
    function digitalSignage4_ajax_AddGabaritCustomizeAjaxHandler()
    {
        if ( ! check_ajax_referer( 'ds4_ajax_nonce', 'nonce', false ) ) {
            wp_send_json_error( [ 'message' => 'Invalid Nonce' ] );
        }
        
        if (isset($_FILES)) {
            if (isset($_FILES['file'])) {
                            //$uploaddir= DigitalSignage4_Tools::getModuleDir().'../Files/';
                //$uploaddir=str_replace('\\', "/", $uploaddir);

                            $upload_dir_global = wp_upload_dir();
                            $uploaddir =$upload_dir_global['basedir'] . '/' . 'ds4' . '/Files';

                            if (!file_exists($uploaddir)) {
                                    wp_mkdir_p($uploaddir);
                            }
                            $uploaddir .='/';

                $uploadfile = $uploaddir . "gabarit_customize_".(isset($_POST['id_gabarit'])?sanitize_text_field(wp_unslash($_POST['id_gabarit'])):"")."_".(isset($_POST['destination'])?sanitize_text_field(wp_unslash($_POST['destination'])):"").".png";

                $responseText="";
                if (isset($_FILES['file']['size'])?$_FILES['file']['size']:0 > 0) {
                    $overrides = [ 'test_form' => false ];


                    $movefile = wp_handle_upload($_FILES['file'] , $overrides );

                    if ( $movefile && empty( $movefile['error'] ) ) {
                        $watermarkUploaded = true;
                        $file_path = $movefile['file'];
                        @unlink($uploadfile);
                        copy($file_path,$uploadfile);
                    }
                    else {
                        $watermarkUploaded = false;
                    }

                    if ($watermarkUploaded) {
                        chmod($uploadfile, 0777);
                    }
                    //$url_file=DigitalSignage4_Tools::getModuleUrl().'Files/'."gabarit_customize_".sanitize_text_field($_POST['id_gabarit'])."_".sanitize_text_field($_POST['destination']).".png";
                                    $url_file=$upload_dir_global['baseurl'] . '/' . 'ds4' . '/Files/'."gabarit_customize_".(isset($_POST['id_gabarit'])?sanitize_text_field(wp_unslash($_POST['id_gabarit'])):"")."_".(isset($_POST['destination'])?sanitize_text_field(wp_unslash($_POST['destination'])):"").".png";
                    $responseText=$url_file.";".$uploadfile;

                }

                wp_send_json_success(['message' =>wp_json_encode($responseText)]);
            }
        }

        if (isset($_POST)) {
            $datas['gabarit'] = (isset($_POST['gabarit'])?sanitize_text_field(wp_unslash($_POST['gabarit'])):"");
            $gabaritManager = new DigitalSignage4_GabaritManager();
            $gabarit = $gabaritManager->getGabarit(sanitize_text_field(wp_unslash($datas['gabarit'])));

                    $gabaritChamps = $gabarit->getChamps();
                    foreach ($gabaritChamps as $champ) {
                            $champName = $champ['name'];
                            $datas[$champName]=isset($_POST[$champName])?sanitize_text_field(wp_unslash($_POST[$champName])):"";
                            if (isset($_POST[$champName . "_ia_question"]))
                            {
                                $datas[$champName . "_ia_question"] = sanitize_text_field(wp_unslash($_POST[$champName . "_ia_question"]));
                            }
                    }

            $gabarit->setCustom($datas);
            wp_send_json_success(['message' =>'ok']);
        }
        wp_send_json_success(['message' =>'ok']);
    }
    
    function digitalSignage4_ajax_AddVideoAjaxHandler()
    {
        if ( ! check_ajax_referer( 'ds4_ajax_nonce', 'nonce', false ) ) {
            wp_send_json_error( [ 'message' => 'Invalid Nonce 4' ] );
        }

        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";
                            wp_send_json_success(['message' =>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";
                    }
                }
                wp_send_json_success(['message' =>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();
            }
        }

        new DigitalSignage4_AddVideoHandler();
        wp_send_json_success(['message' =>esc_html('fin')]);
    }
    
    function digitalSignage4_ajax_DisplayedVideoProductAjaxHandler()
    {
        if ( ! check_ajax_referer( 'ds4_ajax_nonce', 'nonce', false ) ) {
            wp_send_json_error( [ 'message' => 'Invalid Nonce 5' ] );
        }
        
        $idVideo = isset($_GET['idDemande'])?sanitize_text_field(wp_unslash($_GET['idDemande'])):"";
        $idProduct = isset($_GET['idProduct'])?sanitize_text_field(wp_unslash($_GET['idProduct'])):"";
        if ($idProduct && $idVideo) {
            DigitalSignage4_DisplayedVideoProduct::setDisplayedVideoProduct($idProduct, $idVideo);
            if (DigitalSignage4_DisplayedVideoProduct::getDisplayedVideoProduct($idProduct) == $idVideo) {
                wp_send_json_success(['message' =>"ok"]);
            }
        }
        wp_send_json_success(['message' =>"ko"]);
    }
    
    function digitalSignage4_ajax_UpdateVideoAjaxHandler()
    {
        if ( ! check_ajax_referer( 'ds4_ajax_nonce', 'nonce', false ) ) {
            wp_send_json_error( [ 'message' => 'Invalid Nonce 6' ] );
        }
        wp_send_json_success(['message' =>'coucou']);
        
        $demande_items = "false";

        if (isset($_GET['demande_items']) && $_GET['demande_items'] == "true") {
            $demande_items = "true";
        }

        $videoHandlerManager = new DigitalSignage4_UpdateVideoHandlerManager($demande_items, (isset($_GET['demande_id'])) ? sanitize_text_field(wp_unslash($_GET['demande_id'])) : null, (isset($_GET['product_id'])) ? sanitize_text_field(wp_unslash($_GET['product_id'])) : null);
        wp_send_json_success(['message' => $videoHandlerManager->echoHtmlDatas()]);
    }
    
    function digitalSignage4_ajax_CreationVideoSpecialDataProviderAjaxHandler()
    {
        if ( ! check_ajax_referer( 'ds4_ajax_nonce', 'nonce', false ) ) {
            wp_send_json_error( [ 'message' => 'Invalid Nonce 7' ] );
        }
        
        class DigitalSignage4_CreationVideoSpecialDataProviderAjaxHandler
        {
            public $data = "";

            public function __construct($request)
            {
                $datasProvider = new DigitalSignage4_CreationVideoSpecialDataProvider();

                $callableFunctionData = array($datasProvider, $request);
                if (is_callable($callableFunctionData)) {
                    $this->data = call_user_func($callableFunctionData);
                } else {
                    $this->data=$request;
                }
            }

            public function display()
            {
                ob_get_clean();
                wp_send_json_success(['message' => esc_html($this->data)]);
                die();
            }
        }
        
        if (isset($_GET['digitalSignageSpecialData'])) {


                    if (isset($_GET['ia_question'])) {
                            $datasProvider = new DigitalSignage4_CreationVideoSpecialDataProvider();
                            $retour=$datasProvider->IA_description((isset($_GET['ia_question'])?sanitize_text_field(wp_unslash($_GET['ia_question'])):""),(isset($_GET['id_product'])?sanitize_text_field(wp_unslash($_GET['id_product'])):""));
                            ob_get_clean();
                            wp_send_json_success(['message' => $retour]);

                    } else {
                        $handler = new DigitalSignage4_CreationVideoSpecialDataProviderAjaxHandler((isset($_GET['digitalSignageSpecialData'])?sanitize_text_field(wp_unslash($_GET['digitalSignageSpecialData'])):""));
                            $handler->display();
                    }
        }


        
    }