<?php

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

require_once __DIR__ ."/../../../Classes/DigitalSignage4_caller.php";
require_once __DIR__ ."/../../../Kernel/API/Entity/DigitalSignage4_DemandeEntity.php";
require_once __DIR__ ."/../../../Kernel/API/Entity/DigitalSignage4_GabaritEntity.php";
require_once __DIR__ ."/../../../Kernel/API/Linker/DigitalSignage4_API_Linker.php";
require_once __DIR__ ."/../../../Kernel/API/Linker/DigitalSignage4_CMS_Linker.php";
require_once __DIR__ ."/../../../Kernel/Translations/DigitalSignage4_Translate.php";
require_once "DigitalSignage4_Manager.php";

class DigitalSignage4_DemandeManager extends DigitalSignage4_Manager
{
    private $managerEntityName = "Demande";
    private $database_caller = null;

    public function __construct($caller)
    {
        if ($caller instanceof DigitalSignage4_CMS_Linker) {
            $this->database_caller = $caller;
        }
    }

    /**
     * @throws DigitalSignage4_Exception
     */
    public static function set($cms_linker)
    {
        if (!$cms_linker instanceof DigitalSignage4_CMS_Linker) {
            throw new DigitalSignage4_Exception(esc_html(DigitalSignage4_Translate::getTraduction('mauvais_cms_linker')));
        } else {
            return new DigitalSignage4_DemandeManager($cms_linker);
        }
    }

    /**
     * @param array $needle
     *
     * @return array|DigitalSignage4_DemandeEntity[]
     * @throws DigitalSignage4_Exception
     */
    public function getDemandes($needle = array())
    {
        if (! empty($needle)) {
            $needle = "?" . implode("&", $needle);
        } else {
            $needle = "";
        }

        $demandes = DigitalSignage4_API_Linker::get_entitys($this->managerEntityName . $needle, get_class(new DigitalSignage4_DemandeEntity()), DigitalSignage4_ForfaitManager::instance()->getToken());

        return $demandes;
    }

    /**
     * @param DigitalSignage4_DemandeEntity $demande
     *
     * @throws DigitalSignage4_Exception
     */
    public function postDemande($demande)
    {
        $demandeIsGood = true;
        $datas         = array();

        // Verification du type du parametre
        if (! $demande instanceof DigitalSignage4_DemandeEntity) {
            throw new DigitalSignage4_Exception(esc_html(DigitalSignage4_Translate::getTraduction('attribut_faux', '1', 'postDemande', 'DigitalSignage4_DemandeEntity')));
        }

        // Verification si tous les champs de base sont presents
        if (null === ($demande->getGabarit())) {
            $demandeIsGood = false;
            $this->addUserMessage(DigitalSignage4_Translate::getTraduction('champ_obligatoir', "gabarit"));
        }

        if (null === ($demande->getAutomatique())) {
            $demandeIsGood = false;
            $this->addUserMessage(DigitalSignage4_Translate::getTraduction('champ_obligatoir', "automatique"));
        }

        if (null === ($demande->getProductId())) {
            $demandeIsGood = false;
            $this->addUserMessage(DigitalSignage4_Translate::getTraduction('champ_obligatoir', "product_id"));
        }
        
        // Récuperation du gabarit de la demande
        if ($demandeIsGood) {
            $gabarit  = DigitalSignage4_GabaritManager::instance()->getGabarit($demande->getGabarit());

            if (!$gabarit) {
                $demandeIsGood = false;
                $this->addUserMessage(DigitalSignage4_Translate::getTraduction('champ_faux', "gabarit"));
            }
        }
        // Vérification des champs du gabarit
        if ($demandeIsGood) {
            $demandeDatas = $demande->getData();

            foreach ($gabarit->getChamps() as $neededChamp) {
                if (! isset($demandeDatas[$neededChamp['name']])) {
                    $demandeIsGood = false;
                    $this->addUserMessage(DigitalSignage4_Translate::getTraduction('champ_obligatoir', $neededChamp['name']));
                } else {

                    // Si le parametre est une image alors on fait un check supplementaire
                    if ($neededChamp['type'] == "picture") {

                        // Verification de l'existance du fichier
                        if (! file_exists($demandeDatas[ $neededChamp['name'] ])) {
                            $demandeIsGood = false;
                            $this->addUserMessage(DigitalSignage4_Translate::getTraduction('image_introuvable', sanitize_text_field(wp_unslash($demandeDatas[ $neededChamp['name'] ]))));
                        } else {

                            // Vérification de l'exctension du fichier
                            $extension = explode(".", $demandeDatas[ $neededChamp['name'] ]);
                            $extension = array_pop($extension);
                            if (! in_array($extension, array( "png", "jpg", "jpeg", "gif", "webp" ))) {
                                $demandeIsGood = false;
                                $this->addUserMessage(DigitalSignage4_Translate::getTraduction('image_type_faux', sanitize_text_field(wp_unslash($demandeDatas[ $neededChamp['name'] ]))));
                            } else {
                                /*if (function_exists('curl_file_create')) { // php 5.5+
                                    $cFile = curl_file_create(sanitize_text_field($demandeDatas[ $neededChamp['name'] ]));
                                } else { //
                                    $cFile = '@' . realpath(sanitize_text_field($demandeDatas[ $neededChamp['name'] ]));
                                }*/
                                $uploads = wp_upload_dir();
                                $cFile = str_replace($uploads['basedir'], $uploads['baseurl'], sanitize_text_field(wp_unslash($demandeDatas[ $neededChamp['name']])));

                                $datas[ $neededChamp['name'] ] = $cFile;
                            }
                        }
                    } else {
                        $datas[ $neededChamp['name'] ] = sanitize_text_field(wp_unslash($demandeDatas[ $neededChamp['name'] ]));
                    }
                }
            }
        }

        // Verification des champs obligatoirs des gaabrit
        foreach (array( 'video_name', 'video_comment' ) as $neededChamp) {
            $datas[ $neededChamp ] = (isset($demandeDatas[ $neededChamp ])) ? $demandeDatas[ $neededChamp ] : "";
        }

        // Envois de la demandes
        if ($demandeIsGood) {
            $datas = array_merge($datas, array(
                'gabarit'       => $demande->getGabarit(),
                'automatique'   => $demande->getAutomatique(),
                'product_id'    => $demande->getProductId(),
                'video_name'    => $demande->getVideoName(),
                'video_comment' => $demande->getVideoComment(),
                'downloaded'    => '0',
                'video_deleted' => '0',
                'youtube_data' => $demande->getYoutubeData()
            ));

            $demande = DigitalSignage4_API_Linker::post($this->managerEntityName, $datas, DigitalSignage4_ForfaitManager::instance()->getToken());

            if ($demande->getResponseCode() >= 400) {
                foreach ($demande->getErrors() as $error) {
                    $this->addUserMessage(DigitalSignage4_Translate::getTraduction('api_erreur', $error));
                }
            } else {
                $demandeE = new DigitalSignage4_DemandeEntity();
                $demandeDatas = $demande->getDatas();
                $demandeE->hydrate($demandeDatas[0]);

                return $demandeE;
            }
        }
        return false;
    }

    /**
     * @param $sql
     *
     * @return array|mixed|DigitalSignage4_DemandeEntity[]
     */
    public function getLocalDemandes($sql)
    {
        $videos = $this->database_caller->execute_video_request($sql);


        if ($videos) {
            foreach ($videos as $key => $video) {
                $videoEntity = new DigitalSignage4_DemandeEntity();
                $video = $videoEntity->hydrate($video);

                if ($video) {
                    $gabarit = DigitalSignage4_GabaritManager::instance()->getGabarit($video->getGabarit());
                    $video->setGabarit($gabarit);
                    $videos[ $key ] = $video;
                }
            }

            return $videos;
        }

        return array();
    }
}
