<?php

namespace Macymed\MacymedLinkTracker\Admin;

use Macymed\MacymedLinkTracker\Admin\Pages\Dashboard;
use Macymed\MacymedLinkTracker\Admin\Pages\Evolution;

use Macymed\MacymedLinkTracker\Admin\Pages\ListClicks;
use Macymed\MacymedLinkTracker\Admin\Pages\Settings;
use Macymed\MacymedLinkTracker\Admin\Pages\Statistiques;
use Macymed\MacymedLinkTracker\Admin\Pages\Stats;
use Macymed\MacymedLinkTracker\Admin\Pages\Tools;
use Macymed\MacymedLinkTracker\Utils\Statistics;
use Macymed\MacymedLinkTracker\Utils\Utils;

if (! defined('ABSPATH')) {
    exit; // Sécurité
}

// use DLXPlugins\PowerBlocks\Functions as Functions;

/**
 * Create the admin menu.
 */
class RegisterAdmin
{
    /**
     * Main class runner.
     */
    public static function run()
    {
        // add_action( 'admin_menu', array( static::class, 'init_menu' ) );
        self::register_assets();
        self::init_menu();
        self::register_pages();
    }

    public static function register_pages()
    {
        Statistics::init();
        Hooks::init();
        Settings::init();

        Dashboard::init();

        ListClicks::init();

        Stats::init();

        Tools::init();

        Statistiques::init();

        Evolution::init();
        // Help::init();


        add_action('admin_head', [self::class, 'macymed_add_custom_sidebar']);
        add_filter('admin_body_class', [self::class, 'macymed_add_body_class']);
        add_action('macymed_link_tracker_sidebar_before', [self::class, 'renderProButton']);
    }
    public static function renderProButton()
    {
?>
        <a href="https://extensions.macymed.fr/prix/" target="_blank" class="macymed-upgrade-btn">Passer à la version Pro</a>

    <?php
    }
    public static function get_list_admin_pages()
    {
        return [
            'macymed-link-tracker-dashboard',
            'macymed-link-tracker-settings',
            'macymed-link-tracker-clicks',
            'macymed-link-tracker-stats',
            'macymed-link-tracker-custom-report',
            'macymed-link-tracker-tools',
            'macymed-link-tracker-statistics',
            'macymed-link-tracker-evolution',
            'macymed-link-tracker-pro-ai',
            'macymed_link_tracker-license',


            // 'macymed-link-tracker-help',
        ];
    }
    /**
     * Fonction statique pour générer le tableau des menus
     */
    public static function get_menu_structure()
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing
        $current_page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';


        $menus = [];
        switch ($current_page) {

            case 'macymed-link-tracker-settings':
                $menus = Settings::get_menu_structure();
                break;
            case 'macymed-link-tracker-statistics':
                $menus = Statistiques::get_menu_structure();
                break;
            case 'macymed-link-tracker-evolution':
                $menus = Evolution::get_menu_structure();
                break;
                break;
            case 'macymed-link-tracker-tools':
                $menus = Tools::get_menu_structure();
                break;
            case 'macymed-link-tracker-dashboard':
                $menus = Dashboard::get_menu_structure();
                break;
        }
        return $menus;
    }


    public static function macymed_add_body_class($classes)
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing
        $current_page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
        $plugin_pages = self::get_list_admin_pages();

        if (in_array($current_page, $plugin_pages)) {
            $classes .= ' admin-page-macymed-link-tracker';
        }

        return $classes;
    }
    public static function macymed_add_custom_sidebar()
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing
        $current_page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
        $current_tab = isset($_GET['tab']) ? sanitize_text_field(wp_unslash($_GET['tab'])) : '';

        $plugin_pages = self::get_list_admin_pages();

        if (!in_array($current_page, $plugin_pages)) {
            return; // Ne rien afficher si ce n'est pas une page de votre plugin
        }

        // Récupérer le menu via la fonction statique
        $sidebar_menu = self::get_menu_structure();
        if (count($sidebar_menu) == 0) {
            return;
        }

    ?>
        <div class="macymed-hamburger">☰</div>

        <!-- 📌 Sidebar -->
        <div class="macymed-custom-sidebar">
            <!-- 📌 Logo en haut -->
            <div class="sidebar-logo">
                <a href="https://extensions.macymed.fr" target="_blank">
                    <div class="link-tracker-image"></div>
                </a>
            </div>
            <?php
            do_action('macymed_link_tracker_sidebar_before');
            ?>


            <?php $sidebar_menu = self::get_menu_structure(); ?>
            <?php
            $cpt = 0;
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing
            $current_page = isset($_GET['page']) ? sanitize_text_field( wp_unslash( $_GET['page'])) : '';

            ?>
            <?php foreach ($sidebar_menu as $section => $links):
            ?>
                <h4><?php echo esc_html($section); ?></h4>
                <ul>
                    <?php foreach ($links as $index => $urlItem):
                       
                        $active_class = $urlItem['tab'] === $current_tab ? 'active' : '';
                        $default = isset($urlItem['default']) ? $urlItem['default'] !== 'none' : true;
                        if (($cpt == 0) && !trim($current_tab) && ($default)) {
                            $active_class = 'active';
                        }

                        $target = isset($urlItem['target']) ? ' target="' . sanitize_text_field($urlItem['target']) . '" ' : '';
                    ?>
                        <li>
                            <a <?php echo esc_attr($target); ?> href="<?php echo esc_url($urlItem['url']); ?>" class="<?php echo esc_attr($active_class); ?>"><?php echo esc_html($urlItem['label']); ?></a>
                            <?php
                            $cpt = 1;
                            ?>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endforeach; ?>
        </div>

<?php
    }

    public static function register_assets()
    {
        add_action(
            'admin_enqueue_scripts',
            function () {
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing
                $current_page = isset($_GET['page']) ? sanitize_text_field( wp_unslash( $_GET['page'])) : '';

                $plugin_pages = self::get_list_admin_pages();

                if (!in_array($current_page, $plugin_pages)) {
                    return; // Ne rien afficher si ce n'est pas une page de votre plugin
                }
                // Charger les styles et scripts des postboxes
                wp_enqueue_script('postbox');
                wp_enqueue_script('dashboard');
                wp_enqueue_style('dashboard');

                wp_enqueue_script(
                    'chartjs', // Handle du script
                    Utils::get_plugin_url() . 'dist/js/vendor/chart.min.js',
                    [], // Pas de dépendances
                    '4.4.7',
                    false
                );
                wp_enqueue_script(
                    'vis-js',
                    Utils::get_plugin_url() . 'dist/js/vendor/vis-network.min.js',
                    [], // Pas de dépendances
                    '9.1.9',
                    false
                );


                wp_register_script(
                    'macymed-link-traker-visualizer', // Handle du script
                    Utils::get_plugin_url() . 'dist/js/macymed-link-traker-visualizer.js' . '?t=' . time(),
                    [], // Pas de dépendances
                    '1.0.0.1',
                    ['in_footer' => true]
                );

                wp_enqueue_script('macymed-link-traker-visualizer');

                add_filter("script_loader_tag", [self::class, "add_module_to_my_script"], 10, 3);


                wp_enqueue_script('macymed-admin-script', Utils::get_plugin_url() . 'dist/js/admin-script.js' . '?t=' . time(), ['chartjs', 'jquery'], '1.0', true);
                wp_localize_script('macymed-admin-script', 'macymedAdminScriptAjax', [
                    'ajax_url' => admin_url('admin-ajax.php'),
                    'nonce'  => wp_create_nonce('macymed-admin-script-ajax-nonce'),
                ]);
                wp_enqueue_style('macymed-admin-style', Utils::get_plugin_url() . 'dist/css/admin-style.css' . '?t=' . time(), [], '1.0.0');
                wp_enqueue_style('macymed-link-traker-visualizer-style', Utils::get_plugin_url() . 'dist/css/macymed-link-traker-visualizer.css' . '?t=' . time(), [], '1.0.0');
            }
        );
    }
    public static function add_module_to_my_script($tag, $handle, $src)
    {
        if ("macymed-link-traker-visualizer" === $handle) {
            // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript
            $tag = '<script type="module" src="' . esc_url($src) . '"></script>';
        }

        return $tag;
    }
    /**
     * Register the plugin menu.
     */
    public static function init_menu()
    {

        add_action(
            'admin_menu',
            function () {
                add_menu_page(
                    'Link Tracker',                  // Titre de la page
                    'Link Tracker',                  // Titre du menu
                    'manage_options',                   // Capacité requise
                    'macymed-link-tracker-dashboard',        // Slug de la page
                    function () {
                        Dashboard::render();
                    },
                    '',
                    2                                   // Position
                );
                add_submenu_page(
                    'macymed-link-tracker-dashboard',
                    'Statistiques',
                    'Statistiques',
                    'manage_options',
                    'macymed-link-tracker-statistics',
                    function () {
                        Statistiques::render();
                    },
                );
                add_submenu_page(
                    'macymed-link-tracker-dashboard',
                    'Options',
                    'Options',
                    'manage_options',
                    'macymed-link-tracker-settings',
                    // 'macymed_tracker_settings_page'
                    function () {
                        Settings::render();
                    },
                );



                add_submenu_page(
                    'macymed-link-tracker-dashboard',
                    'Outils',
                    'Outils',
                    'manage_options',
                    'macymed-link-tracker-tools',
                    // 'macymed_tracker_clicks_page'
                    function () {
                        Tools::render();
                    },
                );

               

                add_submenu_page(
                    'macymed-link-tracker-dashboard',
                    'Support',
                    'Support',
                    'manage_options',
                    'macymed-link-tracker-evolution',
                    // 'macymed_tracker_clicks_page'
                    function () {
                        Evolution::render();
                    },
                );
                


                do_action('macymed_link_tracker_admin_menu_init');
                global $menu;

                foreach ($menu as &$item) {
                    if ($item[2] === 'macymed-link-tracker-dashboard') {
                        $item[4] .= ' macymed-link-tracker-logo-menu';
                        break;
                    }
                }
               
            }
        );
    }
    public static function render_statistics_page() {}
}
