<?php

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

class CSCF_ACF_Tracking
{
    private $api_url = 'https://red-fly-431376.hostingersite.com/receiver.php';
    private $secret_key = '8jF29fLkmsP0V9as0DLkso2P9lKs29FjsP4k2F0lskM2k';

    public function init()
    {
        add_action('admin_menu', [$this, 'add_settings_page']);
        add_action('admin_init', [$this, 'handle_settings_save']);
        add_action('admin_init', [$this, 'handle_activation_redirect']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
        add_action('upgrader_process_complete', [$this, 'track_plugin_update'], 10, 2);
        add_filter('plugin_action_links_' . plugin_basename(CSCF_ACF_PLUGIN_FILE), [$this, 'add_settings_link']);
    }

    public function add_settings_link($links)
    {
        $settings_link = '<a href="' . admin_url('edit.php?post_type=acf-field-group&page=cscf-acf-settings') . '">' . __('Settings', 'cross-site-copy-field-for-acf') . '</a>';
        array_unshift($links, $settings_link);
        return $links;
    }

    public function handle_activation_redirect()
    {
        if (get_transient('cscf_acf_activation_redirect')) {
            delete_transient('cscf_acf_activation_redirect');
            if (current_user_can('manage_options')) {
                wp_safe_redirect(admin_url('edit.php?post_type=acf-field-group&page=cscf-acf-settings'));
                exit;
            }
        }
    }

    private function build_payload($event, $extra = [])
    {
        $info = $this->get_plugin_info();
        $theme = wp_get_theme();
        $base_payload = [
            'site_url' => home_url(),
            'plugin_name' => $info['Name'],
            'plugin_version' => $info['Version'],
            'event' => $event,
            'php_version' => phpversion(),
            'wp_version' => get_bloginfo('version'),
            'theme_name' => $theme->get('Name'),
            'theme_version' => $theme->get('Version'),
            'is_multisite' => is_multisite() ? 'yes' : 'no',
            'site_language' => get_locale(),
            'timestamp' => time(),
        ];
        return array_merge($base_payload, $extra);
    }

    private function encrypt_payload($data)
    {
        $iv = openssl_random_pseudo_bytes(16);
        $encrypted = openssl_encrypt(json_encode($data), 'AES-256-CBC', $this->secret_key, 0, $iv);
        return base64_encode($iv . $encrypted);
    }

    public function send_tracking($event, $extra = [])
    {
        if (get_option('cscf_acf_tracking_optin') !== 'yes') {
            return;
        }
        $payload = $this->build_payload($event, $extra);
        $encrypted = $this->encrypt_payload($payload);
        $signature = hash_hmac('sha256', $encrypted, $this->secret_key);
        wp_remote_post($this->api_url, [
            'method' => 'POST',
            'body' => ['data' => $encrypted, 'signature' => $signature],
            'timeout' => 20,
            'blocking' => false,
        ]);
    }

    public function enqueue_admin_scripts($hook)
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Safe check for page slug
        if (!isset($_GET['page']) || $_GET['page'] !== 'cscf-acf-settings') {
            return;
        }
        wp_enqueue_style('cscf-acf-settings', CSCF_ACF_PLUGIN_URL . 'assets/css/admin-settings.css', array(), defined('CSCF_ACF_VERSION') ? CSCF_ACF_VERSION : '1.0.0');
        ?>
        <style>
            #acf-group-menu,
            .acf-admin-toolbar {
                display: none !important;
            }

            .notice,
            .updated,
            .error,
            .is-dismissible {
                display: none !important;
            }

            #wpbody-content {
                padding-bottom: 0;
            }
        </style>
        <?php
    }

    public function add_settings_page()
    {
        add_submenu_page(
            'edit.php?post_type=acf-field-group',
            __('Cross Site Copy Settings', 'cross-site-copy-field-for-acf'),
            __('Copy Field Settings', 'cross-site-copy-field-for-acf'),
            'manage_options',
            'cscf-acf-settings',
            [$this, 'render_settings_page']
        );
    }

    public function render_settings_page()
    {
        $tracking_optin = get_option('cscf_acf_tracking_optin', 'no');
        ?>
        <div class="wrap cscf-settings-wrap">
            <div class="cscf-header">
                <h1><?php esc_html_e('Cross Site Copy Field Settings', 'cross-site-copy-field-for-acf'); ?></h1>
                <p><?php esc_html_e('Manage your preferences and contribute to the ecosystem.', 'cross-site-copy-field-for-acf'); ?>
                </p>
            </div>

            <div class="cscf-container">
                <div class="cscf-main-content">
                    <div class="cscf-card">
                        <div class="cscf-analytics-header">
                            <span class="dashicons dashicons-chart-bar cscf-analytics-icon"></span>
                            <span
                                class="cscf-analytics-title"><?php esc_html_e('What we track to improve more feature', 'cross-site-copy-field-for-acf'); ?></span>
                        </div>

                        <div class="cscf-analytics-subtitle">
                            <?php esc_html_e('Help us improve this plugin by allowing us to collect anonymous, non-personal technical information such as:', 'cross-site-copy-field-for-acf'); ?>
                        </div>

                        <div class="cscf-feature-rows">
                            <div class="cscf-check-item">
                                <div class="cscf-check-circle">✓</div>
                                <span><?php esc_html_e('Site URL (domain only)', 'cross-site-copy-field-for-acf'); ?></span>
                            </div>
                            <div class="cscf-check-item">
                                <div class="cscf-check-circle">✓</div>
                                <span><?php esc_html_e('WordPress version', 'cross-site-copy-field-for-acf'); ?></span>
                            </div>
                            <div class="cscf-check-item">
                                <div class="cscf-check-circle">✓</div>
                                <span><?php esc_html_e('PHP version', 'cross-site-copy-field-for-acf'); ?></span>
                            </div>
                            <div class="cscf-check-item">
                                <div class="cscf-check-circle">✓</div>
                                <span><?php esc_html_e('Plugin version', 'cross-site-copy-field-for-acf'); ?></span>
                            </div>
                            <div class="cscf-check-item">
                                <div class="cscf-check-circle">✓</div>
                                <span><?php esc_html_e('Theme name and version', 'cross-site-copy-field-for-acf'); ?></span>
                            </div>
                            <div class="cscf-check-item">
                                <div class="cscf-check-circle">✓</div>
                                <span><?php esc_html_e('Activation/deactivation/update events', 'cross-site-copy-field-for-acf'); ?></span>
                            </div>
                        </div>

                        <div class="cscf-privacy-box">
                            <span class="dashicons dashicons-shield cscf-privacy-icon"></span>
                            <span
                                class="cscf-privacy-text"><?php esc_html_e('No personal data, user information, IP addresses, or sensitive details are ever collected or stored.', 'cross-site-copy-field-for-acf'); ?></span>
                        </div>

                        <form method="post" action="">
                            <?php wp_nonce_field('cscf_acf_settings_save', 'cscf_acf_nonce'); ?>

                            <div class="cscf-status-section">
                                <span
                                    class="cscf-status-label"><?php esc_html_e('Current Status:', 'cross-site-copy-field-for-acf'); ?></span>
                                <?php if ($tracking_optin === 'yes'): ?>
                                    <span class="cscf-status-badge enabled"><span class="dashicons dashicons-yes"></span>
                                        <?php esc_html_e('ENABLED', 'cross-site-copy-field-for-acf'); ?></span>
                                <?php else: ?>
                                    <span class="cscf-status-badge disabled"><span class="dashicons dashicons-no-alt"></span>
                                        <?php esc_html_e('DISABLED', 'cross-site-copy-field-for-acf'); ?></span>
                                <?php endif; ?>
                            </div>

                            <div class="cscf-action-buttons">
                                <?php if ($tracking_optin === 'yes'): ?>
                                    <!-- Status: ENABLED - Show subtle disable text link -->
                                    <button type="submit" name="cscf_acf_tracking_optin" value="yes" class="cscf-btn-secondary"
                                        disabled>
                                        <span class="dashicons dashicons-yes-alt"></span>
                                        <?php esc_html_e('Tracking Enabled', 'cross-site-copy-field-for-acf'); ?>
                                    </button>

                                    <button type="submit" name="cscf_acf_tracking_optin" value="no" class="cscf-btn-text-link">
                                        <?php esc_html_e('Disable Tracking', 'cross-site-copy-field-for-acf'); ?>
                                    </button>
                                <?php else: ?>
                                    <!-- Status: DISABLED - Show prominent Enable button -->
                                    <button type="submit" name="cscf_acf_tracking_optin" value="yes" class="cscf-btn-enable">
                                        <span class="dashicons dashicons-yes-alt"></span>
                                        <?php esc_html_e('Enable Tracking', 'cross-site-copy-field-for-acf'); ?>
                                    </button>

                                    <button type="submit" name="cscf_acf_tracking_optin" value="no" class="cscf-btn-disable">
                                        <span class="dashicons dashicons-dismiss"></span>
                                        <?php esc_html_e('Disable Tracking', 'cross-site-copy-field-for-acf'); ?>
                                    </button>
                                <?php endif; ?>
                            </div>


                            <input type="hidden" name="cscf_acf_save_settings" value="1">
                        </form>
                    </div>
                </div>

                <div class="cscf-sidebar">
                    <div class="cscf-sidebar-header">
                        <span class="dashicons dashicons-star-filled cscf-star-icon"></span>
                        <span
                            class="cscf-sidebar-title"><?php esc_html_e('More Plugins by Code and Core', 'cross-site-copy-field-for-acf'); ?></span>
                    </div>
                    <p class="cscf-sidebar-subtitle">
                        <?php esc_html_e('Handpicked tools for content teams & developers', 'cross-site-copy-field-for-acf'); ?>
                    </p>

                    <!-- Plugin Card 1 -->
                    <div class="cscf-plugin-card">
                        <div class="cscf-plugin-icon-large">
                            <img src="<?php echo esc_url(CSCF_ACF_PLUGIN_URL); ?>assets/images/wysiwyg-character-limit-for-acf.png"
                                alt="WYSIWYG" onerror="this.outerHTML='<span style=font-size:40px>📝</span>'">
                        </div>
                        <h4 class="cscf-plugin-title">
                            <?php esc_html_e('WYSIWYG Character Limit for ACF', 'cross-site-copy-field-for-acf'); ?>
                        </h4>
                        <span
                            class="cscf-plugin-badge free"><?php esc_html_e('FREE', 'cross-site-copy-field-for-acf'); ?></span>
                        <p class="cscf-plugin-description">
                            <?php esc_html_e('Set character limits for ACF WYSIWYG fields with a live counter and validation for better content control.', 'cross-site-copy-field-for-acf'); ?>
                        </p>
                        <a href="https://wordpress.org/plugins/" target="_blank" class="cscf-plugin-cta">
                            <?php esc_html_e('View Plugin', 'cross-site-copy-field-for-acf'); ?>
                            <span class="dashicons dashicons-external"></span>
                        </a>
                    </div>

                    <!-- Plugin Card 2 -->
                    <div class="cscf-plugin-card featured">
                        <div class="cscf-plugin-icon-large">
                            <img src="<?php echo esc_url(CSCF_ACF_PLUGIN_URL); ?>assets/images/speedy-go.gif" alt="Speedy Go"
                                onerror="this.outerHTML='<span style=font-size:40px>🚀</span>'">
                        </div>
                        <h4 class="cscf-plugin-title"><?php esc_html_e('Speedy Go', 'cross-site-copy-field-for-acf'); ?></h4>
                        <span
                            class="cscf-plugin-badge featured"><?php esc_html_e('FEATURED', 'cross-site-copy-field-for-acf'); ?></span>
                        <p class="cscf-plugin-description">
                            <?php esc_html_e('Optimize your WordPress site performance with advanced caching and speed optimization tools.', 'cross-site-copy-field-for-acf'); ?>
                        </p>
                        <a href="https://wordpress.org/plugins/" target="_blank" class="cscf-plugin-cta">
                            <?php esc_html_e('View Plugin', 'cross-site-copy-field-for-acf'); ?>
                            <span class="dashicons dashicons-external"></span>
                        </a>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    public function handle_settings_save()
    {
        if (!isset($_POST['cscf_acf_save_settings']))
            return;
        // Sanitize and unslash nonce for strict verification
        $nonce = isset($_POST['cscf_acf_nonce']) ? sanitize_text_field(wp_unslash($_POST['cscf_acf_nonce'])) : '';
        if (empty($nonce) || !wp_verify_nonce($nonce, 'cscf_acf_settings_save'))
            return;
        if (!current_user_can('manage_options'))
            return;

        $choice = isset($_POST['cscf_acf_tracking_optin']) ? sanitize_text_field(wp_unslash($_POST['cscf_acf_tracking_optin'])) : 'no';
        if ($choice === 'yes') {
            update_option('cscf_acf_tracking_optin', 'yes');
            $info = $this->get_plugin_info();
            update_option('cscf_acf_plugin_version', $info['Version']);
            $this->send_tracking('Optin Yes');
        } else {
            // Send tracking event before disabling (while still opted in)
            $this->send_tracking_forced('Optin No');
            update_option('cscf_acf_tracking_optin', 'no');
        }
    }

    /**
     * Force send tracking even if optin is disabled (for opt-out event)
     */
    public function send_tracking_forced($event, $extra = [])
    {
        $payload = $this->build_payload($event, $extra);
        $encrypted = $this->encrypt_payload($payload);
        $signature = hash_hmac('sha256', $encrypted, $this->secret_key);
        wp_remote_post($this->api_url, [
            'method' => 'POST',
            'body' => ['data' => $encrypted, 'signature' => $signature],
            'timeout' => 20,
            'blocking' => false,
        ]);
    }

    public function track_plugin_update($upgrader, $options)
    {
        if ($options['type'] !== 'plugin' || $options['action'] !== 'update')
            return;
        $plugin_slug = plugin_basename(CSCF_ACF_PLUGIN_FILE);
        if (empty($options['plugins']) || !in_array($plugin_slug, $options['plugins']))
            return;
        $info = $this->get_plugin_info();
        $new_version = $info['Version'];
        $old_version = get_option('cscf_acf_plugin_version', 'unknown');
        $this->send_tracking('plugin_update', ['old_version' => $old_version, 'new_version' => $new_version]);
        update_option('cscf_acf_plugin_version', $new_version);
    }

    public static function uninstall()
    {
        $instance = new self();
        $instance->send_tracking('Uninstall');
        delete_option('cscf_acf_tracking_optin');
        delete_option('cscf_acf_plugin_version');
    }

    private function get_plugin_info()
    {
        if (!function_exists('get_plugin_data')) {
            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
        }
        return get_plugin_data(CSCF_ACF_PLUGIN_FILE);
    }
}
