{block name='content'}
    <div class="DigitalSignage4_card DigitalSignage4_wp_card">
        {$form_nonce}
        <!-- Titre -->
        <h2> {$t::getTraduction( "ajout_lot_titre")}</h2>
        <br>

        <!-- Choix du filtre -->
        <div>

            <label for="name">
                {$t::getTraduction( "ajout_lot_nom")} :
                <input id="name" type="text" value="{$datas.name}"/>
            </label>

            <label style="display: flex;align-items: baseline;">
               {$t::getTraduction( "ajout_lot_description")}
            </label>

            


            <div id="sell_more" style="display: none">

                <br>

                <p>
                    
                    <span onmouseenter="this.classList.toggle('is_hover')"
                          onmouseleave="this.classList.toggle('is_hover')" class="DigitalSignage4_material-icons DigitalSignage4_click DigitalSignage4_tool-tips"
                          data-tips="{$t::getTraduction( "Aide_creation_auto_ventes")}">
                            help_outline
                        </span>
                </p>

            </div>

            <br>


        </div>
        <br><br>

        <h2>{$t::getTraduction( "Filtrer_produit_creable")}</h2>

        <br>

        <!-- Choix du filtre de prix -->
        <div>

            <label for="min">
                {$t::getTraduction( "Prix_min")} :
                <input id="min" type="number" value="{($datas.priceMin)?($datas.priceMin==-1)?"":$datas.priceMin:""}"/>
            </label>

            <br>

            <label for="max">
                {$t::getTraduction( "Prix_max")} :
                <input id="max" type="number" value="{($datas.priceMax)?($datas.priceMax==-1)?"":$datas.priceMax:""}"/>
            </label>

            <br>

            <label>
                {$t::getTraduction( "Categories")} : <br>
                {$datas.categorieTree}
            </label>

        </div>

        <br><br>

        <h2>{$t::getTraduction( "parametres_video")}</h2>

        <br>

        <!-- Choix du gabarit -->
        <div>

            {*            <label for="sell">*}
            {*                {$t::getTraduction( "Choix_gabarit")} :*}
            {*            </label>*}

            <div class="gabarits">
                {if $gabarits}
                {foreach from=$gabarits item=gabarit}
                    <div class="DigitalSignage4_gabarit">
                        <input type="radio" name="gabarit"
                               value="{$gabarit->getId()}" {if $gabarit->getId() == $datas.gabarit} checked {/if} />
                        <video controls id="{$gabarit->getId()}" loop width="250" preload="auto" muted="muted">
                            <source src="{$gabarit->getLienVideoExemple()}" type="video/mp4">
                        </video>
                        <p>{$gabarit->getNom()}</p>
                    </div>
                {/foreach}
                    <script>
                        let videos_displayers = document.querySelectorAll(".gabarits .DigitalSignage4_gabarit>input");
                        videos_displayers.forEach((input) => {

                                let videoContainer = input.parentElement.querySelector("video");

                                if (videoContainer) {

                                    videoContainer.currentTime = 2;
                                    videoContainer.load();

                                    input.addEventListener("mouseenter", () => {
                                        videoContainer.play();
                                    });

                                    input.addEventListener("mouseleave", () => {
                                        videoContainer.pause();
                                        videoContainer.currentTime = 2;
                                    });

                                }
                            }
                        )
                    </script>
                {else}
                    <p>{$t::getTraduction( "Aucun_gabarit")}</p>
                {/if}
            </div>

        </div>
        <br><br>

        <h2>{$t::getTraduction( "Enregistrement_videos")}</h2>

        <br>


        <!-- Choix de la playlist -->
        <label for="playlist">

            <label style="display: flex;align-items: baseline;" for="activer_p">
                <input style="margin-right: 5px;" id="activer_p" type="checkbox" onchange="affiche_playlist(this)"
                       {if $datas.playlist != 'null'}checked{/if} >
                {$t::getTraduction( "Enregistrement_playlist_videos")}
            </label>

            <div id="playlist_hiddden" {if $datas.playlist == 'null'}style="display: none"{/if}>

                <br>

                <ul>

                    <li>
                        {$t::getTraduction( "Playlist_enregistrement")}
                        <select id="playlist" name="playlist">
                            {*                            <option value="">{$t::getTraduction( "Choix_playlist")}</option>*}
                            {foreach from=$playlists item=playlist}
                                <option value="{$playlist->get_id()}" {if $playlist->get_id() == $datas.playlist} selected {/if} >
                                    ({$playlist->get_id()})
                                    {$playlist->get_title()}</option>
                            {/foreach}
                        </select>
                        <br>
                    </li>

                    <br>

                    {*                    <li style="list-style: none">*}
                    {*                        Ajout rapide d'une nouvelle playlist*}
                    {*                        <div style="display: flex;align-items: baseline;"><input id="new_playlist_name" type="text">*}
                    {*                            <button onclick="create_new_playlist()">Créer</button>*}
                    {*                        </div>*}
                    {*                    </li>*}

                </ul>


            </div>


        </label>

        <!-- Enregistrement -->
        <button id="sendForm" class="btn DigitalSignage4_button btn-primary"
                onclick="affiche_msg_enregistrer()">{$t::getTraduction( "Enregistrer")}</button>
        <br>


        <script>

            let currentPlaylistId = "{$datas.id}";

            function affiche_playlist(element) {

                if (element.checked) {
                    document.getElementById('playlist_hiddden').style.display = "block";
                } else {
                    document.getElementById('playlist_hiddden').style.display = "none";
                }
            }
			
            function affiche_msg_enregistrer()
            {
		let form = new FormData();
		let categories = Array.from(document.querySelectorAll('.caseCategorie input[type="checkbox"]:not(.when):checked')).map(function (categorie) {
                    return categorie.value;
                });
                form.append("categories", categories);

                let when = Array.from(document.querySelectorAll('.when:checked')).map(function (when) {
                    return when.value;
                });
                form.append("when", when);
				

                let prixMin = parseInt(document.getElementById("min").value);
                let prixMax = parseInt(document.getElementById("max").value);


                if ((prixMin === 0 && prixMax === 0) || (!prixMin && !prixMax)) {
                    prixMin = -1;
                    prixMax = -1;
                } else if (!prixMax && prixMin) {
                    prixMax = -1; // unlimited
                } else if (prixMax && !prixMin) {
                    prixMin = 0;
                } else if (prixMin && prixMax) {
                    if (prixMin >= prixMax) {
                        DigitalSignage4_showErrorMessage("{$t::getTraduction( "Prix_min_sup_prix_max")}", false);
                        requestIsValid = false;
                    }
                }

                form.append("prixMin", prixMin);
                form.append("prixMax", prixMax);
                form.append('request', 'calcul_nb_pdt_Lot');

                var xhr = new XMLHttpRequest();
                xhr.open('POST', '', true);
                xhr.onload = function () {
                    let response = this.responseText;
                    if (isJson(response)) {
                        response = JSON.parse(response);
                        if (confirm('Confirmez-vous la création de vidéos pour '+response['nb']+' produit(s) ?')) {
                            sendForm();
                        }
                    }
                };

                xhr.send(form);
            }

            function create_new_playlist() {

                let playlistName = document.getElementById('new_playlist_name').value;

                if (!playlistName) {
                    DigitalSignage4_showErrorMessage("{$t::getTraduction( "Nom_playlist_vide")}");
                    return;
                }

                let form = new FormData;
                form.append('new_playlist_name', playlistName);
                form.append('request', 'add_playlist');

                var xhr = new XMLHttpRequest();
                xhr.open('POST', '', true);

                xhr.onload = function () {

                    let response = this.responseText;

                    if (isJson(response)) {

                        response = JSON.parse(response);

                        //      console.log(response);

                        if (response[1] && response[0]) {

                            let option = document.createElement('option');
                            option.innerHTML = "(" + response[1] + ") " + response[0];
                            option.value = response[1];
                            option.selected = true;
                            document.getElementById('playlist').appendChild(option);

                            DigitalSignage4_showSuccessMessage("{$t::getTraduction( "Playlist_enregistree")}");
                            document.getElementById('new_playlist_name').value = "";

                        } else {
                            DigitalSignage4_showErrorMessage("{$t::getTraduction( "Playlist_non_cree")}");
                        }

                    } else {
                        DigitalSignage4_showErrorMessage("{$t::getTraduction( "Playlist_non_enregistree")}");
                    }

                };

                xhr.send(form);

            }


            function isJson(str) {
                try {
                    JSON.parse(str);
                } catch (e) {
                    return false;
                }
                return true;
            }


           // toggleDisplayMore(document.getElementById("sell"));
/*
            function toggleDisplayMore(button) {
                if (button.checked === true) {
                    document.getElementById(button.id + '_more').style.display = "block";
                } else {
                    hideDisplayMore();
                }
            }
			


            function hideDisplayMore() {
                document.getElementById('sell_more').style.display = "none";
            }
*/

            function sendForm() {

                document.getElementById('sendForm').disabled = true;

                let requestIsValid = true;

                let id_playlist = currentPlaylistId;

                let form = new FormData();

                form.append("id", id_playlist);

                let name = document.getElementById('name').value;
                form.append("name", name);

                if (!name) {
                    DigitalSignage4_showErrorMessage("{$t::getTraduction( "Nom_auto_vide")}", false);
                    requestIsValid = false;
                }

               // let sell = document.getElementById("sell").checked;
               // form.append("sell", sell);

                //let creation = document.getElementById("create").checked;
                //form.append("creation", creation);

                //if (!sell && !creation) {
                //    DigitalSignage4_showErrorMessage("{$t::getTraduction( "Auto_pas_type")}", false);
                //    requestIsValid = false;
                //}
				

                let playlist = null;
                if (document.getElementById('activer_p').checked) {
                    playlist = document.getElementById('playlist').value;
                    if (!playlist) {
                        DigitalSignage4_showErrorMessage("{$t::getTraduction( "choix_playlist_vide")}", false);
                        requestIsValid = false;
                    }
                }
                form.append("playlist", playlist);


                var gabarit = document.querySelector('input[name="gabarit"]:checked');
                if (gabarit) {
                    form.append("gabarit", gabarit.value);
                } else {
                    DigitalSignage4_showErrorMessage("{$t::getTraduction( "choix_gabarit_vide")}", false);
                    requestIsValid = false;
                }

                let categories = Array.from(document.querySelectorAll('.caseCategorie input[type="checkbox"]:not(.when):checked')).map(function (categorie) {
                    return categorie.value;
                });
                form.append("categories", categories);

				
                let when = Array.from(document.querySelectorAll('.when:checked')).map(function (when) {
                    return when.value;
                });
                form.append("when", when);
				

                let prixMin = parseInt(document.getElementById("min").value);
                let prixMax = parseInt(document.getElementById("max").value);


                if ((prixMin === 0 && prixMax === 0) || (!prixMin && !prixMax)) {
                    prixMin = -1;
                    prixMax = -1;
                } else if (!prixMax && prixMin) {
                    prixMax = -1; // unlimited
                } else if (prixMax && !prixMin) {
                    prixMin = 0;
                } else if (prixMin && prixMax) {
                    if (prixMin >= prixMax) {
                        DigitalSignage4_showErrorMessage("{$t::getTraduction( "Prix_min_sup_prix_max")}", false);
                        requestIsValid = false;
                    }
                }

                form.append("prixMin", prixMin);
                form.append("prixMax", prixMax);

                let creationNbProduit = 0;
                let creationNbJours = 0;
/*
                if (sell) {

                    //creationNbProduit = document.getElementById("nbProduits").value;
                    //creationNbJours = document.getElementById("nbJours").value;

                    if (!creationNbProduit || !creationNbJours) {
                        DigitalSignage4_showErrorMessage("{$t::getTraduction( "Parametres_auto_ventes")}", false);
                        requestIsValid = false;
                    }

                }
				*/

                if (!requestIsValid) {
                    document.getElementById('sendForm').disabled = false;
                    return false;
                }

                //form.append('sellNbJours', creationNbJours);
                //form.append('sellNbProduit', creationNbProduit);

                form.append('save_lot', true);


                var xhr = new XMLHttpRequest();
                xhr.open('POST', '', true);
                xhr.onload = function () {
                    // do something to response

                    document.getElementById('sendForm').disabled = false;

                    let responseCode = this.responseText.split(":")[0];

                    if (responseCode === "ok") {

                        DigitalSignage4_showSuccessMessage("{$t::getTraduction( "Auto_save")}");
                        id_playlist = this.responseText.split(":")[1];

                        //Changement de l'url avce ajout de l'id de l'auto créée en cas de rechargement par f5 de la page
                        currentPlaylistId = id_playlist;
                        const nextURL = window.location.href + '&auto_id=' + id_playlist;
                        const nextTitle = '';
                        const nextState = '';
                        window.history.pushState(nextState, nextTitle, nextURL);

                    } else {
                        DigitalSignage4_showErrorMessage(this.responseText);
                    }

                };

                xhr.send(form);
            }

        </script>

    </div>
{/block}
