<?php
/**
 * Onboarding System
 *
 * Provides guided tours for first-time users on key plugin pages.
 * Tours are displayed as overlay cards anchored to specific UI sections.
 *
 * @package VMPFence
 * @since 2.2.4
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * VMPFence Onboarding Class
 *
 * Manages per-page onboarding tours with custom overlay cards
 * positioned relative to target UI sections. Tour state is persisted
 * globally in vmpfence_config table.
 */
class VMPFence_Onboarding {

    /**
     * Initialize the onboarding system
     *
     * @since 2.2.4
     */
    public static function init() {
        add_action('admin_enqueue_scripts', array(__CLASS__, 'enqueue_assets'));
        add_action('wp_ajax_vmpfence_dismiss_onboarding', array(__CLASS__, 'ajax_dismiss'));
        add_action('wp_ajax_vmpfence_reset_onboarding', array(__CLASS__, 'ajax_reset'));
    }

    /**
     * Get current page key from WordPress hook suffix
     *
     * @since 2.2.4
     * @param string $hook WordPress admin hook suffix
     * @return string|false Page key or false if not a plugin page
     */
    private static function get_current_page_key($hook) {
        // Dashboard page
        if (strpos($hook, 'vmpfence-dashboard') !== false) {
            return 'dashboard';
        }

        // Login Security (2FA) page
        if (strpos($hook, 'vmpfence-login-security') !== false) {
            return 'login_security';
        }

        // Scan page
        if (strpos($hook, 'vmpfence-scan') !== false) {
            return 'scan';
        }

        // Firewall page (with blocking tab)
        if (strpos($hook, 'vmpfence-firewall') !== false) {
            $tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'firewall';
            if ($tab === 'blocking') {
                return 'blocking';
            }
            return 'firewall';
        }

        // Tools page (live traffic and audit log tabs)
        if (strpos($hook, 'vmpfence-tools') !== false) {
            $tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'live-traffic';
            if ($tab === 'audit-log') {
                return 'audit_log';
            }
            if ($tab === 'live-traffic') {
                return 'live_traffic';
            }
        }

        // Direct Live Traffic page (alternative URL)
        if (strpos($hook, 'vmpfence-live-traffic') !== false) {
            return 'live_traffic';
        }

        // Direct Audit Log page (alternative URL)
        if (strpos($hook, 'vmpfence-audit-log') !== false) {
            return 'audit_log';
        }

        return false;
    }

    /**
     * Get tour step data for all pages
     *
     * @since 2.2.4
     * @return array Associative array of page keys to tour steps
     * Property	          Purpose	                                                Values
     *
     * placement	 Fix card side (skips auto-detect)	                 'top', 'bottom', 'left', 'right'
     * arrow	     Fix arrow edge (skips auto-derive)	                  'up', 'down', 'left', 'right'
     * offsetTop	 Nudge card vertically (% of target height)	                   e.g. -20, 15
     * offsetLeft	 Nudge card horizontally (% of target width)	                   e.g. 10, -5
     * arrowOffsetX	 Nudge arrow along its edge (px)                                   e.g. -50, 30
     * 
     * 
     */
    private static function get_tour_data() {
        return array(
            'dashboard' => array(
                array(
                    'selector' => '#vmpfence-firewall-progress',
                    'title' => __('This is your Dashboard', 'vmpfence-security'),
                    'description' => __('The VMP Security Dashboard provides valuable insights into the current state of your site\'s security. You\'ll find useful data summarized here as well as important status updates and notifications.', 'vmpfence-security'),
                    'offsetTop' => -70,
                    'placement' => 'bottom',
                    'arrowOffsetX' => -130
                ),
                array(
                    'selector' => '#vmpfence-notifications-section',
                    'title' => __('Easily Monitor Your VMP Security Protection', 'vmpfence-security'),
                    'description' => __('Each feature contains a status that reminds you what\'s enabled, disabled or need attention. The Notification section will highlight actions you need to take.', 'vmpfence-security'),
                    'offsetTop' => -20,
                    'placement' => 'bottom',
                    'arrowOffsetX' => -130
                ),
                array(
                    'selector' => '#vmpfence-global-options-link',
                    'title' => __('Global VMP Security Options', 'vmpfence-security'),
                    'description' => __('You will find this icon throughout the plugin. Clicking it will show you the options and features for each section of VMP Security. From the dashboard, you can find the <strong>Global Options</strong> for VMP Security such as alerts, automatic updates, and managing your site\'s Premium License.', 'vmpfence-security'),
                    'iconSvg' => '<svg viewBox="0 0 100.11 100.11" class="wf-block-navigation-option-icon"><title>options</title><path d="M99.59,41.42a2.06,2.06,0,0,0-1.37-.82L86.3,38.78a39.34,39.34,0,0,0-2.67-6.39q1.17-1.63,3.52-4.6t3.32-4.33A2.52,2.52,0,0,0,91,22a2.1,2.1,0,0,0-.46-1.43Q88.18,17.2,79.78,9.45a2.52,2.52,0,0,0-1.63-.65,2.12,2.12,0,0,0-1.57.59l-9.25,7a40.09,40.09,0,0,0-5.87-2.41L59.64,2a1.92,1.92,0,0,0-.75-1.4A2.46,2.46,0,0,0,57.29,0H42.82a2.19,2.19,0,0,0-2.34,1.82,106,106,0,0,0-1.89,12.12,37.62,37.62,0,0,0-5.93,2.48l-9-7A2.78,2.78,0,0,0,22,8.8q-1.44,0-6.16,4.66a64.88,64.88,0,0,0-6.42,7A2.75,2.75,0,0,0,8.8,22a2.44,2.44,0,0,0,.65,1.56q4.37,5.28,7,9a32.38,32.38,0,0,0-2.54,6L1.76,40.34a2,2,0,0,0-1.24.85A2.5,2.5,0,0,0,0,42.69V57.16a2.44,2.44,0,0,0,.52,1.53,2,2,0,0,0,1.37.82l11.93,1.76a31.91,31.91,0,0,0,2.67,6.45Q15.31,69.35,13,72.31T9.65,76.65a2.54,2.54,0,0,0-.07,3q2.54,3.52,10.75,11a2.25,2.25,0,0,0,1.63.71,2.35,2.35,0,0,0,1.63-.59l9.19-7a40.54,40.54,0,0,0,5.87,2.41l1.82,12a1.92,1.92,0,0,0,.75,1.4,2.45,2.45,0,0,0,1.6.55H57.29a2.2,2.2,0,0,0,2.35-1.82,107.41,107.41,0,0,0,1.89-12.12,37.19,37.19,0,0,0,5.93-2.48l9,7a3.18,3.18,0,0,0,1.69.59q1.43,0,6.13-4.62a65.86,65.86,0,0,0,6.45-7,2.16,2.16,0,0,0,.59-1.5,2.51,2.51,0,0,0-.65-1.63q-4.69-5.74-7-9a41.57,41.57,0,0,0,2.54-5.93l12.06-1.82a2,2,0,0,0,1.3-.85,2.52,2.52,0,0,0,.52-1.5V43a2.46,2.46,0,0,0-.52-1.53ZM61.85,61.86a16.08,16.08,0,0,1-11.8,4.89A16.69,16.69,0,0,1,33.37,50.06,16.69,16.69,0,0,1,50.06,33.37,16.69,16.69,0,0,1,66.74,50.06a16.08,16.08,0,0,1-4.89,11.8Zm0,0"></path></svg>',
                    'placement' => 'left',
                    'offsetLeft' => 6,
                    'arrowOffsetX' => -130
                )
            ),

            'login_security' => array(
                array(
                    'selector' => '#vmpfence-2fa-header',
                    'title' => __('Introducing the New VMP Security 2FA', 'vmpfence-security'),
                    'description' => __('We are excited to announce the release of a completely rebuilt two-factor authentication (2FA) feature within VMP Security. 2FA is an important layer of security that protects you from password guessing and credential stuffing attacks. Previously a Premium-only feature, it is now available for sites running the free version of VMP Security. You are now able to enable 2FA for any role, we\'ve added a number of important security features, and we\'ve significantly improved the admin interface.', 'vmpfence-security'),
                    'placement' => 'bottom',
                    'offsetTop' => 70,
                    'arrowOffsetX' => -490,
                    'offsetLeft' => -17
                ),
                array(
                    'selector' => '#vmpfence-ip-allowlist',
                    'title' => __('Individual Allowlisting', 'vmpfence-security'),
                    'description' => __('Two-factor authentication now has its own IP allowlist. If necessary, you can allow specific IP addresses or ranges to skip 2FA when logging in.', 'vmpfence-security'),
                    'placement' => 'top',
                    'offsetTop' => 10
                ),
                array(
                    'selector' => '#vmpfence-recaptcha-settings',
                    'title' => __('New Login Page Captcha Feature', 'vmpfence-security'),
                    'description' => __('VMP Security now includes the option to enable Google reCaptcha v3 on your WordPress login and registration pages. This adds a powerful new layer of protection against password guessing and credential stuffing attacks from bots without slowing down real users.', 'vmpfence-security'),
                    'placement' => 'top',
                    'offsetTop' => 10
                )
            ),

            'firewall' => array(
                array(
                    'selector' => '#vmpfence-firewall-status',
                    'title' => __('The VMP Security firewall protects your sites from attackers', 'vmpfence-security'),
                    'description' => __('This is where you can monitor the work VMP Security is doing to protect your site and also where you can manage the options to optimize the firewall\'s configuration.', 'vmpfence-security'),
                    'placement' => 'bottom',
                    'arrowOffsetX' => -250,
                    'offsetTop' => -70
                ),
                array(
                    'selector' => '#vmpfence-firewall-waf-status',
                    'title' => __('Web Application Firewall (WAF)', 'vmpfence-security'),
                    'description' => __('The VMP Security Web Application Firewall blocks known and emerging attacks using firewall rules. When you first install the WAF, it will be in default mode. This allows VMP Security to protect your site in the best way possible with our pre-configured settings. We also recommend you to optimize the firewall to enable extended protection.', 'vmpfence-security'),
                    'placement' => 'bottom',
                    'arrowOffsetX' => -100,
                    'offsetTop' => -10,
                    'offsetLeft' => 68
                ),
                array(
                    'selector' => '#vmpfence-firewall-brute-force-status',
                    'title' => __('Brute Force Protection', 'vmpfence-security'),
                    'description' => __('VMP Security protects your site from password-guessing attacks by locking out attackers and helping you avoid weak passwords.', 'vmpfence-security'),
                    'arrow' => 'right',
                    'placement' => 'left',
                    'offsetLeft' => 10
                ),
                array(
                    'selector' => '#vmpfence-firewall-options-box',
                    'title' => __('Firewall Options', 'vmpfence-security'),
                    'description' => __('Set up the way you want the firewall to protect your site including the web application firewall, brute force protection, rate limiting, and blocking.', 'vmpfence-security'),
                    'iconSvg' => '<svg viewBox="0 0 100.11 100.11" class="wf-block-navigation-option-icon"><title>options</title><path d="M99.59,41.42a2.06,2.06,0,0,0-1.37-.82L86.3,38.78a39.34,39.34,0,0,0-2.67-6.39q1.17-1.63,3.52-4.6t3.32-4.33A2.52,2.52,0,0,0,91,22a2.1,2.1,0,0,0-.46-1.43Q88.18,17.2,79.78,9.45a2.52,2.52,0,0,0-1.63-.65,2.12,2.12,0,0,0-1.57.59l-9.25,7a40.09,40.09,0,0,0-5.87-2.41L59.64,2a1.92,1.92,0,0,0-.75-1.4A2.46,2.46,0,0,0,57.29,0H42.82a2.19,2.19,0,0,0-2.34,1.82,106,106,0,0,0-1.89,12.12,37.62,37.62,0,0,0-5.93,2.48l-9-7A2.78,2.78,0,0,0,22,8.8q-1.44,0-6.16,4.66a64.88,64.88,0,0,0-6.42,7A2.75,2.75,0,0,0,8.8,22a2.44,2.44,0,0,0,.65,1.56q4.37,5.28,7,9a32.38,32.38,0,0,0-2.54,6L1.76,40.34a2,2,0,0,0-1.24.85A2.5,2.5,0,0,0,0,42.69V57.16a2.44,2.44,0,0,0,.52,1.53,2,2,0,0,0,1.37.82l11.93,1.76a31.91,31.91,0,0,0,2.67,6.45Q15.31,69.35,13,72.31T9.65,76.65a2.54,2.54,0,0,0-.07,3q2.54,3.52,10.75,11a2.25,2.25,0,0,0,1.63.71,2.35,2.35,0,0,0,1.63-.59l9.19-7a40.54,40.54,0,0,0,5.87,2.41l1.82,12a1.92,1.92,0,0,0,.75,1.4,2.45,2.45,0,0,0,1.6.55H57.29a2.2,2.2,0,0,0,2.35-1.82,107.41,107.41,0,0,0,1.89-12.12,37.19,37.19,0,0,0,5.93-2.48l9,7a3.18,3.18,0,0,0,1.69.59q1.43,0,6.13-4.62a65.86,65.86,0,0,0,6.45-7,2.16,2.16,0,0,0,.59-1.5,2.51,2.51,0,0,0-.65-1.63q-4.69-5.74-7-9a41.57,41.57,0,0,0,2.54-5.93l12.06-1.82a2,2,0,0,0,1.3-.85,2.52,2.52,0,0,0,.52-1.5V43a2.46,2.46,0,0,0-.52-1.53ZM61.85,61.86a16.08,16.08,0,0,1-11.8,4.89A16.69,16.69,0,0,1,33.37,50.06,16.69,16.69,0,0,1,50.06,33.37,16.69,16.69,0,0,1,66.74,50.06a16.08,16.08,0,0,1-4.89,11.8Zm0,0"></path></svg>',
                    'placement' => 'left',
                    'offsetLeft' => 0,
                    'arrow' => 'right'
                )
            ),

            'blocking' => array(
                array(
                    'selector' => '#vmpfence-blocking-options-left',
                    'title' => __('Blocking', 'vmpfence-security'),
                    'description' => __('VMP Security lets you take control of protecting your site with powerful blocking features. Block traffic based on IP, IP range, hostname, browser, or referrer. Country blocking is available for Premium customers.', 'vmpfence-security'),
                    'placement' => 'bottom',
                    'arrow' => 'up',
                    'offsetTop' => -150,
                    'arrowOffsetX' => -130
                ),
                array(
                    'selector' => '#vmpfence-block-tabs',
                    'title' => __('Blocking Builder', 'vmpfence-security'),
                    'description' => __('All of your blocking rules are in one central location. Choose the Block Type, then enter the details for the rule. Once it has been added, you\'ll see it saved as a rule for your site.', 'vmpfence-security'),
                    'placement' => 'bottom',
                    'arrow' => 'up',
                    'offsetTop' => -5,
                    'arrowOffsetX' => -230
                ),
                array(
                    'selector' => '#vmpfence-ip-table-section',
                    'title' => __('Manage Blocking Rules', 'vmpfence-security'),
                    'description' => __('Here\'s where you\'ll see all the blocking rules you\'ve created. You can also manage them as well as remove or modify them from this table.', 'vmpfence-security'),
                    'placement' => 'top',
                    'arrow' => 'down',
                    'offsetTop' => 5,
                    'arrowOffsetX' => -230
                )
            ),

            'scan' => array(
                array(
                    'selector' => '#vmpfence-scan-status',
                    'title' => __('Scan', 'vmpfence-security'),
                    'description' => __('A VMP Security scan looks for malware, malicious URLs, and patterns of infections by examining all of the files, posts, and comments on your WordPress website. It also checks your server and monitors your site\'s online reputation.', 'vmpfence-security'),
                    'placement' => 'bottom',
                    'offsetTop' => -80,
                    'arrowOffsetX' => -230
                ),
                array(
                    'selector' => '#vmpfence-scan-options',
                    'title' => __('Manage Scan Settings', 'vmpfence-security'),
                    'description' => __('Set up the way you want the scan to monitor your site security including custom scan configurations and scheduling.', 'vmpfence-security'),
                    'iconSvg' => '<svg viewBox="0 0 100.11 100.11" class="wf-block-navigation-option-icon"><title>options</title><path d="M99.59,41.42a2.06,2.06,0,0,0-1.37-.82L86.3,38.78a39.34,39.34,0,0,0-2.67-6.39q1.17-1.63,3.52-4.6t3.32-4.33A2.52,2.52,0,0,0,91,22a2.1,2.1,0,0,0-.46-1.43Q88.18,17.2,79.78,9.45a2.52,2.52,0,0,0-1.63-.65,2.12,2.12,0,0,0-1.57.59l-9.25,7a40.09,40.09,0,0,0-5.87-2.41L59.64,2a1.92,1.92,0,0,0-.75-1.4A2.46,2.46,0,0,0,57.29,0H42.82a2.19,2.19,0,0,0-2.34,1.82,106,106,0,0,0-1.89,12.12,37.62,37.62,0,0,0-5.93,2.48l-9-7A2.78,2.78,0,0,0,22,8.8q-1.44,0-6.16,4.66a64.88,64.88,0,0,0-6.42,7A2.75,2.75,0,0,0,8.8,22a2.44,2.44,0,0,0,.65,1.56q4.37,5.28,7,9a32.38,32.38,0,0,0-2.54,6L1.76,40.34a2,2,0,0,0-1.24.85A2.5,2.5,0,0,0,0,42.69V57.16a2.44,2.44,0,0,0,.52,1.53,2,2,0,0,0,1.37.82l11.93,1.76a31.91,31.91,0,0,0,2.67,6.45Q15.31,69.35,13,72.31T9.65,76.65a2.54,2.54,0,0,0-.07,3q2.54,3.52,10.75,11a2.25,2.25,0,0,0,1.63.71,2.35,2.35,0,0,0,1.63-.59l9.19-7a40.54,40.54,0,0,0,5.87,2.41l1.82,12a1.92,1.92,0,0,0,.75,1.4,2.45,2.45,0,0,0,1.6.55H57.29a2.2,2.2,0,0,0,2.35-1.82,107.41,107.41,0,0,0,1.89-12.12,37.19,37.19,0,0,0,5.93-2.48l9,7a3.18,3.18,0,0,0,1.69.59q1.43,0,6.13-4.62a65.86,65.86,0,0,0,6.45-7,2.16,2.16,0,0,0,.59-1.5,2.51,2.51,0,0,0-.65-1.63q-4.69-5.74-7-9a41.57,41.57,0,0,0,2.54-5.93l12.06-1.82a2,2,0,0,0,1.3-.85,2.52,2.52,0,0,0,.52-1.5V43a2.46,2.46,0,0,0-.52-1.53ZM61.85,61.86a16.08,16.08,0,0,1-11.8,4.89A16.69,16.69,0,0,1,33.37,50.06,16.69,16.69,0,0,1,50.06,33.37,16.69,16.69,0,0,1,66.74,50.06a16.08,16.08,0,0,1-4.89,11.8Zm0,0"></path></svg>',
                    'placement' => 'left',
                    'arrow' => 'right',
                    'offsetLeft' => 10,
                ),
                array(
                    'selector' => '#vmpfence-start-scan',
                    'title' => __('Start Your First Scan', 'vmpfence-security'),
                    'description' => __('By default, VMP Security will scan your site daily. Start your first scan now to see if your site has any security issues that need to be addressed. From here you can run manual scans any time you like.', 'vmpfence-security'),
                    'arrow' => 'left',
                    'placement' => 'right',
                    'offsetLeft' => -20,
                )
            ),

            'live_traffic' => array(
                array(
                    'selector' => '#live-traffic-table-container',
                    'title' => __('Live Traffic', 'vmpfence-security'),
                    'description' => __('Live traffic defaults to a summary view of all security-related traffic. Details are viewable by clicking anywhere within the summary record. To switch to the expanded view, click the <strong>Expand All Records</strong> switch.', 'vmpfence-security'),
                    'placement' => 'top',
                    'offsetTop' => 6,
                    'arrowOffsetX' => -290
                )
            ),

            'audit_log' => array(
                array(
                    'selector' => '#audit-log-recent-event-summary',
                    'title' => __('Audit Log', 'vmpfence-security'),
                    'description' => __('The VMP Security Audit Log is a premium feature that records a history of events on your site to assist in monitoring for unauthorized actions or signs of compromise. Events can include everything from user creation and editing to plugin/theme installation and updates. All data captured for relevant events is saved remotely to VMP Security Central to prevent any tampering that may interfere with post-incident analysis and response.', 'vmpfence-security'),
                    'placement' => 'top',
                    'offsetTop' => 220,
                    'arrowOffsetX' => -290
                )
            )
        );
    }

    /**
     * Enqueue onboarding assets on plugin pages
     *
     * @since 2.2.4
     * @param string $hook WordPress admin hook suffix
     */
    public static function enqueue_assets($hook) {
        // Only show onboarding if license is activated
        $license_key = VMPFence_Config::get('license_key', '');
        if (empty($license_key)) {
            return;
        }

        // Only load on plugin pages
        if (strpos($hook, 'vmpfence') === false) {
            return;
        }

        // Get current page key
        $page_key = self::get_current_page_key($hook);
        if (!$page_key) {
            return;
        }

        // Check if tour is already dismissed for this page
        $dismissed = VMPFence_Config::get('onboarding_dismissed', array());
        if (!empty($dismissed[$page_key])) {
            return;
        }

        // Get tour steps for this page
        $all_tours = self::get_tour_data();
        if (!isset($all_tours[$page_key]) || empty($all_tours[$page_key])) {
            return;
        }

        $steps = $all_tours[$page_key];

        // Enqueue CSS
        wp_enqueue_style(
            'vmpfence-onboarding',
            VMPFENCE_PLUGIN_URL . 'admin/assets/css/onboarding.css',
            array(),
            VMPFENCE_VERSION
        );

        // Enqueue JS
        wp_enqueue_script(
            'vmpfence-onboarding',
            VMPFENCE_PLUGIN_URL . 'admin/assets/js/onboarding.js',
            array('jquery'),
            VMPFENCE_VERSION,
            true
        );

        // Localize script with tour data
        wp_localize_script(
            'vmpfence-onboarding',
            'vmpfenceOnboarding',
            array(
                'steps' => $steps,
                'pageKey' => $page_key,
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('vmpfence_onboarding_nonce')
            )
        );
    }

    /**
     * AJAX handler for dismissing onboarding tours
     *
     * @since 2.2.4
     */
    public static function ajax_dismiss() {
        check_ajax_referer('vmpfence_onboarding_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'vmpfence-security')));
        }

        $page_key = isset($_POST['page_key']) ? sanitize_text_field($_POST['page_key']) : '';

        // Validate page key
        $allowed_keys = array('dashboard', 'firewall', 'blocking', 'scan', 'login_security', 'live_traffic', 'audit_log');
        if (!in_array($page_key, $allowed_keys, true)) {
            wp_send_json_error(array('message' => __('Invalid page key', 'vmpfence-security')));
        }

        // Get current dismissed state
        $dismissed = VMPFence_Config::get('onboarding_dismissed', array());

        // Mark this page as dismissed
        $dismissed[$page_key] = true;

        // Save back to config
        $result = VMPFence_Config::set('onboarding_dismissed', $dismissed);

        if ($result) {
            wp_send_json_success(array('message' => __('Tour dismissed successfully', 'vmpfence-security')));
        } else {
            wp_send_json_error(array('message' => __('Failed to save dismissal state', 'vmpfence-security')));
        }
    }

    /**
     * AJAX handler for resetting all onboarding tours
     *
     * @since 2.2.4
     */
    public static function ajax_reset() {
        check_ajax_referer('vmpfence_onboarding_reset_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'vmpfence-security')));
        }

        // Reset all tours
        $result = VMPFence_Config::set('onboarding_dismissed', array());

        if ($result) {
            wp_send_json_success(array('message' => __('All tours have been reset. Refresh the page to see tours again.', 'vmpfence-security')));
        } else {
            wp_send_json_error(array('message' => __('Failed to reset tours', 'vmpfence-security')));
        }
    }

    /**
     * Reset all tours (public method for programmatic access)
     *
     * @since 2.2.4
     * @return bool True on success, false on failure
     */
    public static function reset_all_tours() {
        return VMPFence_Config::set('onboarding_dismissed', array());
    }
}
