<?php
namespace MetForm_Pro\Core\Analytics;
defined( 'ABSPATH' ) || exit;

class Base {

    use \MetForm_Pro\Traits\Singleton;

    public $api;
    private $analytics_enabled = false;

    public function __construct(){
        $this->set_default_analytics_option();
        $this->analytics_enabled = $this->is_analytics_enabled();

        if ( $this->analytics_enabled ) {
            self::load_data_classes();
            $this->api = new Api();
        }
    }

    /**
     * Enable analytics by default for Pro until the user explicitly disables it.
     *
     * @return void
     */
    private function set_default_analytics_option() {
        $settings = get_option( 'metform_option__settings', [] );
        $settings = is_array( $settings ) ? $settings : [];

        if ( isset( $settings['mf_enable_form_analytics'] ) ) {
            return;
        }

        $settings['mf_enable_form_analytics'] = '1';
        update_option( 'metform_option__settings', $settings );
    }

    /**
     * Check whether form analytics is enabled in plugin settings.
     *
     * @return bool
     */
    private function is_analytics_enabled() {
        $settings = get_option( 'metform_option__settings', [] );

        return ! empty( $settings['mf_enable_form_analytics'] );
    }

    /**
     * Load all data classes
     */
    private static function load_data_classes() {
        require_once __DIR__ . '/helpers/database.php';
        require_once __DIR__ . '/helpers/quiz-analytics.php';
    }

    public function init(){
        $this->analytics_enabled = $this->is_analytics_enabled();

        if ( ! $this->analytics_enabled ) {
            return;
        }

        add_action('wp_enqueue_scripts', [$this, 'register_frontend_tracking'], 10);
        // Only emit the tracking script when a MetForm is actually on the page. Elementor/shortcode
        // enqueue 'metform-app' at render time (during the body), so the decision is deferred to the footer.
        add_action('wp_footer', [$this, 'maybe_enqueue_frontend_tracking'], 5);
        add_action('metform_after_store_form_data', [$this, 'track_submission'], 10, 4);
        add_action('init', [$this, 'sync_cleanup_schedule'], 20);
        add_action('metform_analytics_auto_cleanup', [$this, 'run_scheduled_cleanup']);

        // Removed all analytics data when a MetForm form is permanently deleted.
        add_action('before_delete_post', [$this, 'on_form_deleted'], 10, 1);
    }

    /**
     * Align cron schedule with current analytics retention settings.
     */
    public function sync_cleanup_schedule() {
        $settings = get_option( 'metform_option__settings', [] );
        $enabled = ! empty( $settings['mf_enable_form_analytics'] );
        $range = isset( $settings['mf_analytics_delete_range'] ) ? sanitize_text_field( $settings['mf_analytics_delete_range'] ) : '6_months';

        $next = wp_next_scheduled( 'metform_analytics_auto_cleanup' );
        $scheduled_event = wp_get_scheduled_event( 'metform_analytics_auto_cleanup' );

        if ( ! $enabled || $range === 'keep_forever' ) {
            if ( $next ) {
                wp_unschedule_event( $next, 'metform_analytics_auto_cleanup' );
            }
            return;
        }

        if ( $next && $scheduled_event && $scheduled_event->schedule !== 'weekly' ) {
            wp_unschedule_event( $next, 'metform_analytics_auto_cleanup' );
            $next = false;
        }

        if ( ! $next ) {
            wp_schedule_event( time() + HOUR_IN_SECONDS, 'weekly', 'metform_analytics_auto_cleanup' );
        }
    }

    /**
     * Scheduled cleanup callback to enforce analytics data retention.
     */
    public function run_scheduled_cleanup() {
        Helpers\Database::cleanup_expired_data();
    }

    /**
     * Delete all analytics data for a MetForm form when it is permanently deleted.
     *
     * Triggered by the `before_delete_post` hook (permanent delete only — not trash).
     * Removes rows from: mf_analytics_logs, mf_analytics_countries,
     * mf_analytics_reffrearrs_log, and orphaned mf_analytics_referrers entries.
     *
     * @param int $post_id The ID of the post being deleted.
     */
    public function on_form_deleted( $post_id ) {
        if ( get_post_type( $post_id ) !== 'metform-form' ) {
            return;
        }

        Helpers\Database::delete_form_data( $post_id );
    }

    /**
     * Register the tracking script (and its localized data) on the frontend.
     *
     * Registration is unconditional, but the script is not enqueued here — it is only
     * enqueued in the footer when a MetForm is present on the page. See maybe_enqueue_frontend_tracking().
     */
    public function register_frontend_tracking() {
        $script_url = plugin_dir_url(__FILE__) . 'js/tracking.js';

        wp_register_script(
            'metform-analytics-tracking',
            $script_url,
            ['jquery'],
            \MetForm\Plugin::instance()->version(),
            true
        );

        // Pass REST API URL and nonce to tracking script for logging conversions with additional data (country/referrer)
        wp_localize_script('metform-analytics-tracking', 'metformAnalyticsTracking', [
            'restUrl'         => rest_url('metform-pro/v1/analytics'),
            'nonce'           => wp_create_nonce('wp_rest'),
            // Gate the third-party ipinfo.io country lookup so it can be disabled (privacy/GDPR).
            'countryDetection' => $this->is_country_detection_enabled() ? 1 : 0,
        ]);
    }

    /**
     * Enqueue the tracking script only when a MetForm is rendered on the current page.
     *
     * MetForm enqueues its core 'metform-app' handle whenever a form is output (Elementor widget
     * via script_depends, the [metform] shortcode, or the form CPT). Using that as the signal avoids
     * loading the tracker on pages that contain no form. Runs in the footer (before script printing
     * at wp_footer:20) so it sees enqueues made during body render.
     */
    public function maybe_enqueue_frontend_tracking() {
        if ( ! wp_script_is( 'metform-app', 'enqueued' ) ) {
            return;
        }

        wp_enqueue_script('metform-analytics-tracking');
    }

    /**
     * Whether visitor country detection (third-party ipinfo.io lookup) is enabled.
     *
     * Controlled by the `mf_analytics_country_detection` setting. Defaults to enabled
     * to preserve existing behaviour; site owners can disable it for privacy/GDPR.
     *
     * @return bool
     */
    private function is_country_detection_enabled() {
        $settings = get_option( 'metform_option__settings', [] );
        $settings = is_array( $settings ) ? $settings : [];

        // Default ON when the option has never been set.
        if ( ! isset( $settings['mf_analytics_country_detection'] ) ) {
            return true;
        }

        return ! empty( $settings['mf_analytics_country_detection'] );
    }

    /**
     * Track form submission (conversion)
     * Hooked to metform_after_store_form_data
     * Increments conversion count in database
     * Gets country and referrer from cookie (set during form view)
     * @param int $form_id Form ID
     * @param array $form_data Submitted form data
     * @param array $form_settings Form settings
     * @param array $attributes Form attributes
     */
    public function track_submission($form_id, $form_data, $form_settings, $attributes) {
        // Only track conversions for genuine MetForm forms.
        if ( get_post_type( (int) $form_id ) !== 'metform-form' ) {
            return;
        }

        // Get tracking data from cookie (set by tracking.js when form was viewed)
        $cookie_key = 'mf_analytics_' . $form_id;
        
        $tracking_data = [
            'country' => '',
            'referrer' => ''
        ];
        
        // Read country and referrer from cookie
        if (isset($_COOKIE[$cookie_key])) {
            $cookie_data = json_decode(stripslashes($_COOKIE[$cookie_key]), true);
            
            if (is_array($cookie_data)) {
                // Only use country/referrer if they have valid values
                $tracking_data['country'] = !empty($cookie_data['country']) ? sanitize_text_field($cookie_data['country']) : '';
                $tracking_data['referrer'] = !empty($cookie_data['referrer']) ? esc_url_raw($cookie_data['referrer']) : '';
            }
        }
        
        // Log conversion - updates conversion counts in database
        // Only updates country/referrer tables if valid data exists
        Helpers\Database::log_conversion($form_id, $tracking_data);
        
        // Clear cookie after conversion
        if (isset($_COOKIE[$cookie_key])) {
            setcookie($cookie_key, '', time() - 3600, '/');
        }
    }
}
