<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Enqueues tracker.js and recorder.js on the frontend.
 */
class VLENS_Frontend_Scripts {

    public function __construct() {
        add_action( 'wp_enqueue_scripts', [ $this, 'enqueue' ] );
        add_action( 'after_setup_theme', [ $this, 'maybe_hide_admin_bar_for_replay' ] );
    }

    /**
     * Hides the admin bar (and any plugin toolbars docked to it, e.g. Rank
     * Math/Customize/host branding) inside the session-replay iframe, so the
     * preview shows the page the recorded visitor actually saw rather than
     * the viewing admin's own logged-in chrome. Must run before `init` —
     * show_admin_bar() rejects calls made afterward.
     */
    public function maybe_hide_admin_bar_for_replay() {
        if ( isset( $_GET['vs_replay'] ) && sanitize_text_field( wp_unslash( $_GET['vs_replay'] ) ) === '1' ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            show_admin_bar( false );
        }
    }

    private function ver( $relative_path ) {
        $abs = VLENS_PLUGIN_DIR . $relative_path;
        return file_exists( $abs ) ? (string) filemtime( $abs ) : VLENS_VERSION;
    }

    public function enqueue() {
        // Don't load scripts inside the session replay iframe
        if ( isset( $_GET['vs_replay'] ) && sanitize_text_field( wp_unslash( $_GET['vs_replay'] ) ) === '1' ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            return;
        }

        // Don't load scripts if visitor should be excluded
        if ( VLENS_Helpers::should_exclude() ) {
            return;
        }

        $track_endpoint  = rest_url( 'vlens/v1/track' );
        $record_endpoint = rest_url( 'vlens/v1/record' );

        // Load privacy/consent settings once for both scripts
        $settings = VLENS_Settings::get_all();
        $gate_config = [
            'consent_required'    => (bool) $settings['consent_required'],
            'consent_mode'        => $settings['consent_mode'],
            'consent_cookie_name' => $settings['consent_cookie_name'],
            'exclude_urls'        => is_array( $settings['exclude_urls'] ) ? $settings['exclude_urls'] : [],
        ];

        // vsr-gate.js — shared consent + URL exclusion logic
        wp_enqueue_script(
            'vlens-gate',
            VLENS_PLUGIN_URL . 'assets/js/vsr-gate.js',
            [],
            $this->ver( 'assets/js/vsr-gate.js' ),
            true
        );
        wp_localize_script( 'vlens-gate', 'vlensGate', $gate_config );

        // Tracker.js — visitor statistics
        if ( get_option( 'vlens_tracking_enabled', '1' ) === '1' ) {
            wp_enqueue_script(
                'vlens-tracker',
                VLENS_PLUGIN_URL . 'assets/js/tracker.js',
                [ 'vlens-gate' ],
                $this->ver( 'assets/js/tracker.js' ),
                true
            );

            $tracker_config = [
                'endpoint' => $track_endpoint,
            ];
            // Premium can add tracker settings
            $tracker_config = apply_filters( 'vlens_tracker_config', $tracker_config );
            wp_localize_script( 'vlens-tracker', 'vlensTracker', $tracker_config );
        }

        // Recorder.js — session recording
        if ( get_option( 'vlens_recording_enabled', '1' ) === '1' ) {
            wp_enqueue_script(
                'vlens-recorder',
                VLENS_PLUGIN_URL . 'assets/js/recorder.js',
                [ 'vlens-gate' ],
                $this->ver( 'assets/js/recorder.js' ),
                true
            );

            // Recording save interval (seconds → ms), admin-configurable.
            // Clamp to the allowed range as a defensive floor/ceiling.
            $flush_seconds = (int) ( $settings['flush_interval'] ?? 10 );
            $flush_seconds = max( 6, min( 16, $flush_seconds ) );

            // Percentage of visitors to actually record (100 = everyone).
            // Sampled-out visitors still get tracker.js pageview stats — this
            // only skips the heavier, continuously-beaconing session recorder.
            $sampling_rate = (int) ( $settings['sampling_rate'] ?? 100 );
            $sampling_rate = max( 0, min( 100, $sampling_rate ) );

            $recorder_config = [
                'endpoint'      => $record_endpoint,
                'flush_ms'      => $flush_seconds * 1000,
                'sampling_rate' => $sampling_rate,
            ];
            // Premium can add recorder settings
            $recorder_config = apply_filters( 'vlens_recorder_config', $recorder_config );
            wp_localize_script( 'vlens-recorder', 'vlensRecorder', $recorder_config );

            // Premium can enqueue additional frontend scripts that depend on vlens-recorder
            do_action( 'vlens_enqueue_frontend_scripts' );
        }
    }
}
