<?php

namespace Controllers;

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

use Classes\DigitalSignage4_Tools2;
use Classes\DigitalSignage4_Tools;
use Kernel\Translations\Translate;
use Classes\DigitalSignage4_caller;
use Kernel\API\Entity\AutomatisationEntity;
use Kernel\API\Entity\DigitalSignage4_PlaylistEntity;
use Kernel\API\Manager\DigitalSignage4_AutomatisationManager;
use Kernel\API\Manager\DigitalSignage4_Exception;
use Kernel\API\Manager\DigitalSignage4_GabaritManager;
use Kernel\API\Manager\DigitalSignage4_PlaylistManager;

class DigitalSignage4_CreationController extends Controller
{
    public function generatePage()
    {
        check_admin_referer( 'ds4_form_nonce' );
        $this->handleAjaxRequest($_POST);

        $vue = (isset($_GET['automatisationVue'])) ? (sanitize_text_field(wp_unslash($_GET['automatisationVue']))) : 'liste';

        $autos = ( new DigitalSignage4_AutomatisationManager(new DigitalSignage4_caller()) )->get_automatisations();

        foreach ($autos as $key => $auto) {
            $playlist = ( new DigitalSignage4_PlaylistManager(new DigitalSignage4_caller()) )->get_playlist($auto->getPlaylist());
            if ($playlist) {
                $autos[ $key ]->setPlaylist($playlist);
            } else {
                $autos[ $key ]->setPlaylist(null);
            }
        }

        if ($vue == "liste") {
            $this->assign(array(
                'pageProduits'    => DigitalSignage4_Tools::getProductsUrl(),
                'automatisations' => $autos,
                "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",
                'playlistBaseUrl' => DigitalSignage4_Tools2::getUrlRedirect('mes_playlists'),
                'form_nonce' => wp_nonce_field( 'ds4_form_nonce' ),
            ));
            $this->setWPTemplate("Creation_video/creation");
        } else {
            if (isset($_POST)) {
                if (isset($_POST['save_automatisation'])) {
                    $name = isset($_POST['name'])?sanitize_text_field(wp_unslash($_POST['name'])):"";
                    $categories = isset($_POST['categories'])?sanitize_text_field(wp_unslash($_POST['categories'])):"";
                    $sellNbProduit = isset($_POST['sellNbProduit'])?sanitize_text_field(wp_unslash($_POST['sellNbProduit'])):"";
                    $sellNbJours = isset($_POST['sellNbJours'])?sanitize_text_field(wp_unslash($_POST['sellNbJours'])):"";
                    $gabarit = isset($_POST['gabarit'])?sanitize_text_field(wp_unslash($_POST['gabarit'])):"";
                    $playlist = isset($_POST['playlist'])?sanitize_text_field(wp_unslash($_POST['playlist'])):"";

                    ob_get_clean();
                    ob_start();

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

                    $tmpId = isset($_POST['id'])?sanitize_text_field(wp_unslash($_POST['id'])):false;
                    if (!$tmpId) {
                        $id     = ( new DigitalSignage4_AutomatisationManager(new DigitalSignage4_caller()) )->get_last_id() + 1;
                        $update = false;
                    } else {
                        $id     = $tmpId;
                        $update = true;
                    }

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


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

                        if ($update) {
                            if ($automatisationInstance->get_automatisation($id) == $automatisation) {
                                echo esc_html(Translate::getTraduction("Parametres_inchangé"));
                            } else {
                                if (( new DigitalSignage4_AutomatisationManager(new DigitalSignage4_caller()) )->update_automatisation($automatisation)) {
                                    echo esc_html("ok:" . $id);
                                } else {
                                    echo esc_html(Translate::getTraduction("MAJ_bdd_impossible"));
                                }
                            }
                        } else {
                            if (( new DigitalSignage4_AutomatisationManager(new DigitalSignage4_caller()) )->add_automatisation($automatisation)) {
                                echo esc_html("ok:" . $id);
                            } else {
                                echo esc_html(Translate::getTraduction("MAJ_bdd_impossible"));
                            }
                        }
                    } catch (DigitalSignage4_Exception $e) {
                        echo esc_html("erreur : " . $e->getMessage());
                    }

                    die(esc_html(ob_get_clean()));
                }
            }

            $this->assign(array(
                'playlists' => ( new DigitalSignage4_PlaylistManager(new DigitalSignage4_caller()) )->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 handleAjaxRequest($post)
    {
        if (isset($post['request'])) {
            ob_get_clean();
            ob_start();

            try {
                $request = sanitize_text_field(wp_unslash($post['request']));
                switch ($request) {

                    case 'changeActive':

                        $id      = sanitize_text_field(wp_unslash($post['automatisationId']));
                        $active  = sanitize_text_field(wp_unslash($post['active']));
                        $autoc   = new DigitalSignage4_AutomatisationManager(new DigitalSignage4_caller());
                        $automat = $autoc->get_automatisation($id);

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

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

                        break;


                    case 'delete':

                        if (( new DigitalSignage4_AutomatisationManager(new DigitalSignage4_caller()) )->remove_automatisation(( new DigitalSignage4_AutomatisationManager(new DigitalSignage4_caller()) )->get_automatisation(sanitize_text_field(wp_unslash($post['id']))))) {
                            echo esc_html("ok");
                        } else {
                            echo esc_html(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(( new DigitalSignage4_caller() ));
                            $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;
                            }
                        }

                        echo wp_json_encode(array( $playlist_name, $playlist_id ));

                        break;

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

            die(esc_html(ob_get_clean()));
        }
    }

    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 = ( new DigitalSignage4_AutomatisationManager(new DigitalSignage4_caller()) )->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;
    }
}
