<?php

namespace WPUltimateSecurity\UltimateSecurity\Presentation\Admin;

use WPUltimateSecurity\UltimateSecurity\Support\Helpers\Utils;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\IpHelper;
use WP_Admin_Bar;
class AdminHooks
{
    public static function register()
    {
        add_filter('plugin_action_links_' . ULTIMATE_SECURITY_NAME, [self::class, 'ultimate_security_add_action_links']);

        add_action('admin_init', [self::class, 'ultimate_security_do_activation_redirect']);

        add_action('admin_bar_menu', [self::class, 'ultimate_security_admin_bar_menu'], 500);

        add_action('admin_init', [self::class, 'ultimate_security_page_data']);

        add_action('admin_init', [self::class, 'ultimate_security_product_category_data']);

        add_filter('cron_schedules', [self::class, 'ultimate_security_cron_schedules']);


        add_action( 'admin_notices', [self::class, 'ultimate_security_admin_notice_feedback'] );
        add_action( 'admin_footer', [self::class, 'ultimate_security_admin_footer_feedback'] );
    }

    public static function ultimate_security_add_action_links($links)
    {
        $settings_link = array(
            '<a href="' . admin_url('admin.php?page=ultimate-security') . '">' . esc_html__('Settings', 'ultimate-security') . '</a>',
        );
        return array_merge($settings_link, $links);
    }

    

    public static function ultimate_security_do_activation_redirect()
    {
        if (get_option('ultimate_security_do_activation_redirect')) {
            delete_option('ultimate_security_do_activation_redirect');

            if (!is_network_admin() && is_admin() && current_user_can('manage_options')) {

                // Check if setup is still 1 (not reset)
                wp_safe_redirect(admin_url('admin.php?page=ultimate-security'));
                // if ((int) get_option('ultimate_security_setup') === 1) {
                //     wp_safe_redirect(admin_url('admin.php?page=ultimate-security#/more/setup-wizard'));
                // } else {
                //     wp_safe_redirect(admin_url('admin.php?page=ultimate-security'));
                // }

                exit; // Don't forget this
            }
        }
    }


   

    /**
     * REMOVED: Debug IP switching admin bar menu
     * This feature depended on restrictions.settings.debug_log which has been removed
     * as part of the server-level features cleanup.
     */
    public static function ultimate_security_admin_bar_menu(WP_Admin_Bar $wp_admin_bar)
    {
        // Feature removed - restrictions config no longer exists
    }

    public static function ultimate_security_cron_schedules($schedules)
    {
        $schedules['weekly'] = array(
            'interval' => WEEK_IN_SECONDS, // 1 week in seconds
            'display' => esc_html__('Weekly', 'ultimate-security')
        );
        $schedules['monthly'] = array(
            'interval' => 30 * DAY_IN_SECONDS, // Approx. 1 month in seconds
            'display' => esc_html__('Monthly', 'ultimate-security')
        );
        $schedules['quarterly'] = array(
            'interval' => 91 * DAY_IN_SECONDS, // Approx. 3 months in seconds
            'display' => esc_html__('Every 3 Months', 'ultimate-security')
        );
        $schedules['biannually'] = array(
            'interval' => 182 * DAY_IN_SECONDS, // Approx. 6 months in seconds
            'display' => esc_html__('Every 6 Months', 'ultimate-security')
        );

        return $schedules;
    }

    public static function ultimate_security_page_data()
    {
        // Fetch the pages
        $pages = get_pages();

        // Store the data in a global or an option
        $page_data = array();
        $n = 0;
        foreach ($pages as $page) {
            // { value: 'Administrator', code: 'administrator' },
            $page_data[$n]['code'] = $page->ID;
            $page_data[$n]['value'] = $page->post_title;
            $n++;
        }

        // Make it available globally or store it in a transient/option
        global $ultimate_security_page_data;
        $ultimate_security_page_data = $page_data;
    }

    public static function ultimate_security_product_category_data()
    {

        // Get all product categories
        $product_categories = get_terms(array(
            'taxonomy' => 'product_cat',
            'hide_empty' => false, // Set to true if you only want categories with products
        ));

        // Initialize an empty array to store category IDs and titles
        $product_category_data = array();

        if (!is_wp_error($product_categories)) {
            $n = 0;
            foreach ($product_categories as $category) {
                $product_category_data[$n]['code'] = $category->term_id;
                $product_category_data[$n]['value'] = $category->name;
                $n++;
            }
        }
        // Make it available globally or store it in a transient/option
        global $ultimate_security_product_category_data;
        $ultimate_security_product_category_data = $product_category_data;
    }

    /**
     * Count the number of enabled security features
     *
     * @return int
     */
    private static function count_enabled_features()
    {
        $options = Utils::ultimate_security_get_option();
        $count = 0;

        // 2FA Features
        if (!empty($options['security']['2fa_authentication']['email_authentication']['2fa_email_verification_enable'])
            && $options['security']['2fa_authentication']['email_authentication']['2fa_email_verification_enable'] === '1') {
            $count++;
        }
        if (!empty($options['security']['2fa_authentication']['application_authentication']['2fa_application_authentication_enable'])
            && $options['security']['2fa_authentication']['application_authentication']['2fa_application_authentication_enable'] === '1') {
            $count++;
        }

        // Password Policy
        if (!empty($options['security']['password_policies']['activate_password_policies'])
            && $options['security']['password_policies']['activate_password_policies'] === '1') {
            $count++;
        }

        // Custom Login URL
        if (!empty($options['security']['login_security']['custom_login_url'])) {
            $count++;
        }

        // Salt Change Schedule
        if (!empty($options['security']['salt_change']['enable_schedules'])
            && $options['security']['salt_change']['enable_schedules'] === '1') {
            $count++;
        }

        // REMOVED: IP, Geo, Bot Restrictions - server-level features

        return $count;
    }

    /**
     * Get security statistics for milestone messages
     *
     * @return array
     */
    private static function get_security_stats()
    {
        global $wpdb;
        $stats = [
            'blocked_requests' => 0,
            'failed_logins' => 0,
        ];

        // Check if URL guard table exists and count blocked requests
        $table_name = $wpdb->prefix . 'ultimate_security_url_guard_requestslog';
        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name));
        if ($table_exists === $table_name) {
            $stats['blocked_requests'] = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$table_name} WHERE status = 'blocked'");
        }

        // Check auth_logs for failed logins (pro table)
        $auth_table = $wpdb->prefix . 'ultimate_security_auth_logs';
        $auth_table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $auth_table));
        if ($auth_table_exists === $auth_table) {
            $stats['failed_logins'] = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$auth_table} WHERE event_type LIKE '%failed%'");
        }

        return $stats;
    }

    public static function ultimate_security_admin_notice_feedback()
    {
        // Only show on Ultimate Security pages and WordPress dashboard
        $screen = get_current_screen();
        $allowed_screens = ['dashboard', 'toplevel_page_ultimate-security'];
        if (!$screen || (strpos($screen->id, 'ultimate-security') === false && !in_array($screen->id, $allowed_screens))) {
            return;
        }

        // Check if permanently dismissed
        if (get_option('ultimate_security_feedback_dismissed_permanently')) {
            return;
        }

        // Check if already reviewed
        if (get_option('ultimate_security_feedback_clicked')) {
            return;
        }

        // Check minimum usage time (7 days)
        $activated_at = get_option('ultimate_security_activated_at', 0);
        $min_days = 7;
        // $min_days = 0;
        if ($activated_at && (time() - $activated_at) < ($min_days * DAY_IN_SECONDS)) {
            return;
        }

        // Check snooze time
        $next_fire = get_option('ultimate_security_feedback_next_show', 0);
        if ($next_fire && time() < $next_fire) {
            return;
        }

        // Get feature count and security stats
        $feature_count = self::count_enabled_features();
        $stats = self::get_security_stats();
        $total_blocked = $stats['blocked_requests'] + $stats['failed_logins'];

        // Milestone message based on blocked threats
        $milestone_message = '';
        if ($total_blocked >= 100) {
            $milestone_message = sprintf(
                /* translators: %d is the number of blocked threats */
                esc_html__('Ultimate Security has blocked %d threats!', 'ultimate-security'),
                $total_blocked
            );
        } elseif ($total_blocked >= 10) {
            $milestone_message = sprintf(
                /* translators: %d is the number of blocked threats */
                esc_html__('Ultimate Security has blocked %d threats so far!', 'ultimate-security'),
                $total_blocked
            );
        }

        // Personalized message based on feature count
        if ($feature_count === 0) {
            $message = esc_html__("Set up your first security feature to protect your site! Once you're up and running, we'd love to hear your feedback.", 'ultimate-security');
        } elseif ($feature_count === 1) {
            $message = esc_html__("You've enabled your first security feature! If Ultimate Security has been helpful, please consider leaving a review.", 'ultimate-security');
        } else {
            $message = sprintf(
                /* translators: %d is the number of security features enabled */
                esc_html__("You've protected your site with %d security features! If Ultimate Security has helped keep your site safe, please consider leaving a review.", 'ultimate-security'),
                $feature_count
            );
        }

        // Render notice with standard WordPress styling
        ?>
        <div class="notice notice-info is-dismissible ultimate-security-review-notice">
            <p>
                <strong><?php esc_html_e('Enjoying Ultimate Security?', 'ultimate-security'); ?></strong>
                <?php if ($milestone_message) : ?>
                    — <?php echo esc_html($milestone_message); ?>
                <?php endif; ?>
            </p>
            <p><?php echo esc_html($message); ?></p>
            <p>
                <a href="https://wordpress.org/support/plugin/ultimate-security/reviews/?filter=5#new-post"
                   class="button button-primary"
                   target="_blank"
                   rel="noopener noreferrer">
                    <?php esc_html_e('Leave a Review', 'ultimate-security'); ?>
                </a>
                <button type="button" class="button us-review-btn" data-action="remind-later">
                    <?php esc_html_e('Maybe Later', 'ultimate-security'); ?>
                </button>
                <button type="button" class="button us-review-btn" data-action="already-reviewed">
                    <?php esc_html_e('Already Reviewed', 'ultimate-security'); ?>
                </button>
            </p>
        </div>
        <?php
    }
    public static function ultimate_security_admin_footer_feedback() {
        ?>
        <script type="text/javascript">
            document.addEventListener("DOMContentLoaded", function() {
                let link = document.querySelector("a[href='admin.php?page=ultimate-security-contact']");
                if (link) {
                    link.setAttribute("href", "https://wpultimatesecurity.com/contact-us/");
                    link.setAttribute("target", "_blank"); // Open in new tab
                    // // Add dashicon before or after the text
                    link.innerHTML += ' <span class="dashicons dashicons-external" style="vertical-align:middle;"></span>';
            
                }
            });
        </script>
        <?php
    }
}
