<?php
defined( 'ABSPATH' ) || exit;

class SITECL_Loader {

    public static function init(): void {
        self::load_dependencies();

        add_action( 'rest_api_init', [ 'SITECL_REST_Controller', 'register_routes' ] );

        // Public token-based URL handlers (no login required, token-authenticated).
        add_action( 'init', [ __CLASS__, 'handle_email_rollback' ] );
        add_action( 'init', [ __CLASS__, 'handle_guardian_fix' ] );

        add_action( 'sitecl_scheduled_scan',    [ __CLASS__, 'run_scheduled_scan' ] );
        add_action( 'sitecl_scheduled_email',   [ __CLASS__, 'run_scheduled_email' ] );
        add_action( 'sitecl_activation_scan',   [ __CLASS__, 'run_activation_scan' ] );
        add_action( 'sitecl_guardian_check',    [ __CLASS__, 'run_guardian_check' ] );

        // Register the every-minute cron interval.
        add_filter( 'cron_schedules', [ __CLASS__, 'add_every_minute_schedule' ] );

        // Plugin backup — hooks into WordPress upgrader to back up before updates.
        SITECL_Plugin_Backup::init();

        if ( is_admin() ) {
            new SITECL_Admin_Menu();
        }
    }

    public static function activate(): void {
        require_once SITECL_PLUGIN_DIR . 'includes/class-db-tables.php';
        SITECL_DB_Tables::create();
        add_option( 'sitecl_db_version', SITECL_VERSION );

        // Run an initial scan + snapshot on first activation so AI Chat has context immediately.
        if ( ! wp_next_scheduled( 'sitecl_activation_scan' ) ) {
            wp_schedule_single_event( time() + 10, 'sitecl_activation_scan' );
        }
    }

    public static function deactivate(): void {
        wp_clear_scheduled_hook( 'sitecl_scheduled_scan' );
        wp_clear_scheduled_hook( 'sitecl_scheduled_email' );
        wp_clear_scheduled_hook( 'sitecl_activation_scan' );
        wp_clear_scheduled_hook( 'sitecl_guardian_check' );
    }

    public static function add_every_minute_schedule( array $schedules ): array {
        if ( ! isset( $schedules['every_minute'] ) ) {
            $schedules['every_minute'] = [
                'interval' => 60,
                'display'  => __( 'Every Minute', 'site-cliniq' ),
            ];
        }
        return $schedules;
    }

    public static function run_guardian_check(): void {
        if ( class_exists( 'SITECL_Guardian' ) ) {
            SITECL_Guardian::check();
        }
    }

    public static function handle_guardian_fix(): void {
        if ( empty( $_GET['sitecl_guardian_fix'] ) ) {
            return;
        }

        // Permission check — admin login required.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have permission to perform this action.', 'site-cliniq' ), '', [ 'response' => 403 ] );
        }

        // Nonce verification — validates the request origin.
        $nonce = isset( $_GET['_wpnonce'] ) ? sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ) : '';
        if ( ! wp_verify_nonce( $nonce, 'sitecl_guardian_fix_action' ) ) {
            wp_die( esc_html__( 'Security check failed. This link may have expired — please use the dashboard to manage fixes.', 'site-cliniq' ) );
        }

        if ( empty( $_GET['token'] ) || ! class_exists( 'SITECL_Guardian' ) ) {
            return;
        }

        $token  = sanitize_text_field( wp_unslash( $_GET['token'] ) );
        $result = SITECL_Guardian::fix_via_token( $token );

        $message = $result['success']
            ? urlencode( '✅ Fix applied successfully — your site has been restored.' )
            : urlencode( '❌ Fix failed: ' . $result['message'] );

        $status = $result['success'] ? 'success' : 'error';

        wp_safe_redirect( admin_url( 'admin.php?page=sitecl&tab=auto-fix&sitecl_rb=' . $status . '&sitecl_msg=' . $message ) );
        exit;
    }

    public static function run_scheduled_scan(): void {
        // Full scan + snapshot so AI Chat history grows with every scheduled run.
        SITECL_Scanner::run_full_scan();
        if ( class_exists( 'SITECL_Site_Snapshot' ) ) {
            SITECL_Site_Snapshot::take();
        }
    }

    public static function run_scheduled_email(): void {
        SITECL_Email_Report::send_now();
    }

    public static function handle_email_rollback(): void {
        if ( empty( $_GET['sitecl_rollback'] ) ) {
            return;
        }

        // Permission check — admin login required.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have permission to perform this action.', 'site-cliniq' ), '', [ 'response' => 403 ] );
        }

        // Nonce verification — validates the request origin.
        $nonce = isset( $_GET['_wpnonce'] ) ? sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ) : '';
        if ( ! wp_verify_nonce( $nonce, 'sitecl_email_rollback' ) ) {
            wp_die( esc_html__( 'Security check failed. This link may have expired — please use the dashboard to manage rollbacks.', 'site-cliniq' ) );
        }

        if ( empty( $_GET['token'] ) || ! class_exists( 'SITECL_Auto_Fix' ) ) {
            return;
        }

        $token  = sanitize_text_field( wp_unslash( $_GET['token'] ) );
        $result = SITECL_Auto_Fix::rollback_via_token( $token );

        $message = $result['success']
            ? urlencode( '✅ Rollback successful — your site has been restored.' )
            : urlencode( '❌ Rollback failed: ' . $result['message'] );

        $status = $result['success'] ? 'success' : 'error';

        wp_safe_redirect( admin_url( 'admin.php?page=sitecl&tab=auto-fix&sitecl_rb=' . $status . '&sitecl_msg=' . $message ) );
        exit;
    }

    public static function run_activation_scan(): void {
        SITECL_Scanner::run_full_scan();
        if ( class_exists( 'SITECL_Site_Snapshot' ) ) {
            SITECL_Site_Snapshot::take();
        }
    }

    private static function load_dependencies(): void {
        $includes = [
            'class-db-tables.php',
            'class-error-log.php',
            'class-plugin-backup.php',
            'class-ai-diagnosis.php',
            'class-scanner.php',
            'class-error-reader.php',
            'class-health-score.php',
            'class-plugin-cve.php',
            'class-plugin-bloat.php',
            'class-update-risk.php',
            'class-image-audit.php',
            'class-alt-scanner.php',
            'class-seo-checker.php',
            'class-broken-links.php',
            'class-email-report.php',
            'class-rest-controller.php',
        ];

        foreach ( $includes as $file ) {
            require_once SITECL_PLUGIN_DIR . "includes/{$file}";
        }

        require_once SITECL_PLUGIN_DIR . 'admin/class-admin-menu.php';

        // PRO classes — only loaded when the pro/ folder exists (PRO version).
        if ( is_dir( SITECL_PLUGIN_DIR . 'pro' ) ) {
            $pro_files = [
                'class-site-snapshot.php',
                'class-alt-generator.php',
                'class-redirect-manager.php',
                'class-seo-ai.php',
                'class-performance.php',
                'class-auto-fix.php',
                'class-guardian.php',
                'class-predictive.php',
                'class-scheduled-scan.php',
                'class-ai-chat.php',
            ];

            foreach ( $pro_files as $file ) {
                require_once SITECL_PLUGIN_DIR . "pro/{$file}";
            }

            // Register redirect hook (PRO only).
            SITECL_Redirect_Manager::register_hooks();
        }
    }
}
