<?php

class LinksgardenConfig {

    public static function init(){
        if (is_admin()) {
            add_action('admin_menu', array(__CLASS__, 'admin_menu'));                                           // Encart dans le menu WordPress
            add_filter("plugin_action_links_".LG_PLUGIN_NAME, array(__CLASS__, 'my_plugin_settings_link' ));    // Boutton Réglages dans le menu des plugins
        }

        /*
        * MàJ automatique, check toutes les 12h si une maj à été faite.
        */
        require LG_PLUGIN_DIR . 'includes/plugin-update-checker-4.10/plugin-update-checker.php';
        $myUpdateChecker = Puc_v4_Factory::buildUpdateChecker(
        	'http://api.linksgarden.com/plugin-wp/plugin.json',
        	LG_PLUGIN_FILE,
        	'unique-plugin-or-theme-slug'
        );
    }

    // Menu
    public static function admin_menu(){
        add_menu_page(
            'Linksgarden',
            'Linksgarden',
            'manage_options',
            'linksgarden-config',
            array(__CLASS__, 'config'),
            'data:image/svg+xml;base64,' . base64_encode(file_get_contents(LG_PLUGIN_DIR . '/includes/images/Icon_blanc.svg'))
        );
    }

    /*
    * Fonction pour set les api / api secret
    */
    public static function config() {
        $code_erreur = 0;
        if (isset($_POST['api_lg_public'])) {
            update_option('api_lg_public', sanitize_text_field($_POST['api_lg_public']));
        }
        if (isset($_POST['api_lg_secret'])) {
            update_option('api_lg_secret', sanitize_text_field($_POST['api_lg_secret']));
        }
        if (isset($_POST['submit'])) {
            if (!isset($_POST['lg_nonce']) || !wp_verify_nonce($_POST['lg_nonce'], 'lg_config_save')) {
                wp_die('Erreur de sécurité : token invalide');
            }
            if($code_erreur = self::checkOwnership()){
                self::delete_lg_options(false);
            }
        }
        require LG_PLUGIN_DIR . 'vue/config.php';
    }

    // URL Réglages dans le menu des plugins
    public static function my_plugin_settings_link($links) {
        $settings_link = '<a href="admin.php?page=linksgarden-config">'.__('Settings').'</a>';
        array_unshift($links, $settings_link);
        return $links;
    }

    // Vérifie la propriété d'un site
    private static function checkOwnership(){
        $response = self::lg_post(array(
            'check_ownership' => true
        ));
        if ($response['body'] == 'ok'){
            update_option('owner_confirmed', 1);
            return 0;
        } elseif ($response['body'] == 'bad public') {
            return 1;
        } elseif ($response['body'] == 'bad secret') {
            return 2;
        } elseif ($response['body'] == 'unknown site') {
            return 3;
        }
    }

    // Supprime les données
    public static function delete_lg_options($delete_options = true){
        if (get_option('owner_confirmed') == 1) {
            self::lg_post(array(
                'remove_ppty_lg' => true,
            ));
            if ($delete_options == true) {
                $options = array(
                    'owner_confirmed',
                    'api_lg_public',
                    'api_lg_secret'
                );
                foreach ($options as $key => $option) {
                    delete_option($option);
                }
            } else {
                update_option('owner_confirmed', 4);
            }
        }
    }

    // Post vers l'app LG
    private static function lg_post($body){
        $body = array_merge($body, array(
            'api_lg_public' => get_option('api_lg_public'),
            'api_lg_secret' => get_option('api_lg_secret'),
            'root_ndd' => self::trimToRoot(getenv('HTTP_HOST'))
        ));
        return wp_remote_post('https://app.linksgarden.com/gJLg4v5pRst28_AzX.php', array(
            'method'      => 'POST',
            'timeout'     => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking'    => true,
            'headers'     => array(),
            'body'        => $body,
            'cookies'     => array()
        ));
    }

    private static function trimToRoot($url){
            $root = trim($url);
            $root = parse_url($root, PHP_URL_HOST);
            $root = str_replace("www.", "", $root);
            //on vérifie si la formule parse url ne ressort pas un vide (donc mauvais format lorsqu'il n'y a pas), et s'il y a au moins un point car sinon c'est pas un ndd
            if($root == "" && strpos($url, ".") != 0){
                 $root = "http://".$url;
                 $root = parse_url($root, PHP_URL_HOST);
                 $root = str_replace("www.", "", $root);
            }
            return $root;
    }
}
