<?php

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

    require_once __DIR__ . "/../Kernel/API/Linker/DigitalSignage4_CMS_Linker.php";
	

    class DigitalSignage4_caller implements DigitalSignage4_CMS_Linker
    {
        //saved database champs name
        public const FORFAIT = "DigitalSignage4_forfait";
        public const DISK_FREE_SPACE = "DigitalSignage4_disk_free_space";
        public const WATERMARK = "DigitalSignage4_watermark";
        public const SITE = "DigitalSignage4_site";
        public const PLAYLISTS = "DigitalSignage4_playlist";
        public const AUTOMATISATIONS = "DigitalSignage4_automatisation";
        public const PLACEMENT = "DigitalSignage4_placement";
        public const RESOLUTION = "DigitalSignage4_resolution";
        public const PRIX_FORMAT = "DigitalSignage4_prix_format";
        public const DISPLAYED_VIDEO_PODUCT = "DigitalSignage4_displayed_video_product";
        public const AUTOMATISATION_TRACE = "DigitalSignage4_automatisation_date_last_good_execution";
        public const YOUTUBE_JSON = "DigitalSignage4_Youtube_json";

        public const SQL_VIDEO_DATABASE_NAME = "digitalsignage_video";

        public static $tableExiste = false;

        public static function getInstance()
        {
            return new DigitalSignage4_caller();
        }

        public function save_data($name_data, $data)
        {
            $data = serialize($data);
            return update_option($name_data, $data);
        }

        public function get_data($name)
        {
            $datas = get_option($name);
            if ($datas) {
                $datas = unserialize($datas);

                if ($datas instanceof __PHP_Incomplete_Class) {
                    return false;
                }

                if (is_array($datas) && isset($datas[0])) {
                    $el = $datas[0];
                    if ($el instanceof __PHP_Incomplete_Class) {
                        return false;
                    }
                }

                return $datas;
            }

            return false;
        }

        public function delete_data($name)
        {
            return delete_option($name);
        }

        public static function get_video_table_name()
        {
            global $wpdb;

            return $wpdb->prefix . self::SQL_VIDEO_DATABASE_NAME;
        }

        public function create_video_table()
        {
            global $wpdb;

            // Création de la table ds4 si elle n'existe pas
            $request = "CREATE TABLE if NOT EXISTS `" . $this->get_video_table_name() . "` (
                  `id_demande` INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
                  `data` text NOT NULL,
                  `AE_version` varchar(255) NOT NULL,
                  `liste_id_boxes` varchar(255) NOT NULL DEFAULT '',
                  `flag` varchar(255) NOT NULL DEFAULT 'waiting',
                  `id_thread` varchar(255) NOT NULL,
                  `id_compte` int NOT NULL,
                  `video_name` varchar(255) NOT NULL,
                  `video_comment` varchar(255) NOT NULL,
                  `date_begin` date NOT NULL,
                  `automatique` int NOT NULL DEFAULT '0',
                  `date_end` date NOT NULL,
                  `date_demande` datetime NOT NULL,
                  `gabarit` int NOT NULL,
                  `video_url` varchar(500) NOT NULL,
                  `video_hash` varchar(1000) NOT NULL DEFAULT '',
                  `product_id` varchar(500) NOT NULL DEFAULT '',
				  `youtube_data` text NOT NULL,
				  `youtube_id` varchar(255) NOT NULL DEFAULT ''				  
               )  " . $wpdb->get_charset_collate();
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($request);
			
			
			$sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix ."digitalsignage_gabarit ( 
					`id` INT(11) NOT NULL AUTO_INCREMENT , 
					`id_gabarit` INT(11) NOT NULL,
					`parameters` text NOT NULL DEFAULT '',
					PRIMARY KEY (`id`), 
					INDEX (`id_gabarit`))";
			dbDelta($sql);
		
            $this->checkTableExiste();

            return self::$tableExiste;
        }

        public function checkTableExiste()
        {
            global $wpdb;
            $wpdb->hide_errors();
            $wpdb->get_var('SELECT COUNT(*) FROM `' . $this->get_video_table_name() . '` WHERE 1');
            $wpdb->show_errors();
            self::$tableExiste = empty($wpdb->last_error);
        }

        public function execute_video_insert($request)
        {
            $this->checkTableExiste();

            // Si tous les prerequis ne sont pas present (table ds4 et wooCommerce) alors on quite dans message d'erreur car il sont deja geré par d'autres scripts
            if (DigitalSignage4_Tools::isPrestashop()) {
                if (!self::$tableExiste) { // les settings de presta sont pas bon
                    return false;
                }
            } else {
                if (!$this->wordpressModuleOk() || !self::$tableExiste) { // les settings de wordpress sont pas bon
                    return false;
                }
            }


            global $wpdb;

            // Reconstition de la requete sql

            $sql =$request;

            $results = $wpdb->query($sql);

            if ($results) {
                return $wpdb->insert_id;
            } else {
                return false;
            }
        }

        public function wordpressModuleOk()
        {
            if (!class_exists('WooCommerce') || !in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
                return false;
            }
            return true;
        }


        public function execute_video_request($request)
        {
            $this->checkTableExiste();

            // Si tous les prerequis ne sont pas present (table ds4 et wooCommerce) alors on quite dans message d'erreur car il sont deja geré par d'autres scripts
            if (DigitalSignage4_Tools::isPrestashop()) {
                if (!self::$tableExiste) { // les settings de presta sont pas bon
                    return false;
                }
            } else {
                if (!$this->wordpressModuleOk() || !self::$tableExiste) { // les settings de wordpress sont pas bon
                    return false;
                }
            }

            global $wpdb;

            // Reconstition de la requete sql

            $results = $wpdb->get_results($request, "ARRAY_A");

            if ($request) {
                return $results;
            } else {
                return false;
            }
        }

        private function custom_sprintf($sql, $table)
        {
            return $this->str_replace_once('%s', $table, $sql);
        }

        public function str_replace_once($str_pattern, $str_replacement, $string)
        {
            if (strpos($string, $str_pattern) !== false) {
                $occurrence = strpos($string, $str_pattern);

                return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern));
            }

            return $string;
        }
    }
