<?php
/**
 * VmpFence SIEM Settings Sync
 *
 * Pushes a complete settings snapshot to the Newton Security server
 * during each 5-minute sync cycle. The server stores this so the
 * SIEM website can display and modify settings remotely.
 *
 * All setting reads go through VMPFence_Config::get() which uses the
 * custom wp_vmpfence_config table with in-memory caching.
 *
 * @package    VMPFence
 * @subpackage Includes/Sync
 * @since      2.2.4
 * @since      2.2.6  Added new alert options and updated default boolean values
 */

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

class VmpFence_Sync_Settings {

    /**
     * Collect all settings and push to server.
     * Called from VmpFence_Sync_Manager::sync_all().
     *
     * @since 2.2.4
     * @return array Result with success flag
     */
    public static function sync(): array {
        $api_client = new VMPFence_API_Client();
        $site_uuid  = get_option(VMPFence_Constants::OPTION_SITE_UUID, '');
        $api_key    = VMPFence_Config::get('central_api_key', '');

        if (empty($site_uuid) || empty($api_key)) {
            return array('success' => false, 'error' => 'No UUID or API key');
        }

        $payload = array(
            'firewall_options'        => self::get_firewall_options(),
            'scan_options'            => self::get_scan_options(),
            'login_security'          => self::get_login_security(),
            'general_options'         => self::get_general_options(),
            'email_alerts'            => self::get_email_alerts(),
            'activity_report'         => self::get_activity_report(),
            'dashboard_notifications' => self::get_dashboard_notifications(),
            'all_settings'            => self::get_all_settings_flat(),
            'plugin_version'          => VMPFENCE_VERSION,
        );

        $result = $api_client->push_settings_sync($api_key, $site_uuid, $payload);

        $success = !is_wp_error($result);

        if ($success && class_exists('VMPFence_Secure_Logger')) {
            VMPFence_Secure_Logger::log('debug', 'SIEM settings sync pushed successfully');
        }

        return array('success' => $success);
    }

    // ========================================================================
    // Per-section getters — each returns a keyed array of current values
    // ========================================================================

    /**
     * Firewall & brute-force options.
     *
     * @since 2.2.4
     * @return array
     */
    private static function get_firewall_options(): array {
        return array(
            'waf_enabled'                     => VMPFence_Config::get('waf_enabled', false),
            'waf_protection_level'            => VMPFence_Config::get('waf_protection_level', 'standard'),
            'brute_force_enabled'             => VMPFence_Config::get('brute_force_enabled', false),
            'max_login_attempts'              => VMPFence_Config::get('max_login_attempts', 20),
            'max_forgot_password_attempts'    => VMPFence_Config::get('max_forgot_password_attempts', 20),
            'count_failures_window'           => VMPFence_Config::get('count_failures_window', 240),
            'lockout_duration'                => VMPFence_Config::get('lockout_duration', 240),
            'permanent_ban_threshold'         => VMPFence_Config::get('permanent_ban_threshold', 10),
            'lock_invalid_usernames'          => VMPFence_Config::get('lock_invalid_usernames', false),
            'prevent_leaked_passwords_enabled' => VMPFence_Config::get('prevent_leaked_passwords_enabled', false),
            'enforce_strong_passwords'        => VMPFence_Config::get('enforce_strong_passwords', false),
            'dont_reveal_users'               => VMPFence_Config::get('dont_reveal_users', false),
            'prevent_admin_username'           => VMPFence_Config::get('prevent_admin_username', false),
            'prevent_username_discovery'       => VMPFence_Config::get('prevent_username_discovery', false),
            'disable_app_passwords'            => VMPFence_Config::get('disable_app_passwords', false),
            'block_post_requests'             => VMPFence_Config::get('block_post_requests', false),
            'check_password_strength'         => VMPFence_Config::get('check_password_strength', false),
            'participate_security_network'    => VMPFence_Config::get('participate_security_network', false),
            'rate_limiting_enabled'           => VMPFence_Config::get('rate_limiting_enabled', false),
            'realtime_ip_blocklist_enabled'   => VMPFence_Config::get('realtime_ip_blocklist_enabled', false),
            'global_rate_limit'               => VMPFence_Config::get('global_rate_limit', 0),
            'global_rate_action'              => VMPFence_Config::get('global_rate_action', 'throttle'),
            'crawler_rate_limit'              => VMPFence_Config::get('crawler_rate_limit', 0),
            'crawler_rate_action'             => VMPFence_Config::get('crawler_rate_action', 'throttle'),
            'human_rate_limit'                => VMPFence_Config::get('human_rate_limit', 0),
            'human_rate_action'               => VMPFence_Config::get('human_rate_action', 'throttle'),
            'rate_block_duration'             => VMPFence_Config::get('rate_block_duration', 300),
            'trusted_proxies'                 => VMPFence_Config::get('trusted_proxies', ''),
            'trusted_proxy_preset'            => VMPFence_Config::get('trusted_proxy_preset', 'none'),
            'exclude_directories'             => VMPFence_Config::get('exclude_directories', ''),
            'whitelisted_ips_bypass'          => VMPFence_Config::get('whitelisted_ips_bypass', ''),
            'blocked_urls'                    => VMPFence_Config::get('blocked_urls', ''),
        );
    }

    /**
     * Scan schedule, performance, and enabled-check options.
     *
     * @since 2.2.4
     * @return array
     */
    private static function get_scan_options(): array {
        // Merge in any WP-option-level scan options blob
        $scan_opts = get_option('vmpfence_scan_options', array());
        if (!is_array($scan_opts)) {
            $scan_opts = array();
        }

        return array_merge(
            array(
                'scheduledScansEnabled'   => VMPFence_Config::get('scheduledScansEnabled', false),
                'schedMode'               => VMPFence_Config::get('schedMode', 'auto'),
                'schedPattern'            => VMPFence_Config::get('schedPattern', 'daily'),
                'lowResourceScansEnabled' => VMPFence_Config::get('lowResourceScansEnabled', false),
                'scan_maxIssues'          => VMPFence_Config::get('scan_maxIssues', 1000),
                'scan_maxDuration'        => VMPFence_Config::get('scan_maxDuration', 3600),
                'scan_exclude'            => VMPFence_Config::get('scan_exclude', ''),
            ),
            $scan_opts,
            array(
                // Scan-enabled toggles
                'scansEnabled_malware'              => VMPFence_Config::get('scansEnabled_malware', true),
                'scansEnabled_fileContents'         => VMPFence_Config::get('scansEnabled_fileContents', true),
                'scansEnabled_core'                 => VMPFence_Config::get('scansEnabled_core', true),
                'scansEnabled_plugins'              => VMPFence_Config::get('scansEnabled_plugins', true),
                'scansEnabled_themes'               => VMPFence_Config::get('scansEnabled_themes', true),
                'scansEnabled_coreUnknown'          => VMPFence_Config::get('scansEnabled_coreUnknown', true),
                'scansEnabled_posts'                => VMPFence_Config::get('scansEnabled_posts', true),
                'scansEnabled_comments'             => VMPFence_Config::get('scansEnabled_comments', true),
                'scansEnabled_suspiciousOptions'    => VMPFence_Config::get('scansEnabled_suspiciousOptions', true),
                'scansEnabled_oldVersions'          => VMPFence_Config::get('scansEnabled_oldVersions', true),
                'scansEnabled_suspiciousAdminUsers' => VMPFence_Config::get('scansEnabled_suspiciousAdminUsers', true),
                'scansEnabled_passwds'              => VMPFence_Config::get('scansEnabled_passwds', true),
                'scansEnabled_checkGSB'             => VMPFence_Config::get('scansEnabled_checkGSB', true),
                'spamvertizeCheck'                  => VMPFence_Config::get('spamvertizeCheck', true),
                'checkSpamIP'                       => VMPFence_Config::get('checkSpamIP', true),
                'scansEnabled_diskSpace'            => VMPFence_Config::get('scansEnabled_diskSpace', true),
                'scansEnabled_wafStatus'            => VMPFence_Config::get('scansEnabled_wafStatus', true),
                'scansEnabled_checkReadableConfig'  => VMPFence_Config::get('scansEnabled_checkReadableConfig', true),
                'whitelisted_services'              => VMPFence_Config::get('whitelisted_services', ''),
            )
        );
    }

    /**
     * Login security / 2FA options.
     *
     * @since 2.2.4
     * @return array
     */
    private static function get_login_security(): array {
        return array(
            'two_factor_enabled' => VMPFence_Config::get('two_factor_enabled', false),
        );
    }

    /**
     * General options (auto-update, UI toggles, etc.).
     *
     * @since 2.2.4
     * @return array
     */
    private static function get_general_options(): array {
        return array(
            'auto_update'                => VMPFence_Config::get('auto_update', false),
            'notification_email'         => VMPFence_Config::get('notification_email', ''),
            'ip_detection_method'        => VMPFence_Config::get('ip_detection_method', 'auto'),
            'hide_wp_version'            => VMPFence_Config::get('hide_wp_version', false),
            'pause_live_updates'         => VMPFence_Config::get('pause_live_updates', false),
            'update_interval'            => VMPFence_Config::get('update_interval', 2),
            'display_all_options_menu'   => VMPFence_Config::get('display_all_options_menu', true),
            'blocking_menu_display'      => VMPFence_Config::get('blocking_menu_display', true),
            'display_live_traffic_menu'  => VMPFence_Config::get('display_live_traffic_menu', true),
            'display_audit_log_menu'     => VMPFence_Config::get('display_audit_log_menu', true),
        );
    }

    /**
     * Email alert options.
     *
     * @since 2.2.4
     * @since 2.2.6  Added new alert options and updated default boolean values
     * @return array
     */
    private static function get_email_alerts(): array {
        return array(
            'alert_on_auto_update'         => VMPFence_Config::get('alert_on_auto_update', 0),
            'alert_on_deactivation'        => VMPFence_Config::get('alert_on_deactivation', 1),
            'alert_on_waf_disabled'        => VMPFence_Config::get('alert_on_waf_disabled', 1),
            'alert_on_scan_results'        => VMPFence_Config::get('alert_on_scan_results', 1),
            'alert_scan_severity'          => VMPFence_Config::get('alert_scan_severity', 'low'),
            'alert_on_ip_blocked'          => VMPFence_Config::get('alert_on_ip_blocked', 1),
            'alert_on_lockout'             => VMPFence_Config::get('alert_on_lockout', 1),
            'alert_on_breached_password'   => VMPFence_Config::get('alert_on_breached_password', 1),
            'alert_on_lost_password'       => VMPFence_Config::get('alert_on_lost_password', 1),
            'alert_on_admin_login'         => VMPFence_Config::get('alert_on_admin_login', 1),
            'alert_admin_login_new_device' => VMPFence_Config::get('alert_admin_login_new_device', 0),
            'alert_on_user_login'          => VMPFence_Config::get('alert_on_user_login', 0),
            'alert_user_login_new_device'  => VMPFence_Config::get('alert_user_login_new_device', 0),
            'alert_on_attack_increase'     => VMPFence_Config::get('alert_on_attack_increase', 1),
            'max_email_alerts_per_hour'    => VMPFence_Config::get('max_email_alerts_per_hour', 0),
        );
    }

    /**
     * Activity report / email summary options.
     *
     * @since 2.2.4
     * @since 2.2.6  Added new alert options and updated default boolean values

     * @return array
     */
    private static function get_activity_report(): array {
        return array(
            'enable_email_summary'     => VMPFence_Config::get('enable_email_summary', 1),
            'email_summary_frequency'  => VMPFence_Config::get('email_summary_frequency', 'weekly'),
            'enable_activity_widget'   => VMPFence_Config::get('enable_activity_widget', true),
        );
    }

    /**
     * Dashboard notification options.
     *
     * @since 2.2.4
     * @return array
     */
    private static function get_dashboard_notifications(): array {
        return array(
            'notify_updates_needed'  => VMPFence_Config::get('notify_updates_needed', true),
            'notify_scan_status'     => VMPFence_Config::get('notify_scan_status', true),
            'notify_security_alerts' => VMPFence_Config::get('notify_security_alerts', true),
            'notify_promotions'      => VMPFence_Config::get('notify_promotions', false),
        );
    }

    /**
     * Flat dump of ALL known VMPFence option keys.
     * Used as the single source of truth on the server.
     *
     * @since 2.2.4
     * @return array
     */
    private static function get_all_settings_flat(): array {
        return array_merge(
            self::get_firewall_options(),
            self::get_scan_options(),
            self::get_login_security(),
            self::get_general_options(),
            self::get_email_alerts(),
            self::get_activity_report(),
            self::get_dashboard_notifications()
        );
    }
}
