<?php
/*
Plugin Name:  Solution Webcollectivités
Plugin URI:   https://www.webcollectivites.fr
Description:  Gestion des différents modules de webcollectivites
Version:      250404-3
Author:       Romain PONCET
Author URI:   https://www.webcollectivites.fr
License:      GPL2
License URI:  https://www.gnu.org/licenses/gpl-2.0.html

@Ressources :
https://code.tutsplus.com/tutorials/distributing-your-plugins-in-github-with-automatic-updates--wp-34817
https://stackoverflow.com/questions/48493641/why-am-i-getting-this-error-with-a-php-curl-request-to-the-github-api-when-it-wo/48572038

*/


if ( !function_exists( 'add_action' ) ) {
    exit;
}

if ( version_compare(PHP_VERSION, '5.5', '<') ) {
    wp_die('PHP version 5.6 minimum est recquis pour installer ce plugin.');
};

global $wpdb;

if(!defined('GITHUB_TOKEN')) define ('GITHUB_TOKEN', '');
if(!defined('WEBCO_VERSION')) define( 'WEBCO_VERSION', '250404-3' );
if(!defined('WEBCO_PATH')) define( 'WEBCO_PATH', plugin_dir_path(__FILE__) );
if(!defined('WEBCO_URL')) define( 'WEBCO_URL', plugin_dir_url(__FILE__) );
if(!defined('WEBCO_TABLE')) define( 'WEBCO_TABLE', $wpdb->prefix . 'webco_modules' );
if(!defined('WEBCO_PREFIX')) define( 'WEBCO_PREFIX', 'webco_' );
if(!defined('solutionWebco')) define( 'solutionWebco', true );
if(!defined('WEBCO_API_URL')) define( 'WEBCO_API_URL', 'https://maintenance.webcollectivites.fr/wp-json/wp/v2/' );


if(!class_exists('Webcollectivites')){
    class Webcollectivites
    {

        const needleName = "Plugin Name: ";

		public $plugin_slug;
		public $version;
		public $cache_key;
		public $cache_allowed;

        public function __construct( $pluginFile, $gitHubUsername, $gitHubProjectName, $accessToken = '' )
        {

            register_activation_hook(__FILE__, array($this, 'install'));
//            register_deactivation_hook(__FILE__, array($this, 'uninstall'));

            $this->plugin_slug = plugin_basename( __DIR__ );
			$this->version = '250404-3';
			$this->cache_key = 'misha_custom_upd';
			$this->cache_allowed = false;

			add_filter( 'plugins_api', array( $this, 'info' ), 20, 3 );
			add_filter( 'site_transient_update_plugins', array( $this, 'update' ) );
			add_action( 'upgrader_process_complete', array( $this, 'purge' ), 10, 2 );

            $this->init(false);

            $this->execOptions();

            // Création du menu
            add_action('admin_menu', array($this, 'create_menu_page'));

            // Ajout CSS partout dans le BO
            add_action( 'admin_init', array($this, 'solutionWebcoCssBo') );

            // Action déclenchée par AJAX
            add_action('wp_ajax_majOptionWebcoAjax', array($this, 'majOptionWebcoAjax'));

            //Déclenchement CRONs
            add_action('actionCronPrivacyPolicy', array($this,'cronPrivacyPolicy'));
            add_action('actionCronLegals', array($this,'cronLegals'));
            add_action('actionCronAccessibility', array($this,'cronAccessibility'));

            // add_action('wp_login', array($this, 'notifyAdminLogin', 10, 2));

            $webcoOption = get_option(WEBCO_PREFIX.'options');

            if(isset($webcoOption['webcoAideMenu']) && $webcoOption['webcoAideMenu'] == 'true') {
                add_action('admin_bar_menu', array($this, 'webcoMajAdminMenu'), 999);
            }


        }

public function request(){

			$remote = get_transient( $this->cache_key );

			if( false === $remote || ! $this->cache_allowed ) {

				$remote = wp_remote_get(
					'https:',
					array(
						'timeout' => 10,
						'headers' => array(
							'Accept' => 'application/json'
						)
					)
				);

				if(
					is_wp_error( $remote )
					|| 200 !== wp_remote_retrieve_response_code( $remote )
					|| empty( wp_remote_retrieve_body( $remote ) )
				) {
					return false;
				}

				set_transient( $this->cache_key, $remote, DAY_IN_SECONDS );

			}

			$remote = json_decode( wp_remote_retrieve_body( $remote ) );

			return $remote;

		}


		function info( $res, $action, $args ) {

			// print_r( $action );
			// print_r( $args );

			// do nothing if you're not getting plugin information right now
			if( 'plugin_information' !== $action ) {
				return $res;
			}

			// do nothing if it is not our plugin
			if( $this->plugin_slug !== $args->slug ) {
				return $res;
			}

			// get updates
			$remote = $this->request();

			if( ! $remote ) {
				return $res;
			}

			$res = new stdClass();

			$res->name = $remote->name;
			$res->slug = $remote->slug;
			$res->version = $remote->version;
			$res->tested = $remote->tested;
			$res->requires = $remote->requires;
			$res->author = $remote->author;
			$res->author_profile = $remote->author_profile;
			$res->download_link = $remote->download_url;
			$res->trunk = $remote->download_url;
			$res->requires_php = $remote->requires_php;
			$res->last_updated = $remote->last_updated;

			$res->sections = array(
				'description' => $remote->sections->description,
				'installation' => $remote->sections->installation,
				'changelog' => $remote->sections->changelog
			);

			if( ! empty( $remote->banners ) ) {
				$res->banners = array(
					'low' => $remote->banners->low,
					'high' => $remote->banners->high
				);
			}

			return $res;

		}

		public function update( $transient ) {

			if ( empty($transient->checked ) ) {
				return $transient;
			}

			$remote = $this->request();

			if(
				$remote
				&& version_compare( $this->version, $remote->version, '<' )
				&& version_compare( $remote->requires, get_bloginfo( 'version' ), '<=' )
				&& version_compare( $remote->requires_php, PHP_VERSION, '<' )
			) {
				$res = new stdClass();
				$res->slug = $this->plugin_slug;
				$res->plugin = plugin_basename( __FILE__ ); // misha-update-plugin/misha-update-plugin.php
				$res->new_version = $remote->version;
				$res->tested = $remote->tested;
				$res->package = $remote->download_url;

				$transient->response[ $res->plugin ] = $res;

	    }

			return $transient;

		}

		public function purge( $upgrader, $options ){

			if (
				$this->cache_allowed
				&& 'update' === $options['action']
				&& 'plugin' === $options[ 'type' ]
			) {
				// just clean the cache when new plugin version is installed
				delete_transient( $this->cache_key );
			}

		}

        public function install()
        {
            global $wpdb;
            $charset_collate = $wpdb->get_charset_collate();

            $sql = "CREATE TABLE IF NOT EXISTS ".WEBCO_TABLE." (
                    id INT(9) NOT NULL AUTO_INCREMENT,
                    module_nom varchar(128) NOT NULL,
                    module_nom_dossier varchar(200) NOT NULL,
                    module_actif varchar(200) NOT NULL,
                    UNIQUE KEY id (id)
                    ) $charset_collate;";

            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($sql);

            if (!$wpdb->query($sql)) {
                var_dump('Impossible de créer la table.');
                var_dump($sql);
                die();
            }else{
                update_option(WEBCO_PREFIX.'version', WEBCO_VERSION);
            }
        }


        /**
         * Désinstallation du plugin
         */
        public function uninstall()
        {
            global $wpdb;
            $sql = "DELETE FROM " . tableNameTimeline . ";";

            if (!$wpdb->query($sql)) {
                var_dump($sql);
                die();
            } else {

            }
        }

        /**
         * Get a page url
         * @param  string $page the page
         * @return array
         */
        public static function get_page_url($page = 'setup', $param = array())
        {
            $args = array('page' => $page);

            $url = add_query_arg(array_merge($args, $param), admin_url('admin.php'));

            return $url;
        }

        /**
         * Création des menus
         */
        public function create_menu_page()
        {

            add_menu_page(
                'Webcollectivités', // titre de la page
                'Solution Webco', // nom dans le menu
                'administrator', //role necessaire pour accès
                'webco', //slug de la page
                array($this, 'display_admin'), //fonction de peuplement
                'dashicons-admin-generic', //icon
                90 //position
            );
        }

        /**
         * Initialisation du plugin
         */
        public static function init()
        {
//            self::load_admin_ressources();

            $modules = self::check_db_modules(true);

            if(count($modules) > 0){
                self::load_modules($modules);
            }/*else{
                if(isset($_GET['page']) && $_GET['page'] == 'webco') {
                    self::setup();
                }
            }*/

        }

        public function display_admin(){

            self::load_admin_ressources();

            global $wpdb;

            $tabParametresWebco = array();

            $modules = self::check_db_modules(true);

            if(count($modules) > 0){
                $activeModule = '';
                if (isset($_GET['showModule'])) {
                    $activeModule = $_GET['showModule'];
                }
                echo self::render('admin-tabs', array('modules' => $modules, 'activeModule' => $activeModule));
                if (!isset($_GET['showModule'])) {
                    echo self::render('admin-view');
                } else {
                    if (is_dir(WEBCO_PATH . '/modules/' . $_GET['showModule'])) {
                        $_GET['showModule']::displayModule();
                    }else{

                        if(!empty($_POST) && isset($_POST['installModules'])) {

                            foreach ($_POST['modules'] as $module) {

                                $tabInfoModule = explode('|', $module);

                                $param = array('module_nom' => $tabInfoModule[1],
                                    'module_nom_dossier' => $tabInfoModule[0],
                                    'module_actif' => 1);

                                if ($wpdb->insert(WEBCO_TABLE, $param)) {

                                    if(is_plugin_active($tabInfoModule[0] . '/' . $tabInfoModule[0] . '.php')){
                                        deactivate_plugins($tabInfoModule[0] . '/' . $tabInfoModule[0] . '.php');
                                    }

                                    self::load_modules(array(array('module_nom_dossier' => $tabInfoModule[0])), true);
                                } else {
                                    die('Erreur dans l\'ajout du module ' . $tabInfoModule[1] . ' dans la base');
                                }

                            }
                        }


                        if(!empty($_POST) && isset($_POST['validOptionsWebco'])){

                            $optionsWebco = get_option(WEBCO_PREFIX.'options');
                            if($optionsWebco !== false){
                                $optionsWebco[$_POST['param']] = $_POST['value'];
                                update_option(WEBCO_PREFIX.'options', $optionsWebco);
                            }else{
                                update_option(WEBCO_PREFIX.'options', array($_POST['param'] => $optionsWebco[$_POST['value']]));
                            }

                            // Déclaration ou suppression des CRON
//                            if($_POST['param'] == 'communetCheckPrivacyPolicy'){
//                                if($_POST['value'] == 'true'){
//                                    if (!wp_next_scheduled('actionCronPrivacyPolicy')) {
//                                        wp_schedule_event(time(), 'daily', 'actionCronPrivacyPolicy');
//                                    }
//                                }else{
//                                    wp_clear_scheduled_hook('actionCronPrivacyPolicy');
//                                }
//                            }
//
//                            if($_POST['param'] == 'communetCheckLegals'){
//                                if($_POST['value'] == 'true'){
//                                    if (!wp_next_scheduled('actionCronLegals')) {
//                                        wp_schedule_event(time(), 'daily', 'actionCronLegals');
//                                    }
//                                }else{
//                                    wp_clear_scheduled_hook('actionCronLegals');
//                                }
//                            }
//
//                            if($_POST['param'] == 'communetCheckAccessibility'){
//                                if($_POST['value'] == 'true'){
//                                    if (!wp_next_scheduled('actionCronAccessibility')) {
//                                        wp_schedule_event(time(), 'daily', 'actionCronAccessibility');
//                                    }
//                                }else{
//                                    wp_clear_scheduled_hook('actionCronAccessibility');
//                                }
//                            }
                        }


                        if($_GET['showModule'] == 'webco'){
                            $moduleToInstall = array();
                            $moduleFolder =  self::scan_dossier();
                            $moduleDb = self::check_db_modules();

                            foreach($moduleFolder as $moduleSlug => $moduleName){
                                $moduleNotInstalled = true;
                                foreach($moduleDb as $module){
                                    if(in_array($moduleSlug, $module)){
                                        $moduleNotInstalled = false;
                                    }
                                }
                                if($moduleNotInstalled){
                                    $moduleToInstall[$moduleSlug] = $moduleName;
                                }
                            }
                            $tabParametresWebco['moduleToInstall'] = $moduleToInstall;

                            $optionsWebco = get_option(WEBCO_PREFIX.'options');
                            $tabParametresWebco[WEBCO_PREFIX.'options'] = $optionsWebco;

                        }

                        echo self::render('admin-'.$_GET['showModule'], $tabParametresWebco);
                    }
                }
                echo self::render('admin-footer');
            }else{
                self::setup();
            }
        }

        /**
         * Chargement des CSS & JS pour le plugin
         */
        public static function load_admin_ressources()
        {

            // Bootstrap
            wp_register_style(WEBCO_PREFIX.'bootstrap.css', WEBCO_URL . 'includes/libs/bootstrap/css/bootstrap.min.css', array(), WEBCO_VERSION);
            wp_enqueue_style(WEBCO_PREFIX.'bootstrap.css');
            wp_register_script(WEBCO_PREFIX.'bootstrap.js', WEBCO_URL . 'includes/libs/bootstrap/js/bootstrap.min.js', array(), WEBCO_VERSION, true);
            wp_enqueue_script(WEBCO_PREFIX.'bootstrap.js');


            // CSS & JS custom
            wp_register_style(WEBCO_PREFIX.'style.css', WEBCO_URL . 'assets/css/solutionWebco.css', array(), WEBCO_VERSION);
            wp_enqueue_style(WEBCO_PREFIX.'style.css');
            wp_register_script(WEBCO_PREFIX.'js.js', WEBCO_URL . 'assets/js/solutionWebco.js', array(), WEBCO_VERSION, true);
            wp_enqueue_script(WEBCO_PREFIX.'js.js');
        }

        public static function check_db_modules($active = false)
        {
            global $wpdb;

            $query = "SELECT * FROM " . WEBCO_TABLE;

            if($active){
                $query .= " WHERE module_actif = 1";
            }

            $query .= ' ORDER BY module_nom';

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

            return $results;

        }

        /**
         * @param $view
         * @param array $args
         * @return string
         */
        public function render($view, $args = array())
        {
            foreach($args as $k => $v){
                $$k = $v;
            }

            $file = WEBCO_PATH . 'includes/views/'. $view . '.php';

            ob_start();

            include( $file );

            $content = ob_get_clean();

            return $content;
        }


        public static function scan_dossier()
        {
            $listeDossierModules = scandir(WEBCO_PATH.'modules/');

            $listeModule = array();

            foreach($listeDossierModules as $dossierModule){

                if(is_dir(WEBCO_PATH.'modules/'.$dossierModule) && $dossierModule != '.' && $dossierModule != '..') {
                    if((file_exists(WEBCO_PATH . 'modules/' . $dossierModule . '/' . $dossierModule . '.php'))) {
                        $content = file_get_contents(WEBCO_PATH . 'modules/' . $dossierModule . '/' . $dossierModule . '.php');
                        if (!empty($content)) {
                            $pos = strpos($content, self::needleName);
                            if ($pos != false) {
                                $content = substr($content, $pos + strlen(self::needleName));
                                $pos2 = strpos($content, PHP_EOL);
                                if ($pos2 != false) {
                                    $pluginName = substr($content, 0, $pos2);
                                    $listeModule[$dossierModule] = $pluginName;
                                }
                            }
                        }
                    }
                }
            }
            return $listeModule;
        }


        /**
         * Remove directory recursively
         * @param $dir Directory to remove
         */
        protected static function rrmdir($dir) {
            if (is_dir($dir)) {
                $objects = scandir($dir);
                foreach ($objects as $object) {
                    if ($object != "." && $object != "..") {
                        if (is_dir($dir."/".$object))
                            self::rrmdir($dir."/".$object);
                        else
                            unlink($dir."/".$object);
                    }
                }
                rmdir($dir);
            }
        }


        public function setup(){

            global $wpdb;

            if(isset($_GET['setup']) && !empty($_GET['setup'])){
                if($_GET['setup'] == 'launch'){

                    $listeModules = self::scan_dossier();

                    if(empty($_POST)) {
                        echo self::render('setup-launch', array('listeModules' => $listeModules));
                    }elseif(!empty($_POST) && isset($_POST['validModules'])){

                        foreach($_POST['modules'] as $nomDossierModule){
                            if(array_key_exists($nomDossierModule, $listeModules)){

                                $param = array('module_nom' => $listeModules[$nomDossierModule],
                                    'module_nom_dossier' => $nomDossierModule,
                                    'module_actif' => 1);

                                if($wpdb->insert(WEBCO_TABLE, $param)){
                                    //self::load_modules(array($nomDossierModule), true);

                                    if(is_plugin_active($nomDossierModule . '/' . $nomDossierModule . '.php')){
                                        deactivate_plugins($nomDossierModule . '/' . $nomDossierModule . '.php');
                                    }

                                    self::load_modules(array(array('module_nom_dossier' => $nomDossierModule)), true);
                                }else{
                                    die('Erreur dans l\'ajout du module '.$nomDossierModule.' dans la base');
                                }
                            }else{
                                self::rrmdir(WEBCO_PATH.'modules/'.$nomDossierModule);
                            }
                        }

                        self::display_admin();

                    }
                }
            }else {
                // Redirection vers le Setup
                echo self::render('pre-setup');
            }
        }

        public static function load_modules($modules, $install = false){

            foreach($modules as $module){
                if(file_exists(WEBCO_PATH. 'modules/'. $module['module_nom_dossier'] . '/' . $module['module_nom_dossier'] . '.php')){
                    require_once (WEBCO_PATH. 'modules/'. $module['module_nom_dossier'] . '/' . $module['module_nom_dossier'] . '.php');
                    // $pluginName = ucfirst($module);

                    if($install){
                        $module['module_nom_dossier']::install();
                    }else{
                        new $module['module_nom_dossier'];
                    }
                }else{
                    die("Impossible de charger le module: ".$module['module_nom_dossier']);
                }
            }
        }

        /**
         * Met à jour une option de webcollectivité stocké dans webco_support
         * @param POST array:   action -> le nom de la fonction à declencher
         *                      param -> le nom de l'option à mettre à jour
         *                      value -> la nouvelle valeur
         */
        public function majOptionWebcoAjax() {

            header('Content-type: application/json');

            $return = false;
            if(isset($_POST)){
                if(isset($_POST['action'])){

                    $optionsWebco = get_option(WEBCO_PREFIX.'options');
                    if($optionsWebco !== false){
                        $optionsWebco[$_POST['param']] = $_POST['value'];
                        $return = update_option(WEBCO_PREFIX.'options', $optionsWebco);
                    }else{
                        $return = update_option(WEBCO_PREFIX.'options', array($_POST['param'] => $optionsWebco[$_POST['value']]));
                    }

                    // Déclaration ou suppression des CRON
                    if($_POST['param'] == 'communetCheckPrivacyPolicy'){
                        if($_POST['value'] == 'true'){
                            if (!wp_next_scheduled('actionCronPrivacyPolicy')) {
                                wp_schedule_event(time(), 'daily', 'actionCronPrivacyPolicy');
                            }
                        }else{
                            wp_clear_scheduled_hook('actionCronPrivacyPolicy');
                        }
                    }

                    if($_POST['param'] == 'communetCheckLegals'){
                        if($_POST['value'] == 'true'){
                            if (!wp_next_scheduled('actionCronLegals')) {
                                wp_schedule_event(time(), 'daily', 'actionCronLegals');
                            }
                        }else{
                            wp_clear_scheduled_hook('actionCronLegals');
                        }
                    }

                    if($_POST['param'] == 'communetCheckAccessibility'){
                        if($_POST['value'] == 'true'){
                            if (!wp_next_scheduled('actionCronAccessibility')) {
                                wp_schedule_event(time(), 'daily', 'actionCronAccessibility');
                            }
                        }else{
                            wp_clear_scheduled_hook('actionCronAccessibility');
                        }
                    }

                }
            }

            echo json_encode($return);

            exit();
        }

        /**
         * Execute les options cochées dans l'administration du module
         */
        public function execOptions() {
            $webcoOption = get_option(WEBCO_PREFIX.'options');

            if($webcoOption != false){

                // Activation du support Webcollectivités
                if(isset($webcoOption['webcoSupport']) && $webcoOption['webcoSupport'] == 'true'){
                    add_action('admin_menu', array($this, 'webco_menu_page'));
                }

                // Activation du point de sortie de l'API en fonction de l'option activée
                if((isset($webcoOption['communetLegals']) && $webcoOption['communetLegals'] == 'true') ||
                    (isset($webcoOption['communetPrivacyPolicy']) && $webcoOption['communetPrivacyPolicy'] == 'true') ||
                    (isset($webcoOption['communetAccessibility']) && $webcoOption['communetAccessibility'] == 'true') ||
                    (isset($webcoOption['communetSendNotifications']) && $webcoOption['communetSendNotifications'] == 'true') ||
                    (isset($webcoOption['webcoSendNotifications']) && $webcoOption['webcoSendNotifications'] == 'true')){
                    add_action('rest_api_init', array($this, 'setRestRoute'));
                }

                if(isset($webcoOption['communetCheckPrivacyPolicy']) && $webcoOption['communetCheckPrivacyPolicy'] == 'true'){

                }

            }
        }

        /**
         * Ajout de l'entrée de menu pour le support
         */
        public function webco_menu_page()
        {
            add_menu_page('Support', 'Support', 'publish_pages', 'webco_support', array($this, 'webco_iframe_support'), 'dashicons-sos', 99);

        }

        /**
         * Intégration de l'iframe
         */
        public function webco_iframe_support(){

            add_action('admin_footer', array($this, 'webco_iframe_js'));

            echo '<div class="wrapper">
            <h1>Support Webcollectivités</h1>
                <iframe id="webcoSupport" src="https://maintenance.webcollectivites.fr/support/"></iframe>
            </div>';
        }

        /**
         * Javascript pour adapter la taille de l'iframe
         */
        public function webco_iframe_js(){
            echo '<script type="text/javascript">
                    window.onload = loadWebcoIframe;
                    
                    function loadWebcoIframe(){                        
                        var width = window.innerWidth - 200;
                        var height = window.innerHeight - 200;
                        var webcoIframe = document.getElementById(\'webcoSupport\');
                        webcoIframe.setAttribute(\'width\', width);
                        webcoIframe.setAttribute(\'height\', height);
                    }
                    </script>';
        }

        /**
         * Préparation du point de sortie de l'API
         */
        public function setRestRoute(){
            $webcoOption = get_option(WEBCO_PREFIX.'options');
            if($webcoOption != false) {
                if (isset($webcoOption['communetLegals']) && $webcoOption['communetLegals'] == 'true'){
                    $this->registerRestRoute('communetLegals');
                }
                if (isset($webcoOption['communetPrivacyPolicy']) && $webcoOption['communetPrivacyPolicy'] == 'true'){
                    $this->registerRestRoute('communetPrivacyPolicy');
                }
                if (isset($webcoOption['communetAccessibility']) && $webcoOption['communetAccessibility'] == 'true'){
                    $this->registerRestRoute('communetAccessibility');
                }
                if(isset($webcoOption['communetSendNotifications']) && $webcoOption['communetSendNotifications'] == 'true'){
                    $this->registerRestRoute('communetNotifications');
                }
                if(isset($webcoOption['webcoSendNotifications']) && $webcoOption['webcoSendNotifications'] == 'true'){
                    $this->registerRestRoute('webcoNotifications');
                }
            }
        }

        /**
         * Enregistrement du point de sortie pour l'API
         */
        public function registerRestRoute($endPoint = ''){
            register_rest_route( 'wp/v2', '/'.$endPoint, array(
                'methods' => 'GET',
                'callback' => array($this, $endPoint),
            ) );
        }

        /**
         * Affiche les notifications communet
         */
        public function communetNotifications(){
            header('content-type: application/json; charset=utf-8');
            $activeNotifications = notifications::getNotificationBy(array('date_debut' => array('compare' => '<=',
                'value' => date('Ymd')),
                'date_fin' => array('compare' => '>=',
                    'value' => date('Ymd')),
                'destinataire' => array('compare' => '=',
                    'value' => 'communet')
            ));
            echo json_encode($activeNotifications);
            exit;
        }

        /**
         * Affiche les notifications webcollectivités
         */
        public function webcoNotifications(){
            header('content-type: application/json; charset=utf-8');
            $activeNotifications = notifications::getNotificationBy(array('date_debut' => array('compare' => '<=',
                'value' => date('Ymd')),
                'date_fin' => array('compare' => '>=',
                    'value' => date('Ymd')),
                'destinataire' => array('compare' => '=',
                    'value' => 'webcollectivites')
            ));
            echo json_encode($activeNotifications);
            exit;
        }

        /**
         * Affiche les mentions légales de communet
         */
        public function communetLegals(){

            global $post;
            $array = [];
            $webcoOption = get_option(WEBCO_PREFIX.'options');

            if(is_int(intval($webcoOption['communetPrivacyPolicyAdminId']))) {

                $post = get_post($webcoOption['communetLegalsAdminId']);

                $array['content'] = $post->post_content;
                $array['date_update'] = $post->post_modified;
            }else{
                $array['error'] = 'L\'ID de le page mentions légales est mal renseigné';
            }


            header('content-type: application/json; charset=utf-8');
            echo json_encode($array)."\n";
            exit;
        }

        /**
         * Met à jour la page de politique de confidentialité
         */
        public static function cronLegals() {

            $webcoOption = get_option(WEBCO_PREFIX.'options');

            if(isset($webcoOption['communetLegalsId']) && $webcoOption['communetLegalsId'] > 0){
                $postPrivacy = get_post($webcoOption['communetLegalsId']);

                $postTime = strtotime($postPrivacy->post_modified);

                $reponse = wp_remote_get(WEBCO_API_URL.'communetLegals');
                $json = json_decode($reponse['body']);
                if(isset($json->content)) {
                    $apiPageTime = strtotime($json->date_update);

                    // La date de modification de la page de politique de confidentialité est inférieur ce qui signifie que la page de référence a été mise à jour
                    if ($postTime < $apiPageTime) {
                        $postPrivacy->post_modified = $json->date_update;
                        $postPrivacy->post_content = $json->content;
                        wp_update_post($postPrivacy);
                    }
                }

            }

        }

        /**
         * Affiche la politique de confidentialité de communet
         */
        public function communetPrivacyPolicy(){

            global $post;
            $array = [];
            $webcoOption = get_option(WEBCO_PREFIX.'options');

            if(is_int(intval($webcoOption['communetPrivacyPolicyAdminId']))) {
                $post = get_post($webcoOption['communetPrivacyPolicyAdminId']);

                $array['content'] = $post->post_content;
                $array['date_update'] = $post->post_modified;
            }else{
                $array['error'] = 'L\'ID de le page politique de confidentialité est mal renseigné';
            }
            header('content-type: application/json; charset=utf-8');
            echo json_encode($array)."\n";
            exit;
        }

        /**
         * Met à jour la page de politique de confidentialité
         */
        public static function cronPrivacyPolicy() {

            $webcoOption = get_option(WEBCO_PREFIX.'options');

            if(isset($webcoOption['communetPrivacyPolicyId']) && $webcoOption['communetPrivacyPolicyId'] > 0){
                $postPrivacy = get_post($webcoOption['communetPrivacyPolicyId']);

                $postTime = strtotime($postPrivacy->post_modified);

                $reponse = wp_remote_get(WEBCO_API_URL.'communetPrivacyPolicy');
                $json = json_decode($reponse['body']);
                if(isset($json->content)) {
                    $apiPageTime = strtotime($json->date_update);

                    // La date de modification de la page de politique de confidentialité est inférieur ce qui signifie que la page de référence a été mise à jour
                    if ($postTime < $apiPageTime) {
                        $postPrivacy->post_modified = $json->date_update;
                        $postPrivacy->post_content = $json->content;
                        wp_update_post($postPrivacy);
                    }
                }

            }

        }

        /**
         * Affiche l'accessibilité de communet
         */
        public function communetAccessibility() {
            global $post;
            $array = [];
            $webcoOption = get_option(WEBCO_PREFIX.'options');

            if(is_int(intval($webcoOption['communetAccessibilityAdminId']))) {
                $post = get_post($webcoOption['communetAccessibilityAdminId']);

                $array['content'] = $post->post_content;
                $array['date_update'] = $post->post_modified;

            }else{
                $array['error'] = 'L\'ID de le page accèssibilité est mal renseigné';
            }

            header('content-type: application/json; charset=utf-8');
            echo json_encode($array) . "\n";
            exit;

        }

        /**
         * Met à jour la page d'accèssibilité
         */
        public static function cronAccessibility() {

            $webcoOption = get_option(WEBCO_PREFIX.'options');

            if(isset($webcoOption['communetAccessibilityPageId']) && $webcoOption['communetAccessibilityPageId'] > 0){
                $postAccessibility = get_post($webcoOption['communetAccessibilityPageId']);

                $postTime = strtotime($postAccessibility->post_modified);

                $reponse = wp_remote_get(WEBCO_API_URL.'communetAccessibility');
                $json = json_decode($reponse['body']);
                if(isset($json->content)){
                    $apiPageTime = strtotime($json->date_update);

                    // La date de modification de la page de politique de confidentialité est inférieur ce qui signifie que la page de référence a été mise à jour
                    if($postTime < $apiPageTime){
                        $postAccessibility->post_modified = $json->date_update;
                        $postAccessibility->post_content = $json->content;
                        wp_update_post($postAccessibility);
                    }
                }

            }

        }

        /**
         * @param $user_login string: le login renseigné par l'utilisateur
         * @param $user obj: les données de l'utilisateur loggé
         */
        public static function notifyAdminLogin($user_login, $user){

            $userLoginTest = parametres::getParametreDouble('ADMIN', 'CONNEXIONTEST');

            if($userLoginTest != false && $userLoginTest == $user_login ){

                $to = explode(";", get_option('respo_resa'));
                $subject = '['.get_bloginfo('blogname').'] Connexion de l\'utilisateur: '.$user_login;
                $body = 'L\'utilisateur s\'est connecté le: '.date('d-m-Y à H:i:s').'<br />';
                $headers = array(
                    'Content-Type: text/html; charset=UTF-8',
                    'From: ' . get_bloginfo() . ' <' . get_bloginfo('admin_email') . '>'
                );

                if(function_exists('content_mail')) {
                    $body = content_mail($body);
                }

                wp_mail($to, $subject, $body, $headers);

            }

        }

        /**
         * @param $wp_adminbar Objet barre admin menu
         */
        public static function webcoMajAdminMenu($wp_adminbar){
            // add SitePoint menu item
            $wp_adminbar->add_node([
                'id' => 'aideWebco',
                'title' => 'Besoin d\'aide?',
                'meta' => [
                    'class' => 'nodeWebcoAide'
                ]
            ]);

            // add Forum sub-menu item
            $wp_adminbar->add_node([
                'id' => 'spforum',
//                'title' => 'Besoin d\'aide?',
                'parent' => 'aideWebco',
//                'href' => 'https://www.sitepoint.com/community/',
                'meta' => [
                    'target' => 'aideWebco',
                    'html' => '<div style="width: 250px;padding: 0px 10px"><p class="text-light pl-2"><a class="text-white" target="_blank" href="https://maintenance.webcollectivites.fr/aide-en-ligne/"><u>Consultez l\'aide en ligne</u></a></p style="line-height:26px;">Contacter le support:<br /> <a class="text-white pl-2" target="_blank" href="mailto:support@atelier-111.fr"><u>support@atelier-111.fr</u></a><br />Pour vos signalements, merci de fournir les détails du problème rencontré + les URLs des pages, et si possible des copies d\'écran</p></div><style type="text/css">#wp-admin-bar-aideWebco-default .ab-item.ab-empty-item{height: 0px !important}</style>'
                ]
            ]);

//            // add Forum sub-menu item
//            $wp_adminbar->add_node([
//                'id' => 'sptforum',
//                'title' => 'Contacter le support',
//                'parent' => 'aideWebco',
////                'href' => 'https://www.sitepoint.com/community/',
//                'meta' => [
//                    'target' => 'aideWebco',
//                    'html' => '<p class="text-light pl-3">Vous n\'avez pas  pas trouvé de réponse à votre question ? Contactez-nous à <a class="text-white" target="_blank" href="mailto:support@atelier-111.fr"><u>support@atelier-111.fr</u></a> en donnant tous les détails du problème rencontré, les URLs des pages, et dans la mesure du possible des copies d\'écran. Merci.</p>'
//                ]
//            ]);
        }

        /**
         * @param données à mettre dans le log
         */
        public static function webcoWriteLog($log){
            if (true === WP_DEBUG && true === WP_DEBUG_LOG) {
                if (is_array($log) || is_object($log)) {
                    error_log(print_r($log, true));
                } else {
                    error_log($log);
                }
            }
        }

        public static function solutionWebcoCssBo() {
            wp_register_style(WEBCO_PREFIX.'solutionWebcoCssBo.css', WEBCO_URL . 'assets/css/solutionWebcoCssBo.css', array(), WEBCO_VERSION);
            wp_enqueue_style(WEBCO_PREFIX.'solutionWebcoCssBo.css');
        }

    }
}

new Webcollectivites(__FILE__, 'DevAtelier-111', 'solutionAtelier111', GITHUB_TOKEN);


add_filter( 'cron_schedules', 'a111_cron_add_every_week' );

/**
 * Register new CRON schedule
 */
if(!function_exists('a111_cron_add_every_week')) {
    function a111_cron_add_every_week($schedules)
    {
        $schedules['every_week'] = array(
            'interval' => 3600 * 24 * 7,
            'display' => __('Weekly', 'textdomain')
        );
        return $schedules;
    }
}


//add_action('wp_login', array('Webcollectivites', 'notifyAdminLogin'), 10, 2);
