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

/**
 * Main plugin orchestrator — singleton.
 */
class VLENS_Plugin {

    private static $instance = null;

    public static function instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        // GDPR / privacy compliance
        new VLENS_Privacy();

        // Frontend: enqueue tracker.js + recorder.js
        new VLENS_Frontend_Scripts();

        // REST API endpoints
        add_action( 'rest_api_init', [ $this, 'register_rest_routes' ] );

        // Allow public tracking endpoints to work without a WP nonce.
        // WordPress cookie auth rejects requests that carry auth cookies but no nonce —
        // this happens when the plugin is embedded on a root domain (e.g. myrecorp.com)
        // while WordPress lives in a subdirectory (/wp). Returning null here tells the
        // REST server "no authentication result yet" so it falls through to the
        // permission_callback (which is __return_true for these endpoints).
        add_filter( 'rest_authentication_errors', [ $this, 'allow_public_tracking_endpoints' ], 200 );

        // DB incremental upgrades
        add_action( 'admin_init', [ 'VLENS_Activator', 'maybe_upgrade' ] );

        // Cron: daily cleanup
        VLENS_Cron::init();
        VLENS_Cron::schedule();

        // Admin area
        if ( is_admin() ) {
            new VLENS_Admin_Menu();
            new VLENS_Admin_Assets();
        }
    }

    /**
     * Bypass cookie-nonce authentication for the public tracking endpoints.
     * Returns null (not an error) so WordPress continues to the permission_callback.
     *
     * @param WP_Error|null|true $result Current auth result.
     * @return WP_Error|null|true
     */
    public function allow_public_tracking_endpoints( $result ) {
        // Only intercept when cookie auth has already flagged an error.
        if ( ! is_wp_error( $result ) ) {
            return $result;
        }

        $uri = $_SERVER['REQUEST_URI'] ?? '';

        if ( str_contains( $uri, '/vlens/v1/track' ) || str_contains( $uri, '/vlens/v1/record' ) ) {
            return null; // Clear the error — let permission_callback decide.
        }

        return $result;
    }

    /**
     * Register all REST API routes.
     */
    public function register_rest_routes() {
        ( new VLENS_REST_Track() )->register_routes();
        ( new VLENS_REST_Record() )->register_routes();
        ( new VLENS_REST_Replay() )->register_routes();
        ( new VLENS_REST_Stats() )->register_routes();
        ( new VLENS_REST_Settings() )->register_routes();

        // Premium can register additional REST endpoints
        do_action( 'vlens_register_rest_routes' );
    }
}
