<?php

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

    require_once __DIR__ . "/../Classes/DigitalSignage4_Tools.php";
    require_once __DIR__ . "/../Kernel/API/Entity/DigitalSignage4_AutomatisationEntity.php";
    require_once __DIR__ . "/../Kernel/API/Entity/DigitalSignage4_PlaylistEntity.php";
    require_once __DIR__ . "/../Kernel/API/Entity/DigitalSignage4_LotEntity.php";
    require_once __DIR__ . "/../Kernel/API/Manager/DigitalSignage4_AutomatisationManager.php";
    require_once __DIR__ . "/../Kernel/API/Manager/DigitalSignage4_LotManager.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__ . "/../Kernel/Translations/DigitalSignage4_Translate.php";
    require_once __DIR__ . "/../Classes/DigitalSignage4_caller.php";
    require_once __DIR__ . "/../Kernel/API/Manager/DigitalSignage4_DemandeManager.php";
	

    class DigitalSignage4_VideoController extends DigitalSignage4_Controller
    {
        public function generatePage()
        {
            try {
                $this->route();
            } catch (DigitalSignage4_Exception $e) {
                $e->echoError();
            }
        }

        /**
         * @throws DigitalSignage4_Exception
         */
        private function route()
        {
            //check_admin_referer( 'ds4_form_nonce' );
            $vue = (isset($_GET['automatisationVue'])) ? (sanitize_text_field(wp_unslash($_GET['automatisationVue']))) : 'liste';

            $vue_lot = (isset($_GET['traitement_par_lotVue'])) ? (sanitize_text_field(wp_unslash($_GET['traitement_par_lotVue']))) : 'liste';

            $this->handleDeleteVideoAjaxRequest();
            $this->handleCreationAjaxRequest();

            if ($vue == 'add') {
                $this->generateCreationPage();
                return ;
            }

            if ($vue_lot == 'add') {
                $this->generateCreationLotPage();
                return ;
            }

            if ($vue == 'liste') {

                // Nombre de videos affichées par page de videotheque
                $videosPage = 10;

                $offset = intval((isset($_GET['offset'])) ? $_GET['offset'] : 0);
                if ($offset > 0) {
                    $offset = $offset * $videosPage;
                }

                // Récuperation des videos
                $videos = $this->getVideo($offset, $videosPage);


                $videosHtml = array_map(
                    function ($v) {
                        $u = new DigitalSignage4_UpdateVideoHandlerManager(false, $v->getIdDemande(), $v->getFlag());
                        return $u->getHtmlDatas();
                    },
                    $videos
                );



                // Total des videos
                $pagination = $this->pagination($offset, $videosPage);
//
//                $videos = DigitalSignage4_Tools::convertPoductIdToLink($videos);

                $url = plugin_dir_url(__FILE__);

                $this->assign(array(
                    'pageProduits'     => DigitalSignage4_Tools::getProductsUrl(),
                    'automatisations'  => $this->getAutomatisation(),
                    'traitement_par_lots'  => $this->getLot(),
                    "ManualUrl"         => DigitalSignage4_Tools::getModuleUrl() . "Kernel/Views/img/DS4-Manual.png",
                    "AutomateUrl"       => DigitalSignage4_Tools::getModuleUrl() . "Kernel/Views/img/DS4-Automate.png",
                    "BatchUrl"          => DigitalSignage4_Tools::getModuleUrl() . "Kernel/Views/img/DS4-Batch.png",
                    "VideosUrl"          => DigitalSignage4_Tools::getModuleUrl() . "Kernel/Views/img/DS4-Videos.png",
                    'ajaxUrl'           => admin_url('admin-ajax.php'),
                    'playlistBaseUrl'  => DigitalSignage4_Tools::getUrlRedirect('DigitalSignagePlaylists'),
                    'videos'           => $videosHtml,
                    'puces'            => $pagination,
                    'stats'            => $this->getStats(),
                    'moduleUrl'        => DigitalSignage4_Tools::getModuleUrl(),
                    'updateController' => $url . 'override/DigitalSignage4_UpdateVideoHandler.php',
                    'textBtnCreation' => (DigitalSignage4_Tools::isPrestashop()) ? DigitalSignage4_Translate::getTraduction("Creation_manuelle_btn_pre") : DigitalSignage4_Translate::getTraduction("Creation_manuelle_btn_woo"),
                    'form_nonce' => wp_nonce_field( 'ds4_form_nonce' ),
                    'ajax_nonce' => wp_create_nonce( 'ds4_ajax_nonce' ),
                ));

                $this->setWPTemplate("Videos/videotheque");
            }
        }

        /**
         * @throws DigitalSignage4_Exception
         */
        private function getVideo($offset, $videosPage)
        {
            $sql = "SELECT * from ".DigitalSignage4_caller::get_video_table_name()." ORDER BY `id_demande` DESC, CASE `flag` WHEN 'waiting' THEN 1 WHEN 'in_progress' THEN 2 WHEN 'completed' THEN 3 WHEN 'error' THEN 4 ELSE 5 END  LIMIT %d OFFSET %d";
			global $wpdb;
            $sql=$wpdb->prepare($sql,$videosPage,$offset);
            return DigitalSignage4_DemandeManager::set(DigitalSignage4_caller::getInstance())->getLocalDemandes($sql);
        }

        private function pagination($offset, $videosPage)
        {
            $nombreDeVideo = DigitalSignage4_caller::getInstance()->execute_video_request("SELECT count(*) as 'cpt' FROM ".DigitalSignage4_caller::get_video_table_name());

            if ($nombreDeVideo) {
                $nombreDeVideo = $nombreDeVideo[0]['cpt'];

                $puces = array();

                for ($i = 0; $i < $nombreDeVideo / $videosPage; $i += 1) {
                    $puces[] = array(
                        'active' => ($offset / $videosPage == $i),
                        'nombre' => $i + 1,
                        'lien'   => (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on') ? "https" : "http") . "://" . (isset($_SERVER['HTTP_HOST'])?sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])):"") . (isset($_SERVER['REQUEST_URI'])?sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])):"") . "&offset=$i"
                    );
                }

                return $puces;
            }
        }

        private function getStats()
        {
            $waiting = DigitalSignage4_caller::getInstance()->execute_video_request("SELECT count(*) as 'cpt' FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE `flag` = 'waiting'");
            $in_progress = DigitalSignage4_caller::getInstance()->execute_video_request("SELECT count(*) as 'cpt' FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE `flag` = 'in_progress'");
            $error = DigitalSignage4_caller::getInstance()->execute_video_request("SELECT count(*) as 'cpt' FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE `flag` = 'error'");

            return array(
                'nb_videos_attente'           => $waiting[0]["cpt"],
                'nb_videos_en_cours_creation' => $in_progress[0]["cpt"],
                'nb_video_erreur'             => $error[0]["cpt"],
            );
        }

        public function deleteDirectory($dir)
        {
            if (!file_exists($dir)) {
                return true;
            }

            if (!is_dir($dir)) {
                return unlink($dir);
            }

            foreach (scandir($dir) as $item) {
                if ($item == '.' || $item == '..') {
                    continue;
                }

                if (!$this->deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
                    return false;
                }
            }

            return rmdir($dir);
        }

        private function handleDeleteVideoAjaxRequest()
        {
            if (isset($_POST['id']) && isset($_POST['delete']) && $_POST['delete'] == "true") {
                $id = sanitize_text_field(wp_unslash($_POST['id']));
				ob_get_clean();
                $html_tmp="";

                // delete video files
				$upload_dir = wp_upload_dir();
				
                $this->deleteDirectory($upload_dir['basedir'] . '/' . 'ds4' . '/Videos/' . $id);


                $filesIsDeleted = !file_exists($upload_dir['basedir'] . '/' . 'ds4' . '/Videos/' . $id);

                if ($filesIsDeleted) {
                    try {
                        foreach ((new DigitalSignage4_PlaylistManager(DigitalSignage4_caller::getInstance()))->get_playlists() as $playlist) {
                            $needUpdate = false;
                            $videos = $playlist->get_videos();
                            if (($key = array_search($id, $videos)) !== false) {
                                $needUpdate = true;
                                unset($videos[$key]);
                            }
                            if ($needUpdate) {
                                $playlist->set_videos($videos);
                                if (!((new DigitalSignage4_PlaylistManager(DigitalSignage4_caller::getInstance()))->update_playlist($playlist))) {
									ob_get_clean();
                                    die(esc_html(DigitalSignage4_Translate::getTraduction("Suppression_impossible")));
								}
                            }
                        }
                    } catch (DigitalSignage4_Exception $e) {
                        $html_tmp.= esc_html($e->getMessage());
                    }
                } else {
					ob_get_clean();
                    die(esc_html(DigitalSignage4_Translate::getTraduction("Suppression_files_impossible")));
                }
				
				$sql="DELETE FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE `id_demande` = %d";
				global $wpdb;
				$sql=$wpdb->prepare($sql,$id);
                if (DigitalSignage4_caller::getInstance()->execute_video_request($sql) === false) {
					ob_get_clean();
                    die(esc_html(DigitalSignage4_Translate::getTraduction("MAJ_bdd_impossible")));
                }

                $result = $html_tmp;

                if (empty($result)) {
                    DigitalSignage4_DisplayedVideoProduct::removeDisplayedVideoProduct($id);
					ob_get_clean();
                    die(esc_html("ok"));
                }
				ob_get_clean();
                die(esc_html($result));
            }
        }

        private function getLot()
        {
            $lots = DigitalSignage4_LotManager::set(DigitalSignage4_caller::getInstance())->get_lots();

            foreach ($lots as $key => $lot) {


                //Playlsit
                $playlist = DigitalSignage4_PlaylistManager::set(DigitalSignage4_caller::getInstance())->get_playlist($lot->getPlaylist());
                if ($playlist) {
                    $lots[$key]->setPlaylist($playlist);
                } else {
                    $lots[$key]->setPlaylist(null);
                }

                //Gabarit
                $gabarit = DigitalSignage4_GabaritManager::instance()->getGabarit($lot->getGabarit());
                if ($gabarit) {
                    $lots[$key]->setGabarit($gabarit);
                }
            }



            return $lots;
        }

        /**
         * @throws DigitalSignage4_Exception
         */
        private function getAutomatisation()
        {
            $autos = DigitalSignage4_AutomatisationManager::set(DigitalSignage4_caller::getInstance())->get_automatisations();

            foreach ($autos as $key => $auto) {


                //Playlsit
                $playlist = DigitalSignage4_PlaylistManager::set(DigitalSignage4_caller::getInstance())->get_playlist($auto->getPlaylist());
                if ($playlist) {
                    $autos[$key]->setPlaylist($playlist);
                } else {
                    $autos[$key]->setPlaylist(null);
                }

                //Gabarit
                $gabarit = DigitalSignage4_GabaritManager::instance()->getGabarit($auto->getGabarit());
                if ($gabarit) {
                    $autos[$key]->setGabarit($gabarit);
                }
            }



            return $autos;
        }

        public function generateCreationLotPage()
        {
            if (isset($_POST)) {
                if (isset($_POST['save_lot'])) {
                   ob_get_clean();
					$html_tmp='';
                    if (empty($_POST['when'])) {
                        $_POST['when'] = " ";
                    }

                    $update = true;

                    $id = isset($_POST['id'])?sanitize_text_field(wp_unslash($_POST['id'])):"";
                    if (!$id) {
                        $id = DigitalSignage4_LotManager::set(DigitalSignage4_caller::getInstance())->get_last_id() + 1;
                        $update = false;
                    }

                    
                    $lot = new DigitalSignage4_LotEntity();
                    $lot->setActive(true);
                    $lot->setId($id);
                    $lot->setName(isset($_POST['name'])?sanitize_text_field(wp_unslash($_POST['name'])):"");
                    $tmpCategorie = (isset($_POST['categories'])?sanitize_text_field(wp_unslash($_POST['categories'])):"");
                    $lot->setCategorie(($tmpCategorie == '') ? array() : explode(',', $tmpCategorie));
                    $lot->setCreated(0);
                    //$lot->setHookCreation((strpos($_POST['when'], 'creat') !== false));
                    //$lot->setHookSell((strpos($_POST['when'], 'sell') !== false));
                    $lot->setPriceMax(isset($_POST['prixMax'])?sanitize_text_field(wp_unslash($_POST['prixMax'])):"");
                    $lot->setPriceMin(isset($_POST['prixMin'])?sanitize_text_field(wp_unslash($_POST['prixMin'])):"");
                    $lot->setGabarit(isset($_POST['gabarit'])?sanitize_text_field(wp_unslash($_POST['gabarit'])):"");
                    $lot->setPlaylist(isset($_POST['playlist'])?sanitize_text_field(wp_unslash($_POST['playlist'])):"");
                    //$lot->setNbProduit($_POST['sellNbProduit']);
                    //$lot->setNbJours($_POST['sellNbJours']);


                    try {
                        $lotInstance = new DigitalSignage4_LotManager(DigitalSignage4_caller::getInstance());

                        if ($update) {
                            if ($lotInstance->get_lot($id) == $lot) {
                                $html_tmp.= esc_html(DigitalSignage4_Translate::getTraduction("Parametres_inchangé"));
                            } else {
                                if ($lotInstance->update_lot($lot)) {
                                    $html_tmp.= esc_html("ok:" . $id);
                                } else {
                                    $html_tmp.= esc_html(DigitalSignage4_Translate::getTraduction("MAJ_bdd_impossible"));
                                }
                            }
                        } else {
                            if ($lotInstance->add_lot($lot)) {
                                $html_tmp.= esc_html("ok:" . $id);
                            } else {
                                $html_tmp.= esc_html(DigitalSignage4_Translate::getTraduction("MAJ_bdd_impossible"));
                            }
                        }
                    } catch (DigitalSignage4_Exception $e) {
                        echo esc_html("erreur : " . $e->getMessage());
                    }

                    //lancer la creation de toutes les vidéos...
                    $automatisationsRunner = new DigitalSignage4_AutomatisationHookControllerCreation();
                    //lister les id de produits dont il faut créer la vidéo
                    $Lot_ = DigitalSignage4_LotManager::set(DigitalSignage4_caller::getInstance());
                    $liste_product = $Lot_->get_products(isset($_POST['categories'])?sanitize_text_field(wp_unslash($_POST['categories'])):"", isset($_POST['prixMin'])?sanitize_text_field(wp_unslash($_POST['prixMin'])):"", isset($_POST['prixMax'])?sanitize_text_field(wp_unslash($_POST['prixMax'])):"");

                    foreach ($liste_product  as $id_product_) {
                        $wooCommerceProduct = new WC_Product($id_product_);

                        $datasForPostDemande = $automatisationsRunner->getDatasForPostDemandeAvecGabarit(sanitize_text_field(wp_unslash($_POST['gabarit'])), $wooCommerceProduct, null);
                        

                        $postDemandeResponse = $automatisationsRunner->postVideoToApi($datasForPostDemande, $id+1);
                        
                    }
                    
                    ob_get_clean();
                    
                    die( esc_html($html_tmp));
                }
            }

            $defautData = array(
                'id'            => "",
                'name'          => "",
                'playlist'      => "",
                'priceMin'      => '',
                'priceMax'      => '',
                'categorieTree' => $this->categorieTree(),
                'gabarit'       => '',
                'nbProducts'    => '5',
                'nbJours'       => '5'
            );

            if (isset($_GET['lot_id'])) {
                $lot = DigitalSignage4_LotManager::set(DigitalSignage4_caller::getInstance())->get_lot(sanitize_text_field(wp_unslash($_GET['lot_id'])));
                if ($lot) {
                    $defautData['id'] = $lot->getId();
                    $defautData['name'] = $lot->getName();
                    $defautData['playlist'] = $lot->getPlaylist();
                    $defautData['priceMin'] = $lot->getPriceMin();
                    $defautData['priceMax'] = $lot->getPriceMax();
                    $defautData['categorieTree'] = $this->categorieTree($lot->getCategorie());
                    $defautData['gabarit'] = $lot->getGabarit();
                    $defautData['nbProducts'] = $lot->getNbProduit();
                    $defautData['nbJours'] = $lot->getNbJours();
                }
            }


            $this->assign(array(
                'playlists' => DigitalSignage4_PlaylistManager::set(DigitalSignage4_caller::getInstance())->get_playlists(),
                'gabarits'  => DigitalSignage4_GabaritManager::instance()->getGabarits(),
                'datas'     => $defautData,
                'form_nonce' => wp_nonce_field( 'ds4_form_nonce' ),
            ));

            $this->setWPTemplate("Creation_video/add_lot");
        }

        /**
         * @throws DigitalSignage4_Exception
         */
        public function generateCreationPage()
        {
            if (isset($_POST))
            {
                if (isset($_POST['save_automatisation']))
                {
                    ob_get_clean();
                    $html_tmp='';

                    if (empty($_POST['when'])) {
                        $_POST['when'] = " ";
                    }

                    $update = true;

                    $id = isset($_POST['id'])?sanitize_text_field(wp_unslash($_POST['id'])):"";
                    if (!$id) {
                        $id = DigitalSignage4_PlaylistManager::set(DigitalSignage4_caller::getInstance())->get_last_id() + 1;
                        $update = false;
                    }

                    $automatisation = new DigitalSignage4_AutomatisationEntity();
                    $tmpCategorie = isset($_POST['categories'])?sanitize_text_field(wp_unslash($_POST['categories'])):"";
                    $automatisation->setActive(true)->setId($id)->setName(isset($_POST['name'])?sanitize_text_field(wp_unslash($_POST['name'])):"")->setCategorie(($tmpCategorie == '') ? array() : explode(',', $tmpCategorie))->setCreated(0)->setHookCreation((strpos((isset($_POST['when'])?sanitize_text_field(wp_unslash($_POST['when'])):""), 'creat') !== false))->setHookSell((strpos((isset($_POST['when'])?sanitize_text_field(wp_unslash($_POST['when'])):""), 'sell') !== false))->setPriceMax((isset($_POST['prixMax'])?sanitize_text_field(wp_unslash($_POST['prixMax'])):""))->setPriceMin((isset($_POST['prixMin'])?sanitize_text_field(wp_unslash($_POST['prixMin'])):""))->setGabarit((isset($_POST['gabarit'])?sanitize_text_field(wp_unslash($_POST['gabarit'])):""))->setPlaylist((isset($_POST['playlist'])?sanitize_text_field(wp_unslash($_POST['playlist'])):""))->setNbProduit(isset($_POST['sellNbProduit'])?sanitize_text_field(wp_unslash($_POST['sellNbProduit'])):"")->setNbJours((isset($_POST['sellNbJours'])?sanitize_text_field(wp_unslash($_POST['sellNbJours'])):""));


                    try {
                        $automatisationInstance = new DigitalSignage4_AutomatisationManager(DigitalSignage4_caller::getInstance());

                        if ($update) {
                            if ($automatisationInstance->get_automatisation($id) == $automatisation) {
                                $html_tmp.= esc_html(DigitalSignage4_Translate::getTraduction("Parametres_inchangé"));
                            } else {
                                if ($automatisationInstance->update_automatisation($automatisation)) {
                                    $html_tmp.= esc_html("ok:" . $id);
                                } else {
                                    $html_tmp.= esc_html(DigitalSignage4_Translate::getTraduction("MAJ_bdd_impossible"));
                                }
                            }
                        } else {
                            if ($automatisationInstance->add_automatisation($automatisation)) {
                                $html_tmp.= esc_html("ok:" . $id);
                            } else {
                                $html_tmp.= esc_html(DigitalSignage4_Translate::getTraduction("MAJ_bdd_impossible"));
                            }
                        }
                    } catch (DigitalSignage4_Exception $e) {
                        $html_tmp.= esc_html("erreur : " . $e->getMessage());
                    }
					ob_get_clean();
                    die(esc_html($html_tmp));
                }
            }

            $this->assign(array(
                'playlists' => DigitalSignage4_PlaylistManager::set(DigitalSignage4_caller::getInstance())->get_playlists(),
                'gabarits'  => DigitalSignage4_GabaritManager::instance()->getGabarits(),
                'datas'     => $this->getDatas(),
                'form_nonce' => wp_nonce_field( 'ds4_form_nonce' ),
            ));

            $this->setWPTemplate("Creation_video/add_auto");
        }

        private function categorieTree($selected_cat = array())
        {
            $categories = $this->getWooCommerceCategories();
            ob_start();
            echo ("<div class='caseCategorie'>");
            $this->categoriesGenerateTree($categories, $selected_cat, 0);
            echo ("</div>");

            return ob_get_clean();
        }

        private function getWooCommerceCategories()
        {
            $args = array(
                'taxonomy'     => 'product_cat',
                'orderby'      => 'name',
                'show_count'   => 0,
                'pad_counts'   => 0,
                'hierarchical' => 0,
                'title_li'     => '',
                'hide_empty'   => 0
            );

            return get_categories($args);
        }

        private function categoriesGenerateTree($categories, $selected_cat, $parentId)
        {
            foreach ($categories as $categorie) {
                if ($categorie->parent == $parentId) {
                    $checked = (in_array($categorie->term_id, $selected_cat)) ? "checked" : "";
                    echo ('<div style="margin-left: 20px"><label><input type="checkbox" name="cat[]" id="" ' . esc_html($checked) . ' value="' . esc_html($categorie->term_id) . '">' . esc_html($categorie->name) . "</label><br>");
                    $this->categoriesGenerateTree($categories, $selected_cat, $categorie->term_id);
                    echo ('</div>');
                }
            }
        }

        private function handleCreationAjaxRequest()
        {

            if (isset($_POST['request'])) {
				ob_get_clean();

                try {
                    switch ($_POST['request']) {
                        case 'rendu_Lot':

                            $lots_ = $this->getLot();
                            $stop_refresh=true;

                            $html='<div class="row header">

                <div class="cell" style="width: calc(80px + 5em);">
                </div>


                <div class="cell">
                    '.DigitalSignage4_Translate::getTraduction("Nom").'
                </div>

                <div class="cell">
                    '.DigitalSignage4_Translate::getTraduction("Video_cree").'
                </div>

                <div class="cell">
                    '.DigitalSignage4_Translate::getTraduction("Etat").'
                </div>

                <div class="cell">
                    '.DigitalSignage4_Translate::getTraduction("Playlist").'
                </div>

                <div class="cell">
                    '.DigitalSignage4_Translate::getTraduction("Gabarit").'
                </div>

            </div>';




                            foreach ($lots_ as $elt) {
                                //si un lot est en cours mettre $stop_refresh a true
                                if ($elt->getEtat()!='Terminé') {
                                    $stop_refresh=false;
                                }
                                //generer html de list lot!!
                                $html.='<div class="row" id="row_'.$elt->getId().'">
											<div class="cell" data-title="" style="display: flex; width: calc(80px + 5em);">
											<button style="padding: .55em; border-radius: 2em;background-color: #25b9d7; border: none " class="btn DigitalSignage4_button btn-primary"  onclick="location.href=location.href+\'&traitement_par_lotVue=add&lot_id='.$elt->getId().'\'">
													<span class="DigitalSignage4_material-icons">
														edit
													</span>
											</button>
											<button style="padding: .55em; border-radius: 2em; background-color: #e07281; border: none; margin-left: 1em !important;" onclick="saveIdDeleteLot('.$elt->getId().');deletelot();" class="btn DigitalSignage4_button btn-primary" data-toggle="modal" data-target="#ModalLot">
													 <span class="DigitalSignage4_material-icons">
														delete
													</span>
											</button>
										</div>
										<div class="cell" data-title="'.DigitalSignage4_Translate::getTraduction("Nom").'">
											'.$elt->getName().'
										</div>
										<div class="cell" data-title="'.DigitalSignage4_Translate::getTraduction("Video_cree").'">
											';
                                if ($elt->getCreated()) {
                                    $html.=$elt->getCreated();
                                } else {
                                    $html.='0';
                                }

                                $html.='</div>
										<div class="cell" data-title="Etat">
											'.DigitalSignage4_Translate::getTraduction($elt->getEtat()).'
										</div>
										<div class="cell" data-title="'.DigitalSignage4_Translate::getTraduction("Playlist").'">';


                                if ($elt->getPlaylist()!='') {
                                    $html.='<a href="'. DigitalSignage4_Tools::getUrlRedirect('DigitalSignagePlaylists').'&playlistVue=update&id_playlist='.$elt->getPlaylist()->get_id().'">'.$elt->getPlaylist()->get_title().'</a>';
                                }

                                $html.='</div>
										<div class="cell" data-title="'.DigitalSignage4_Translate::getTraduction("Gabarit").'">
											'.$elt->getGabarit()->getNom().'
										</div>
									</div>';
                            }


							ob_get_clean();
                            die(wp_json_encode(array('html' => $html, 'stop_refresh' => $stop_refresh)));
                            break;
                        case 'calcul_nb_pdt_Lot':
                            //utiliser les param post pour determiner le nombre de video qui vont être générées
                            $Lot_ = DigitalSignage4_LotManager::set(DigitalSignage4_caller::getInstance());
                            $liste_product = $Lot_->get_products((isset($_POST['categories'])?sanitize_text_field(wp_unslash($_POST['categories'])):""), (isset($_POST['prixMin'])?sanitize_text_field(wp_unslash($_POST['prixMin'])):""), (isset($_POST['prixMax'])?sanitize_text_field(wp_unslash($_POST['prixMax'])):""));
							ob_get_clean();
                            die(wp_json_encode(array('nb' => count($liste_product))));

                            break;
                        case 'changeActive':

                            $id = (isset($_POST['automatisationId'])?sanitize_text_field(wp_unslash($_POST['automatisationId'])):"");
                            $active = (isset($_POST['active'])?sanitize_text_field(wp_unslash($_POST['active'])):"");
                            $autoc = DigitalSignage4_AutomatisationManager::set(DigitalSignage4_caller::getInstance());
                            $automat = $autoc->get_automatisation($id);

                            if ($automat) {
                                $automat->setActive($active);

                                if ($autoc->update_automatisation($automat)) {
									ob_get_clean();
                                    die(esc_html("ok"));
                                } else {
									ob_get_clean();
                                    die(esc_html("error"));
                                }
                            } else {
								ob_get_clean();
                                die(esc_html(DigitalSignage4_Translate::getTraduction("Erreur_automat_non_trouve")));
                            }

                            break;
                        case 'deleteAuto':

                            $id = (isset($_POST['id'])?sanitize_text_field(wp_unslash($_POST['id'])):"");
                            if (DigitalSignage4_AutomatisationManager::set(DigitalSignage4_caller::getInstance())->remove_automatisation(DigitalSignage4_AutomatisationManager::set(DigitalSignage4_caller::getInstance())->get_automatisation($id))) {
								ob_get_clean();
                                die(esc_html("ok"));
                            } else {
								ob_get_clean();
                                die(esc_html(DigitalSignage4_Translate::getTraduction("Suppression_impossible")));
                            }

                            break;


                        case 'deleteLot':
                            $idLot = (isset($_POST['id'])?sanitize_text_field(wp_unslash($_POST['id'])):"");
                            if (DigitalSignage4_LotManager::set(DigitalSignage4_caller::getInstance())->remove_lot(DigitalSignage4_LotManager::set(DigitalSignage4_caller::getInstance())->get_lot($idLot))) {
								ob_get_clean();
                                die(esc_html("ok"));
                            } else {
								ob_get_clean();
                                die(esc_html(DigitalSignage4_Translate::getTraduction("Suppression_impossible")));
                            }

                            break;

                        case 'add_playlist':

                            $playlist_id = null;
                            $playlist_name = null;

                            if (!empty($_POST['new_playlist_name'])) {
                                $playlist_controller = new DigitalSignage4_PlaylistManager(DigitalSignage4_caller::getInstance());
                                $playlist_id = $playlist_controller->get_last_id() + 1;
                                $playlist_name = sanitize_text_field(wp_unslash($_POST['new_playlist_name']));

                                $playlist = new DigitalSignage4_PlaylistEntity();
                                $playlist->set_videos(array())->set_title($playlist_name)->set_active(true)->set_limit(0)->set_id($playlist_id);

                                try {
                                    if (!$playlist_controller->add_playlist($playlist)) {
                                        $playlist_id = null;
                                        $playlist_name = null;
                                    }
                                } catch (DigitalSignage4_Exception $e) {
                                    $playlist_id = null;
                                    $playlist_name = null;
                                }
                            }
							ob_get_clean();
                            die(wp_json_encode(array($playlist_name, $playlist_id)));

                            break;

                    }
                } catch (DigitalSignage4_Exception $e) {
                    $e->echoError();
                }

                
            }
        }

        private function getDatas()
        {
            $defautData = array(
                'id'            => "",
                'name'          => "",
                'playlist'      => "",
                'populaire'     => false,
                'new'           => false,
                'priceMin'      => '',
                'priceMax'      => '',
                'categorieTree' => $this->categorieTree(),
                'gabarit'       => '',
                'nbProducts'    => '5',
                'nbJours'       => '5'
            );

            if (isset($_GET['auto_id'])) {
                $automatisation = DigitalSignage4_AutomatisationManager::set(DigitalSignage4_caller::getInstance())->get_automatisation(sanitize_text_field(wp_unslash($_GET['auto_id'])));
                if ($automatisation) {
                    $defautData['id'] = $automatisation->getId();
                    $defautData['name'] = $automatisation->getName();
                    $defautData['playlist'] = $automatisation->getPlaylist();
                    $defautData['populaire'] = $automatisation->getHookSell();
                    $defautData['new'] = $automatisation->getHookCreation();
                    $defautData['priceMin'] = $automatisation->getPriceMin();
                    $defautData['priceMax'] = $automatisation->getPriceMax();
                    $defautData['categorieTree'] = $this->categorieTree($automatisation->getCategorie());
                    $defautData['gabarit'] = $automatisation->getGabarit();
                    $defautData['nbProducts'] = $automatisation->getNbProduit();
                    $defautData['nbJours'] = $automatisation->getNbJours();
                }
            }

            return $defautData;
        }
    }
