<?php
/**
 * Admin Class
 *
 * @package CodeandcoreUserRegistrationCF7
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Class CNC_CF7_Admin
 *
 * Handles settings page registration, UI rendering, and AJAX handlers.
 */
class CNC_CF7_Admin
{
    /**
     * Initialize the admin hooks
     */
    public static function init()
    {
        add_action('admin_menu', [__CLASS__, 'add_admin_menu']);
        add_filter('plugin_action_links_' . plugin_basename(CNC_CF7_PLUGIN_DIR . 'codeandcore-user-registration-cf7.php'), [__CLASS__, 'add_settings_link']);
        add_action('activated_plugin', [__CLASS__, 'activation_redirect']);
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_settings_assets']);
        add_action('wp_ajax_cnc_cf7_tracking_optin', [__CLASS__, 'handle_optin_ajax']);
        add_action('admin_init', [__CLASS__, 'register_settings']);
    }

    /**
     * Register the settings menu
     */
    public static function add_admin_menu()
    {
        add_options_page(
            __('CF7 User Registration Settings', 'codeandcore-user-registration-cf7'),
            __('CF7 User Registration', 'codeandcore-user-registration-cf7'),
            'manage_options',
            'codeandcore-user-registration-cf7',
            [__CLASS__, 'display_settings_page']
        );
    }

    /**
     * Add settings link to plugin list
     */
    public static function add_settings_link($links)
    {
        $settings_link = '<a href="options-general.php?page=codeandcore-user-registration-cf7">' . __('Settings', 'codeandcore-user-registration-cf7') . '</a>';
        array_unshift($links, $settings_link);
        return $links;
    }

    /**
     * Redirect to settings page on activation
     */
    public static function activation_redirect($plugin)
    {
        if ($plugin == plugin_basename(CNC_CF7_PLUGIN_DIR . 'codeandcore-user-registration-cf7.php')) {
            wp_safe_redirect(admin_url('options-general.php?page=codeandcore-user-registration-cf7'));
            exit;
        }
    }

    /**
     * Enqueue scripts and styles for settings page
     */
    public static function enqueue_settings_assets($hook)
    {
        if ($hook !== 'settings_page_codeandcore-user-registration-cf7') {
            return;
        }

        wp_enqueue_style(
            'cnc-cf7-google-fonts',
            'https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap',
            array(),
            CNC_CF7_VERSION
        );

        wp_enqueue_style(
            'cnc-cf7-settings-css',
            CNC_CF7_PLUGIN_URL . 'assets/css/settings.css',
            array(),
            CNC_CF7_VERSION
        );

        wp_enqueue_script(
            'cnc-cf7-settings-js',
            CNC_CF7_PLUGIN_URL . 'assets/js/settings.js',
            array('jquery'),
            CNC_CF7_VERSION,
            true
        );

        wp_localize_script('cnc-cf7-settings-js', 'cnc_cf7_settings', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('cnc_cf7_optin_nonce'),
            'strings' => array(
                'optin_success' => __('Settings updated successfully.', 'codeandcore-user-registration-cf7'),
                'optin_error' => __('Error updating settings.', 'codeandcore-user-registration-cf7'),
            )
        ));
    }

    /**
     * Register settings
     */
    public static function register_settings()
    {
        register_setting('cnc_cf7_settings_group', 'cnc_cf7_tracking_optin', ['sanitize_callback' => 'sanitize_text_field']);
    }

    /**
     * Handle AJAX request for tracking opt-in decision
     */
    public static function handle_optin_ajax()
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'codeandcore-user-registration-cf7')], 403);
        }

        check_ajax_referer('cnc_cf7_optin_nonce', 'nonce');

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

        if (!in_array($status, ['yes', 'no'], true)) {
            wp_send_json_error(['message' => __('Invalid selection', 'codeandcore-user-registration-cf7')], 400);
        }

        update_option('cnc_cf7_tracking_optin', $status);

        if ($status === 'no') {
            delete_option('cnc_cf7_plugin_version');
        }

        wp_send_json_success(['status' => $status]);
    }

    /**
     * Render the settings page HTML
     */
    public static function display_settings_page()
    {
        $tracking_optin = get_option('cnc_cf7_tracking_optin', 'no');
        ?>
        <div class="wrap cnc-cf7-settings-wrap">
            <h1>
                <?php esc_html_e('Codeandcore User Registration for CF7', 'codeandcore-user-registration-cf7'); ?>
            </h1>

            <div class="cnc-cf7-settings-container">
                <!-- Analytics Section -->
                <div class="cnc-cf7-card cnc-cf7-analytics-card">
                    <h2><span class="dashicons dashicons-chart-area"></span>
                        <?php esc_html_e('Analytics & Usage Tracking', 'codeandcore-user-registration-cf7'); ?>
                    </h2>

                    <p>
                        <?php esc_html_e('Help us improve this plugin by allowing us to collect anonymous, non-personal technical information such as:', 'codeandcore-user-registration-cf7'); ?>
                    </p>

                    <ul class="cnc-cf7-tracking-list">
                        <li><span class="dashicons dashicons-yes"></span>
                            <?php esc_html_e('Site URL (domain only)', 'codeandcore-user-registration-cf7'); ?>
                        </li>
                        <li><span class="dashicons dashicons-yes"></span>
                            <?php esc_html_e('WordPress version', 'codeandcore-user-registration-cf7'); ?>
                        </li>
                        <li><span class="dashicons dashicons-yes"></span>
                            <?php esc_html_e('PHP version', 'codeandcore-user-registration-cf7'); ?>
                        </li>
                        <li><span class="dashicons dashicons-yes"></span>
                            <?php esc_html_e('Plugin version', 'codeandcore-user-registration-cf7'); ?>
                        </li>
                        <li><span class="dashicons dashicons-yes"></span>
                            <?php esc_html_e('Theme name and version', 'codeandcore-user-registration-cf7'); ?>
                        </li>
                        <li><span class="dashicons dashicons-yes"></span>
                            <?php esc_html_e('Activation/deactivation/update events', 'codeandcore-user-registration-cf7'); ?>
                        </li>
                    </ul>

                    <div class="cnc-cf7-notice-info">
                        <span class="dashicons dashicons-shield"></span>
                        <?php esc_html_e('No personal data, user information, IP addresses, or sensitive details are ever collected or stored.', 'codeandcore-user-registration-cf7'); ?>
                    </div>

                    <div class="cnc-cf7-actions">
                        <p class="cnc-cf7-status-label">
                            <?php esc_html_e('Current Status:', 'codeandcore-user-registration-cf7'); ?>
                        </p>

                        <div class="cnc-cf7-status-badge <?php echo $tracking_optin === 'yes' ? 'enabled' : 'disabled'; ?>">
                            <?php if ($tracking_optin === 'yes'): ?>
                                <span class="dashicons dashicons-yes"></span>
                                <?php esc_html_e('ENABLED', 'codeandcore-user-registration-cf7'); ?>
                            <?php else: ?>
                                <span class="dashicons dashicons-no"></span>
                                <?php esc_html_e('DISABLED', 'codeandcore-user-registration-cf7'); ?>
                            <?php endif; ?>
                        </div>

                        <div class="cnc-cf7-buttons">
                            <button type="button" class="button button-primary cnc-cf7-enable-tracking" <?php echo $tracking_optin === 'yes' ? 'disabled' : ''; ?>>
                                <span class="dashicons dashicons-yes"></span>
                                <?php esc_html_e('Enable Tracking', 'codeandcore-user-registration-cf7'); ?>
                            </button>

                            <button type="button" class="button button-secondary cnc-cf7-disable-tracking" <?php echo $tracking_optin !== 'yes' ? 'disabled' : ''; ?>>
                                <span class="dashicons dashicons-no"></span>
                                <?php esc_html_e('Disable Tracking', 'codeandcore-user-registration-cf7'); ?>
                            </button>
                        </div>

                        <span class="spinner"></span>
                    </div>
                </div>

                <!-- Sidebar -->
                <div class="cnc-cf7-sidebar">
                    <div class="cnc-cf7-card cnc-cf7-sidebar-card">
                        <h3><span class="dashicons dashicons-star-filled" style="color: #f39c12;"></span>
                            <?php esc_html_e('More Plugins by Code and Core', 'codeandcore-user-registration-cf7'); ?></h3>
                        <p class="cnc-cf7-sidebar-desc">
                            <?php esc_html_e('Handpicked tools for content teams & developers', 'codeandcore-user-registration-cf7'); ?>
                        </p>


                        <!-- Card 1: WYSIWYG -->
                        <div class="cnc-cf7-promo-plugin">
                            <div class="cnc-cf7-promo-icon-img">
                                <img src="<?php echo esc_url(CNC_CF7_PLUGIN_URL . 'assets/images/code-and-core-remove-empty-p-tags.png'); ?>"
                                    alt="WYSIWYG Character Limit for ACF">
                            </div>
                            <h4>WYSIWYG Character Limit for ACF</h4>
                            <span class="cnc-cf7-badge cnc-cf7-badge-free">FREE</span>
                            <p>Set character limits for ACF WYSIWYG fields with a live counter and validation for better content
                                control.</p>
                            <a href="https://wordpress.org/plugins/wysiwyg-character-limit-for-acf/" target="_blank"
                                class="button button-primary cnc-cf7-button-purple">View Plugin</a>
                        </div>

                        <!-- Card 2: Speedy Go -->
                        <div class="cnc-cf7-promo-plugin cnc-cf7-promo-speedy">
                            <div class="cnc-cf7-promo-icon-img cnc-cf7-icon-speedy">
                                <img src="<?php echo esc_url(CNC_CF7_PLUGIN_URL . 'assets/images/speedy-go.gif'); ?>"
                                    alt="Speedy Go">
                            </div>
                            <h4>Speedy Go</h4>
                            <span class="cnc-cf7-badge cnc-cf7-badge-featured">FEATURED</span>
                            <p>Optimize your WordPress site performance with advanced caching and speed optimization tools.</p>
                            <a href="https://wordpress.org/plugins/speedy-go/" target="_blank"
                                class="button button-primary cnc-cf7-button-purple">View Plugin</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }
}
