<?php

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

    require_once __DIR__ . "/../Classes/DigitalSignage4_Tools.php";
    require_once __DIR__ . "/../Kernel/Translations/DigitalSignage4_Translate.php";
    require_once __DIR__ . "/../Classes/DigitalSignage4_caller.php";
    require_once __DIR__ . "/../Kernel/API/Entity/DigitalSignage4_DemandeEntity.php";
    require_once __DIR__ . "/../Kernel/API/Entity/DigitalSignage4_PlaylistEntity.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_PlaylistManager.php";
	
    class DigitalSignage4_PlaylistsController extends DigitalSignage4_Controller
    {
        public function generatePage()
        {
            $this->route();
        }

        private function route()
        {
            
            if (isset($_GET['id_playlist'])) {
                $this->display_playlist();
            } else {
                $this->display_playlists();
            }
        }


        private function display_playlist()
        {
            try {
                $playlistM = new DigitalSignage4_PlaylistManager(DigitalSignage4_caller::getInstance());

                $this->handleUpdatePlaylistAjax();

                if (isset($_GET['loadVideos'], $_GET['start'], $_GET['stop'])) {
                    ob_get_clean();
                    $this->loadAutoPagination();
                }

                try {
                    $playlist = new DigitalSignage4_PlaylistEntity();

                    if (isset($_GET['id_playlist']) && (!empty($_GET['id_playlist']) || strval(sanitize_text_field(wp_unslash($_GET['id_playlist']))) == "0")) {
                        if ($playlistT = $playlistM->get_playlist(sanitize_text_field(wp_unslash($_GET['id_playlist'])))) {
                            $playlist = $playlistT;
                        }
                    }

                    $this->assign(
                        array(
                            'videoPlaylist' => $this->getVideoPlaylist($playlist),
                            'playlist'      => $playlist,
                            "moduleBaseUrl" => DigitalSignage4_Tools::getModuleVideoUrl(),
                            'form_nonce'    => wp_nonce_field( 'ds4_form_nonce' ),
                            'ajax_nonce' => wp_create_nonce( 'ds4_ajax_nonce' ),
                        )
                    );
                } catch (DigitalSignage4_Exception $e) {
                    $e->echoError();
                }

                $this->setWPTemplate("Playlists/add_playlist");
            } catch (DigitalSignage4_Exception $e) {
                $e->echoError();
            }
        }

        private function handleUpdatePlaylistAjax()
        {
            if (isset($_POST)) {
                if (sizeof($_POST) >0) {
                    check_admin_referer( 'ds4_ajax_nonce' );
                }
            }
            if (isset($_POST['playlist_name'], $_POST['playlist_videos'])) {

                // Reste de buffer du module pour les reponse ajax
                ob_get_clean();

                try {
                    $playlistManager = new DigitalSignage4_PlaylistManager(DigitalSignage4_caller::getInstance());

                    // Récuperation de la methode demandé update si un ed existe ou add si un id est generé
                    $isUpdate = false;


                    if (isset($_GET['id_playlist']) && (!empty($_GET['id_playlist']) || strval(sanitize_text_field(wp_unslash($_GET['id_playlist']))) == "0")) {
                        $id = sanitize_text_field(wp_unslash($_GET['id_playlist']));

                        if ($playlistManager->get_playlist($id)) {
                            $isUpdate = true;
                        }
                    } else {
                        $id = DigitalSignage4_PlaylistManager::set(DigitalSignage4_caller::getInstance())->get_last_id() + 1;
                    }


                    $videosSaved = array_unique(json_decode(sanitize_text_field(wp_unslash($_POST['playlist_videos'])), true));

                    $playlist = new DigitalSignage4_PlaylistEntity();
                    $playlist->set_active(true)
                        ->set_id($id)
                        ->set_limit(10)
                        ->set_title(sanitize_text_field(wp_unslash($_POST['playlist_name'])))
                        ->set_videos($videosSaved);


                    if ($isUpdate) {
                        $playlistOld = DigitalSignage4_PlaylistManager::set(DigitalSignage4_caller::getInstance())->get_playlist($id);

                        if ($playlistOld->get_title() == $playlist->get_title() && $playlistOld->get_videos() == $playlist->get_videos()) {
							ob_get_clean();
                            die(esc_html(DigitalSignage4_Translate::getTraduction("Parametres_inchangé")));
                        }

                        $playlist->set_active($playlistOld->get_active());
                        $playlist->set_limit($playlistOld->get_limit());

                        if ($playlistManager->update_playlist($playlist)) {
							ob_get_clean();
                            die(esc_html("ok"));
                        } else {
							ob_get_clean();
                            die(esc_html(DigitalSignage4_Translate::getTraduction("Erreur_playlist_non_trouvé")));
                        }
                    } else {
                        if ($playlistManager->add_playlist($playlist)) {
							ob_get_clean();
                            die(wp_json_encode(array("ok", $playlistManager->get_last_id())));
                        } else {
							ob_get_clean();
                            die(esc_html(DigitalSignage4_Translate::getTraduction("Playlist_non_save")));
                        }
                    }
                } catch (DigitalSignage4_Exception $e) {
                    $e->echoError();
                }
            }
        }

        private function deleteVideoFromPlaylist(
            $videos
        ) {
            $videosFinal = array();
            /*if (isset($_GET)) {
                if (sizeof($_GET) >0) {
                    check_admin_referer( 'ds4_ajax_nonce' );
                }
            }*/
            if (isset($_GET['id_playlist']) && sanitize_text_field(wp_unslash($_GET['id_playlist']) != "")) {
                try {
                    $playlist = DigitalSignage4_PlaylistManager::set(DigitalSignage4_caller::getInstance())->get_playlist(sanitize_text_field(wp_unslash($_GET['id_playlist'])));
                } catch (DigitalSignage4_Exception $e) {
                    $e->echoError();
                }
                if ($playlist) {
                    foreach ($videos as $video) {
                        if (!in_array($video->getIdDemande(), $playlist->get_videos())) {
                            $videosFinal[] = $video;
                        }
                    }
                }

                return $videosFinal;
            }

            return $videos;
        }

        /**
         * @param DigitalSignage4_DemandeEntity $video
         * @return string
         */
        private function generateVideoVue($video)
        {
            if ($video->getFlag() == 'completed') {
                
                return ('<div id=\'' . $video->getIdDemande() . '\' class=\'add_playlist_video\'
                                             ondragstart=\'drag(event)\'>
											 
                                            <video style=\'max-height:141px;\' controls muted=\'muted\' preload=\'auto\' loop onloadedmetadata=\'addPlayOnHover(this)\'>
                                                <source src=\'' . $video->getVideoUrl() . '\'
                                                        type=\'video/mp4\'>
                                            </video>
                                            <div class=\'description_video\'>
                                                <span>' . $video->getVideoName() . '</span>
                                                <span class=\'DigitalSignage4_material-icons\' id=\'button_' . $video->getIdDemande() . '\'
                                                      onclick=\'toggleVideoPlaylist(this)\'>add_circle_outline</span>
                                            </div>
                                        </div>');
            } else {
                return ('<div id=\'' . $video->getIdDemande() . '\' class=\'add_playlist_video\' draggable=\'true\'
                             ondragstart=\'drag(event)\'
                             style=\'display: flex;justify-content: center;flex-wrap: wrap;padding: 10px;color: white;\'
                             onclick=\'toggleVideoPlaylist(this)\'>
                            <span class=\'info\'>' . DigitalSignage4_Translate::getTraduction('Video_cours_creation_playlist', DigitalSignage4_Translate::getTraduction("Videos")) . '</span>
                            <div class=\'sablier\'></div>
                        </div>
                ');
            }
        }

        /**
         * @param DigitalSignage4_PlaylistEntity $playlist
         *
         * @return string
         */
        private function getVideoPlaylist($playlist)
        {
            $videosIds = $playlist->get_videos();
            $videosString = "";
            foreach ($videosIds as $id) {
				$sql="SELECT * FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE `id_demande` =  %d ";
				global $wpdb;
				$sql=$wpdb->prepare($sql,$id);
                $video = DigitalSignage4_DemandeManager::set(DigitalSignage4_caller::getInstance())->getLocalDemandes($sql);
                if (isset($video[0]) && $video[0] instanceof DigitalSignage4_DemandeEntity) {
                    $videosString = $videosString . $this->generateVideoVue($video[0]);
                }
            }

            return $videosString;
        }

        /**
         * affiche la page d'affichage des playlists
         */
        public function display_playlists()
        {
            try {
                $pc = new DigitalSignage4_PlaylistManager(DigitalSignage4_caller::getInstance());

                // si le formulaire est correct
                if (isset($_POST)) {
                    if (sizeof($_POST) >0) {
                        check_admin_referer( 'ds4_ajax_nonce' );
                    }
                }
                if (isset($_POST['id'], $_POST['etat'], $_POST['limit'])) {
                    ob_get_clean();

                    $playlist = $pc->get_playlist(sanitize_text_field(wp_unslash($_POST['id'])));

                    $playlist->set_limit(sanitize_text_field(wp_unslash($_POST['limit'])));
                    $playlist->set_active($_POST['etat'] === "true");

                    try {
                        if ($pc->update_playlist($playlist)) {
							ob_get_clean();
                            die("ok");
                        } else {
                            die(esc_html(DigitalSignage4_Translate::getTraduction("Update_impossible")));
                        }
                    } catch (Exception $e) {
                        die(esc_html(DigitalSignage4_Translate::getTraduction("Update_impossible")));
                    }
                }

                if (isset($_POST['id'], $_POST['delete'])) {
                    ob_get_clean();

                    if ($_POST['delete'] == "true") {
                        $playlistToDelete = $pc->get_playlist(sanitize_text_field(wp_unslash($_POST['id'])));

                        try {
                            if ($playlistToDelete != null && $pc->remove_playlist($playlistToDelete)) {
								ob_get_clean();
                                die("ok");
                            } else {
                                die(esc_html(DigitalSignage4_Translate::getTraduction("Delete_impossible")));
                            }
                        } catch (DigitalSignage4_Exception $e) {
                            $e->echoError();
                        }
                    }
                }

                $playlists = $pc->get_playlists();

                $this->assign(
                    array(
                        'playlists'       => $playlists,
                        "urlTraitement"   => 'admin.php?page=DigitalSignagePlaylists',
                        "urlModification" => 'admin.php?page=DigitalSignagePlaylists'
                    )
                );
            } catch (DigitalSignage4_Exception $e) {
                $e->echoError();
            }


            $this->setWPTemplate("Playlists/playlists");
        }

        private function loadAutoPagination()
        {
            $videoNamePatern = (isset($_GET['find'])) ? sanitize_text_field(wp_unslash($_GET['find'])) : "";


            $playlistVideosIds = array();

            if (isset($_GET['id_playlist']) && sanitize_text_field(wp_unslash($_GET['id_playlist'])) != "") {
                $playlistVideosIds = DigitalSignage4_PlaylistManager::set(DigitalSignage4_caller::getInstance())->get_playlist(sanitize_text_field(wp_unslash($_GET['id_playlist'])))->get_videos();
            }
            $sql="SELECT * FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE `flag` = 'completed' AND `video_name` LIKE '%%%s%%' AND `id_demande` NOT IN (%s) LIMIT %d OFFSET %d";
            global $wpdb;
            $sql=$wpdb->prepare($sql,$videoNamePatern,implode("' , '", $playlistVideosIds),(isset($_GET['stop'])) ? sanitize_text_field(wp_unslash($_GET['stop'])) : "",(isset($_GET['start'])) ? sanitize_text_field(wp_unslash($_GET['start'])) : "");
            $videos = DigitalSignage4_DemandeManager::set(DigitalSignage4_caller::getInstance())->getLocalDemandes($sql);

            $itEnd = true;

            if ($videos) {
                $itEnd = false;
            }

            $videos = $this->deleteVideoFromPlaylist($videos);

            $videosString = ($itEnd) ? "" : " ";

            foreach ($videos as $video) {
                $videosString = $videosString . $this->generateVideoVue($video);
            }

            ob_get_clean();
            die(wp_json_encode(array("ok", htmlentities($videosString))));
        }
    }
