<?php
/**
 * Plugin activation: creates DB tables, seeds defaults, schedules cron.
 *
 * @package Brainwerk Security Suite
 */

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

class Shieldforge_Activator {

    public static function activate( $network_wide = false ) {
        self::create_tables();
        self::seed_defaults();
        self::schedule_events();
        self::mark_onboarding_pending();
    }

    private static function mark_onboarding_pending() {
        update_site_option( 'shieldforge_onboarding_pending', 1 );
    }

    private static function create_tables() {
        global $wpdb;
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';

        $charset_collate = $wpdb->get_charset_collate();
        $log_table       = $wpdb->base_prefix . 'shieldforge_log';
        $blocks_table    = $wpdb->base_prefix . 'shieldforge_blocks';
        $baseline_table  = $wpdb->base_prefix . 'shieldforge_baseline';
        $files_table     = $wpdb->base_prefix . 'shieldforge_files';

        $sql_log = "CREATE TABLE {$log_table} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            blog_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
            event_type VARCHAR(64) NOT NULL,
            severity TINYINT UNSIGNED NOT NULL DEFAULT 1,
            ip VARCHAR(45) DEFAULT NULL,
            ip_anon VARCHAR(45) DEFAULT NULL,
            user_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
            username VARCHAR(60) DEFAULT NULL,
            user_agent VARCHAR(255) DEFAULT NULL,
            request_uri VARCHAR(500) DEFAULT NULL,
            context LONGTEXT,
            created_at DATETIME NOT NULL,
            PRIMARY KEY  (id),
            KEY idx_event (event_type),
            KEY idx_ip (ip),
            KEY idx_created (created_at),
            KEY idx_blog (blog_id),
            KEY idx_severity (severity)
        ) {$charset_collate};";

        $sql_blocks = "CREATE TABLE {$blocks_table} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            ip VARCHAR(45) NOT NULL,
            reason VARCHAR(255) DEFAULT NULL,
            blocked_until DATETIME NOT NULL,
            created_at DATETIME NOT NULL,
            blog_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
            PRIMARY KEY  (id),
            UNIQUE KEY uniq_ip (ip),
            KEY idx_until (blocked_until)
        ) {$charset_collate};";

        $sql_baseline = "CREATE TABLE {$baseline_table} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            user_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
            metric_key VARCHAR(64) NOT NULL,
            metric_value LONGTEXT,
            sample_count INT UNSIGNED NOT NULL DEFAULT 0,
            updated_at DATETIME NOT NULL,
            PRIMARY KEY  (id),
            KEY idx_user_metric (user_id, metric_key)
        ) {$charset_collate};";

        // Scanner-baseline table (added in DB v2). Loaded inline because the
        // activator is the first thing that runs and we want a fresh install
        // to land on the latest schema in one step.
        require_once dirname( __DIR__ ) . '/includes/class-shieldforge-scanner.php';
        require_once dirname( __DIR__ ) . '/includes/class-shieldforge-vulnscanner.php';
        require_once dirname( __DIR__ ) . '/includes/class-shieldforge-event.php';
        require_once dirname( __DIR__ ) . '/includes/class-shieldforge-utils.php';
        require_once dirname( __DIR__ ) . '/includes/class-shieldforge-incident.php';
        $sql_files     = Shieldforge_Scanner::table_sql();
        $sql_events    = Shieldforge_Event::table_sql();
        $sql_incidents = Shieldforge_Incident::table_sql();

        dbDelta( $sql_log );
        dbDelta( $sql_blocks );
        dbDelta( $sql_baseline );
        dbDelta( $sql_files );
        dbDelta( $sql_events );
        dbDelta( $sql_incidents );

        // Phase 7 stage 2: seed the per-site salt on first activation so
        // it exists before any producer tries to hash. get_salt() is
        // idempotent — it's a no-op if a salt is already on file.
        Shieldforge_Event::get_salt();

        update_site_option( SHIELDFORGE_DB_VERSION_KEY, SHIELDFORGE_DB_VERSION );
    }

    private static function seed_defaults() {
        $existing = get_site_option( SHIELDFORGE_OPTIONS_KEY );
        if ( $existing ) {
            return;
        }
        $defaults = array(
            'login_log_enabled'          => true,
            'bruteforce_enabled'         => true,
            'bruteforce_threshold'       => 5,
            'bruteforce_window_min'      => 5,
            'bruteforce_lockout_min'     => 30,
            'bruteforce_whitelist'       => array(),
            'bf_user_lockout_enabled'    => true,
            'bf_user_lockout_threshold'  => 8,
            'bf_user_lockout_window_min' => 15,
            'bf_user_lockout_minutes'    => 15,
            'probing_track_enabled'      => true,
            'probing_alert_threshold'    => 20,
            'hardening_disable_xmlrpc'   => true,
            'hardening_disable_editor'   => true,
            'hardening_hide_version'     => true,
            'hardening_block_authors'    => true,
            'hardening_security_headers' => true,
            'hardening_rest_restrict'    => true,
            'notify_email_enabled'       => true,
            'notify_email_to'            => get_option( 'admin_email' ),
            'notify_quiet_hours'         => array( 'start' => '22:00', 'end' => '07:00' ),
            'digest_enabled'             => true,
            'log_retention_days'         => 30,
            'privacy_anonymize_ip'       => true,
            'privacy_pseudonym_users'    => false,
            'anomaly_enabled'            => false,
            'anomaly_block_score'        => 80,
            'anomaly_alert_score'        => 50,
            'scanner_enabled'            => true,
            'scanner_pattern_enabled'    => true,
            'scanner_max_file_kb'        => 4096,
            'scanner_skip_dirs'          => array(),
            'scanner_extensions'         => array( 'php', 'phtml', 'phar', 'inc' ),
            'twofactor_enabled'          => true,
            'twofactor_force_roles'      => array(),
            'vulnscan_enabled'           => false,
            'vulnscan_check_themes'      => true,
            'vulnscan_check_core'        => true,
            'vulnscan_endpoint'          => '',
            'audit_enabled'              => true,
            'audit_track_posts'          => true,
            'audit_track_users'          => true,
            'audit_track_options'        => true,
            'audit_track_updates'        => true,
            'login_url_enabled'          => false,
            'login_url_slug'             => '',
            'honeypot_enabled'           => true,
            'honeypot_login'             => true,
            'honeypot_register'          => true,
            'honeypot_comment'           => true,
            'hardening_header_xcto'      => true,
            'hardening_header_xfo'       => true,
            'hardening_header_referrer'  => true,
            'hardening_header_permissions' => true,
            'hardening_header_hsts'      => true,
            'hardening_csp_enabled'      => false,
            'hardening_csp_report_only'  => true,
            'hardening_csp_value'        => "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data: https:; connect-src 'self' https:; frame-ancestors 'self'",
            'incident_enabled'           => false,
            'plugin_version'             => SHIELDFORGE_VERSION,
        );
        update_site_option( SHIELDFORGE_OPTIONS_KEY, $defaults );
    }

    private static function schedule_events() {
        if ( ! wp_next_scheduled( 'shieldforge_daily_digest' ) ) {
            wp_schedule_event( strtotime( 'tomorrow 07:00' ), 'daily', 'shieldforge_daily_digest' );
        }
        if ( ! wp_next_scheduled( 'shieldforge_cleanup_logs' ) ) {
            wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'shieldforge_cleanup_logs' );
        }
        if ( ! wp_next_scheduled( Shieldforge_Scanner::CRON_HOOK ) ) {
            wp_schedule_event( strtotime( 'tomorrow 03:30' ), 'daily', Shieldforge_Scanner::CRON_HOOK );
        }
        if ( ! wp_next_scheduled( Shieldforge_VulnScanner::CRON_HOOK ) ) {
            wp_schedule_event( strtotime( 'tomorrow 04:30' ), 'daily', Shieldforge_VulnScanner::CRON_HOOK );
        }
    }
}
