<?php

/**
 * Plugin Name: Product Video Generator
 * Plugin URI: https://www.productvideo.io/
 * Version: 1.0.16
 * Description: Sell more of your products with quality videos created automatically from all the elements of your product sheets. Create in one click videos adapted to events: Sales, promotions, Valentine's Day, Christmas, Black Friday, ...
 * Author: Acacia Dynamic
 * Author URI: https://www.acacia-dynamic.com/
 * Text Domain: digitalsignage4
 * License: GPLv2 or later
 * Domain Path: /languages
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 **/

//error_reporting( E_ALL );
if ( ! defined( 'ABSPATH' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	exit;
}

require_once __DIR__ ."/Classes/DigitalSignage4_FrontShortcodeVideoDisplayer.php";
require_once __DIR__ ."/Classes/DigitalSignage4_caller.php";
require_once __DIR__ ."/Classes/DigitalSignage4_Ajax.php";
require_once __DIR__ ."/Classes/DigitalSignage4_Tools.php";
require_once __DIR__ ."/controllers/hook/DigitalSignage4_AutomatisationHookControllerCreation.php";
require_once __DIR__ ."/controllers/override/DigitalSignage4_wooCommerceProductOverride.php";
require_once __DIR__ ."/controllers/DigitalSignage4_ParametreController.php";
require_once __DIR__ ."/controllers/DigitalSignage4_PlaylistsController.php";
require_once __DIR__ ."/controllers/DigitalSignage4_PresentationController.php";
require_once __DIR__ ."/controllers/DigitalSignage4_VideoController.php";
require_once __DIR__ ."/controllers/DigitalSignage4_GabaritController.php";
require_once __DIR__ ."/Kernel/API/Manager/DigitalSignage4_Exception.php";
require_once __DIR__ ."/Kernel/API/Manager/DigitalSignage4_ForfaitManager.php";
require_once __DIR__ ."/Kernel/Translations/DigitalSignage4_Translate.php";







// Point d'entrée du module
new digitalsignage4();

// Class d'entrée du module, inclusion des hooks
class digitalsignage4
{
    private static $userAliveAlreadyChecked = false;

    /**
     * Method for the translation
     */
    public function digitalsignage4_load_textdomain()
    {
        load_plugin_textdomain(
            'digitalsignage4',
            false,
            dirname( plugin_basename( __FILE__ ) ) . '/languages/'
        );

    }
    
    
    /**
     * digitalsignage constructor.
     */
    public function __construct()
    {
        DigitalSignage4_Translate::setLang(substr(get_bloginfo('language'), 0, 2));
        add_action( 'init', array( $this , 'digitalsignage4_load_textdomain') );
        //permet de traduire la description du module qui est en commentaire
		
		
        $all_active_plugins = get_option('active_plugins');
        if (is_multisite()) {
                $all_active_plugins = array_merge($all_active_plugins, wp_get_active_network_plugins());
        }

        $all_active_plugins = apply_filters('active_plugins', $all_active_plugins);
        if (! stripos(implode($all_active_plugins), '/woocommerce.php')) {
                //deactivate_plugins(plugin_basename(__FILE__)); // Deactivate ourself.



                wp_die(esc_html('Désolé ! Pour utiliser Digitalsignage vous devez installer et activer le plugin WooCommerce.'), esc_html('Digitalsignage for WooCommerce'), array('back_link' => true));
        }

        
        DigitalSignage4_FrontShortcodeVideoDisplayer::init();

        // tabs
        add_action('admin_menu', array( $this, 'add_digitalsignage_tabs' )); // Ajout du hooks des tabs du module
        
        // styles and scripts
        add_action('admin_enqueue_scripts',array( $this, 'setModuleBackofficeStyle' ));
        add_action('admin_enqueue_scripts', array($this, 'setModuleBackofficeScripts'));

        // custom vidéo database
        register_activation_hook(__FILE__, [$this, 'installCustomDbVideo']);

        //add_action('init', array( $this, 'init' ));
        add_action('wp_enqueue_scripts', array($this, 'init'));
        add_action('admin_enqueue_scripts', array($this, 'init'));

        // meta box dans les pages d'articles
        add_action('add_meta_boxes', array( $this, 'digital_signage_metabox' ));
        
        //all ajax actions
        add_action('wp_ajax_CreationVideoSpecialDataProviderAjaxHandler','digitalSignage4_ajax_CreationVideoSpecialDataProviderAjaxHandler');
        add_action('wp_ajax_nopriv_CreationVideoSpecialDataProviderAjaxHandler','digitalSignage4_ajax_CreationVideoSpecialDataProviderAjaxHandler');
        add_action('wp_ajax_UpdateVideoAjaxHandler','digitalSignage4_ajax_UpdateVideoAjaxHandler');
        add_action('wp_ajax_nopriv_UpdateVideoAjaxHandler','digitalSignage4_ajax_UpdateVideoAjaxHandler');
        add_action('wp_ajax_DisplayedVideoProductAjaxHandler','digitalSignage4_ajax_DisplayedVideoProductAjaxHandler');
        add_action('wp_ajax_nopriv_DisplayedVideoProductAjaxHandler','digitalSignage4_ajax_DisplayedVideoProductAjaxHandler');
        add_action('wp_ajax_AddVideoAjaxHandler','digitalSignage4_ajax_AddVideoAjaxHandler');
        add_action('wp_ajax_nopriv_AddVideoAjaxHandler','digitalSignage4_ajax_AddVideoAjaxHandler');
        add_action('wp_ajax_AddGabaritCustomizeAjaxHandler','digitalSignage4_ajax_AddGabaritCustomizeAjaxHandler');
        add_action('wp_ajax_nopriv_AddGabaritCustomizeAjaxHandler','digitalSignage4_ajax_AddGabaritCustomizeAjaxHandler');
        add_action('wp_ajax_FrontShortcodeVideoDisplayerAjaxHandler','digitalSignage4_ajax_FrontShortcodeVideoDisplayerAjaxHandler');
        add_action('wp_ajax_nopriv_FrontShortcodeVideoDisplayerAjaxHandler','digitalSignage4_ajax_FrontShortcodeVideoDisplayerAjaxHandler');
        add_action('wp_ajax_CronJobControllerAjaxHandler','digitalSignage4_ajax_CronJobControllerAjaxHandler');
        add_action('wp_ajax_nopriv_CronJobControllerAjaxHandler','digitalSignage4_ajax_CronJobControllerAjaxHandler');
        	
        // Ajouter un lien de réglages dans la liste des plugins
        add_filter('plugin_action_links_' . plugin_basename(__FILE__), array($this,'digital_signage_settings_link'));
		
        // Ajouter le texte "Nécessite WooCommerce" dans la liste des plugins
        add_filter('plugin_row_meta', array($this, 'add_woocommerce_requirement_message'), 10, 2);
		

        register_uninstall_hook( __FILE__, array( &$this, 'ds4_uninstall' ) );
        register_deactivation_hook( __FILE__, array( &$this, 'ds4_deactivation' ) );

        // event sur le changement d'etat d'un article
        add_action('transition_post_status', array(
            new DigitalSignage4_AutomatisationHookControllerCreation(),
            'handleProductChangeStatus'
        ), 9999, 3);

        $this->user_connection_alive();
		
		
    }
	
	
		
	
	static function ds4_deactivation() {
            DigitalSignage4_Tools::callDS4DemandeAPI(array("action"=>"disableNotification", "token"=>DigitalSignage4_ForfaitManager::instance()->getToken()));
        }
        
	static function ds4_uninstall(){
            delete_option(DigitalSignage4_caller::AUTOMATISATION_TRACE);
            delete_option(DigitalSignage4_caller::DISK_FREE_SPACE);
            delete_option(DigitalSignage4_caller::FORFAIT);
            delete_option(DigitalSignage4_caller::PLACEMENT);
            delete_option(DigitalSignage4_caller::PRIX_FORMAT);
            delete_option(DigitalSignage4_caller::SITE);
            delete_option(DigitalSignage4_caller::WATERMARK);
            delete_option(DigitalSignage4_caller::AUTOMATISATIONS);
            delete_option(DigitalSignage4_caller::PLAYLISTS);
            delete_option(DigitalSignage4_caller::DISPLAYED_VIDEO_PODUCT);

            global $wpdb;
            $table_name = DigitalSignage4_caller::get_video_table_name();
            $sql = "DROP TABLE IF EXISTS $table_name";
            $wpdb->query($sql);


            global $wpdb;
            $table_name = $wpdb->prefix .'digitalsignage_gabarit';
            $sql = "DROP TABLE IF EXISTS $table_name";
            $wpdb->query($sql);
                
            DigitalSignage4_Tools::callDS4DemandeAPI(array("action"=>"uninstallNotification", "token"=>DigitalSignage4_ForfaitManager::instance()->getToken()));
	}
	
	// Ajouter le texte "Nécessite WooCommerce"
    public function add_woocommerce_requirement_message($plugin_meta, $plugin_file) {
        if ($plugin_file === plugin_basename(__FILE__)) {
            // Ajouter le texte si WooCommerce n'est pas activé
            //if (!is_plugin_active('woocommerce/woocommerce.php')) {
                $plugin_meta[] = '<span style="color: red;">Nécessite WooCommerce</span>';
            //}
        }
        return $plugin_meta;
    }
	
	
	public function digital_signage_settings_link($links) {
		$settings_link = '<a href="admin.php?page=DigitalSignageSettings">Réglages</a>';
		array_push($links, $settings_link);
		return $links;
	}

	
	
	

    public function setModuleBackofficeStyle($hook)
    {
		
		if (('product-video-generator_page_DigitalSignageHome' !== $hook) &&
			('product-video-generator_page_DigitalSignageVideos' !== $hook) &&
			('product-video-generator_page_DigitalSignagePlaylists' !== $hook) &&
			('product-video-generator_page_DigitalSignagePersoGabarit' !== $hook) &&
			('product-video-generator_page_DigitalSignageSettings' !== $hook) &&
			!($hook === 'post.php' && get_post_type() === 'product') && // Pas l'édition d'un produit WooCommerce
			!($hook === 'post-new.php' && get_post_type() === 'product') // Pas la création d'un nouveau produit WooCommerce
			) {
				//echo 'hook ' . $hook;
			return;
		}
		
		
			
		
		wp_enqueue_style('bootstrapcss', plugins_url('/Kernel/Views/css/bootstrap.min.css', __FILE__), array(), false, 'all');
		wp_enqueue_style('digitalsignage_css', plugins_url('/Kernel/Views/css/styles.css', __FILE__));
    }

    public function setModuleBackOfficeScripts($hook)
    {
        if (('product-video-generator_page_DigitalSignageHome' !== $hook) &&
			('product-video-generator_page_DigitalSignageVideos' !== $hook) &&
			('product-video-generator_page_DigitalSignagePlaylists' !== $hook) &&
			('product-video-generator_page_DigitalSignagePersoGabarit' !== $hook) &&
			('product-video-generator_page_DigitalSignageSettings' !== $hook) &&
			!($hook === 'post.php' && get_post_type() === 'product') && // Pas l'édition d'un produit WooCommerce
			!($hook === 'post-new.php' && get_post_type() === 'product') // Pas la création d'un nouveau produit WooCommerce
			) {
				
			return;
		}
		
		
		wp_enqueue_script('bootstrapjs',  plugins_url('/Kernel/Views/js/bootstrap.min.js', __FILE__), array( 'jquery' ), false, true);
        wp_enqueue_script('digitalsignage_script', plugins_url('/Kernel/Views/js/script.js', __FILE__), array(), false, true);
		
		
    }


    // Ajout des tabs du module au menu admin
    public function add_digitalsignage_tabs()
    {
        $tabs = array(
            array(
                'name'       => DigitalSignage4_Translate::getTraduction("Digital_Signage_4"),
                
                'display'       => DigitalSignage4_Translate::getTraduction("Digital_Signage_4"),
                'slug'       => 'DigitalSignageHome',
                'capability' => "manage_options",
                'callback'   => '',
                'icon'       => 'dashicons-format-video',
                'position'   => 6
            ),
            array(
                'parent_slug' => 'DigitalSignageHome',
                'name'        => DigitalSignage4_Translate::getTraduction("Accueil"),
                'slug'        => 'DigitalSignageHome',
                'capability'  => "manage_options",
                'callback'    => array( new DigitalSignage4_PresentationController(), "generatePage" ),
                'position'    => null
            ),
            array(
                'parent_slug' => 'DigitalSignageHome',
                'name'        => DigitalSignage4_Translate::getTraduction("Videos"),
                'slug'        => 'DigitalSignageVideos',
                'capability'  => "manage_options",
                'callback'    => array( new DigitalSignage4_VideoController(), "generatePage" ),
                'position'    => null
            ),
            array(
                'parent_slug' => 'DigitalSignageHome',
                'name'        => DigitalSignage4_Translate::getTraduction("Playlists"),
                'slug'        => 'DigitalSignagePlaylists',
                'capability'  => "manage_options",
                'callback'    => array( new DigitalSignage4_PlaylistsController(), "generatePage" ),
                'position'    => null
            ),
            array(
                'parent_slug' => 'DigitalSignageHome',
                'name'        => DigitalSignage4_Translate::getTraduction("Modèles"),
                'slug'        => 'DigitalSignagePersoGabarit',
                'capability'  => "manage_options",
                'callback'    => array( new DigitalSignage4_GabaritController(), "generatePage" ),
                'position'    => null
            ),
            array(
                'parent_slug' => 'DigitalSignageHome',
                'name'        => DigitalSignage4_Translate::getTraduction("Reglages"),
                'slug'        => 'DigitalSignageSettings',
                'capability'  => "manage_options",
                'callback'    => array( new DigitalSignage4_ParametreController(), "generatePage" ),
                'position'    => null
            ),
        );


        foreach ($tabs as $tab) {
            if (isset($tab['parent_slug'])) {
                add_submenu_page($tab['parent_slug'], $tab['name'], $tab['name'], $tab['capability'], $tab['slug'], $tab['callback'], $tab['position']);
            } else {
                add_menu_page($tab['display'], $tab['name'], $tab['capability'], $tab['slug'], $tab['callback'], $tab['icon'], $tab['position']);
            }
        }
        
    }

    // Permet la redirection via php en bloquant les affichage d'html avant la redirection
    public function init()
    {
	wp_register_script('digitalsignage_script_front', plugins_url('/Kernel/Views/js/digitalsignage.js', __FILE__), array(), false, true);
        wp_enqueue_script('digitalsignage_script_front');
        wp_add_inline_script( 'digitalsignage_script_front', 'ajax_url="'.esc_js(admin_url( 'admin-ajax.php' )).'";','before' );
        wp_add_inline_script( 'digitalsignage_script_front', 'ajax_nonce="'. esc_js(wp_create_nonce( 'ds4_ajax_nonce')).'";','before' );
        //ob_start();
    }

    public function installCustomDbVideo()
    {
        if (! DigitalSignage4_caller::getInstance()->create_video_table()) {
            $_SESSION['Errors'][] = DigitalSignage4_Translate::getTraduction("Creation_bdd_impossible");
        }
		
		//copy default watermark to uploads
		$upload_dir_global = wp_upload_dir();
		$uploaddir =$upload_dir_global['basedir'] . '/' . 'ds4' . '/Files';
		if (!file_exists($uploaddir)) {
			wp_mkdir_p($uploaddir);
		}
		$uploaddir .='/';
		$uploadfile = $uploaddir . "watermark.png";
		copy(DigitalSignage4_Tools::getModuleImgDir()."watermark.png",$uploadfile);
    }

    public function digital_signage_metabox()
    {
        $screen = 'product';
        if (wc_get_product()) {
            add_meta_box(
                'digital_signage',                 // Unique ID
                DigitalSignage4_Translate::getTraduction("Digital_Signage_4_creation"),      // Box title
                array( $this, 'wporg_custom_box_html' ),  // Content callback, must be of type callable
                $screen                            // Post type
            );
            add_action('save_post','save_wporg_custom_box_html');
        }
    }
    public function save_wporg_custom_box_html($post_id)
    {
        //check_admin_referer( 'ds4_form_nonce' );
    }
    
    public function wporg_custom_box_html()
    {
        $controller = new DigitalSignage4_wooCommerceProductOverride();
        $controller->setArticle(wc_get_product());
        $controller->generatePage();
    }

    
    private function user_connection_alive()
    {
        $forfait = DigitalSignage4_caller::getInstance()->get_data(DigitalSignage4_caller::FORFAIT);

        if ($forfait) {
            DigitalSignage4_ForfaitManager::instance()->setForfait($forfait);
        } elseif (! self::$userAliveAlreadyChecked) { // Si aucun forfait n'existe alors on créer un compte de test pour l'utilisateur

            try {
                $forfait = DigitalSignage4_ForfaitManager::instance()->createForfaitTrial();

                if (!$forfait) {
                    foreach (DigitalSignage4_ForfaitManager::instance()->getUserMessages() as $error) {
                        $_SESSION['Errors'][] = $error;
                    }
                }

                //Paramétrage par défaut
                $datas = array();
                $datas['placement_6'] = true;
                DigitalSignage4_caller::getInstance()->save_data(DigitalSignage4_caller::PLACEMENT, $datas);

                DigitalSignage4_caller::getInstance()->save_data(DigitalSignage4_caller::FORFAIT, $forfait);
            } catch (DigitalSignage4_Exception $e) {
                $e->echoError();
            }
            self::$userAliveAlreadyChecked = true;
        }
    }
}
