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

/**
 * Manages plugin settings (read/write from options + config table).
 */
class VLENS_Settings {

    /**
     * Get all settings as an associative array.
     */
    public static function get_all(): array {
        global $wpdb;
        $config_table = VLENS_Helpers::table( 'recording_config' );
        $config = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE id = 1", $config_table ), ARRAY_A );

        return [
            'tracking_enabled'     => get_option( 'vlens_tracking_enabled', '1' ),
            'recording_enabled'    => get_option( 'vlens_recording_enabled', '1' ),
            'geoip_enabled'        => get_option( 'vlens_geoip_enabled', '0' ),
            'dashboard_theme'      => get_option( 'vlens_dashboard_theme', 'light' ),
            'flush_interval'       => (int) get_option( 'vlens_flush_interval', 10 ),
            'sampling_rate'        => (int) ( $config['sampling_rate'] ?? 100 ),
            'session_limit'        => (int) ( $config['session_limit'] ?? 500 ),
            'retention_days'       => (int) ( $config['retention_days'] ?? 7 ),
            'exclude_urls'         => $config['exclude_urls'] ? json_decode( $config['exclude_urls'], true ) : [],
            'exclude_ips'          => $config['exclude_ips'] ? json_decode( $config['exclude_ips'], true ) : [],
            'exclude_roles'        => $config['exclude_roles'] ? json_decode( $config['exclude_roles'], true ) : [],
            'exclude_bots'         => (bool) ( $config['exclude_bots'] ?? true ),
            'exclude_wp_admin'     => (bool) ( $config['exclude_wp_admin'] ?? true ),
            'exclude_logged_admins'=> (bool) ( $config['exclude_logged_admins'] ?? true ),
            'respect_dnt'          => (bool) ( $config['respect_dnt'] ?? false ),
            'mask_inputs'          => (bool) ( $config['mask_inputs'] ?? true ),
            'skip_idle'            => (bool) ( $config['skip_idle'] ?? true ),
            'consent_required'     => (bool) ( $config['consent_required'] ?? false ),
            'consent_mode'         => $config['consent_mode'] ?? 'none',
            'consent_cookie_name'  => $config['consent_cookie_name'] ?? '',
            'last_cleanup'         => get_option( 'vlens_last_cleanup', '' ),
        ];
    }

    /**
     * Update settings from a key-value array.
     */
    public static function update( array $data ): bool {
        global $wpdb;
        $config_table = VLENS_Helpers::table( 'recording_config' );

        // WP options
        $option_keys = [ 'tracking_enabled', 'recording_enabled', 'geoip_enabled' ];
        foreach ( $option_keys as $key ) {
            if ( isset( $data[ $key ] ) ) {
                update_option( 'vlens_' . $key, sanitize_text_field( $data[ $key ] ) );
            }
        }

        // Statistics dashboard theme. Constrained to the two choices offered in
        // the UI so a tampered request can't inject an arbitrary attribute value.
        if ( isset( $data['dashboard_theme'] ) ) {
            $theme = $data['dashboard_theme'] === 'dark' ? 'dark' : 'light';
            update_option( 'vlens_dashboard_theme', $theme );
        }

        // Recording flush interval (seconds) — how often the recorder beacons a
        // batch to the server. Constrained to the choices offered in the UI so a
        // tampered request can't set an abusive value; falls back to 10s.
        if ( isset( $data['flush_interval'] ) ) {
            $allowed_flush = [ 6, 8, 10, 12, 14, 16 ];
            $flush         = absint( $data['flush_interval'] );
            if ( ! in_array( $flush, $allowed_flush, true ) ) {
                $flush = 10;
            }
            update_option( 'vlens_flush_interval', $flush );
        }

        // Config table fields
        $config_data = [];
        $int_fields  = [ 'sampling_rate', 'session_limit', 'retention_days' ];
        $bool_fields = [ 'exclude_bots', 'exclude_wp_admin', 'exclude_logged_admins', 'respect_dnt', 'mask_inputs', 'skip_idle', 'consent_required' ];
        $json_fields = [ 'exclude_urls', 'exclude_ips', 'exclude_roles' ];
        $str_fields  = [ 'consent_mode', 'consent_cookie_name' ];

        foreach ( $int_fields as $f ) {
            if ( isset( $data[ $f ] ) ) {
                $config_data[ $f ] = absint( $data[ $f ] );
            }
        }

        foreach ( $bool_fields as $f ) {
            if ( isset( $data[ $f ] ) ) {
                $config_data[ $f ] = $data[ $f ] ? 1 : 0;
            }
        }

        foreach ( $str_fields as $f ) {
            if ( isset( $data[ $f ] ) ) {
                $config_data[ $f ] = sanitize_text_field( $data[ $f ] );
            }
        }

        foreach ( $json_fields as $f ) {
            if ( isset( $data[ $f ] ) ) {
                $arr = is_array( $data[ $f ] ) ? $data[ $f ] : [];
                $config_data[ $f ] = wp_json_encode( array_map( 'sanitize_text_field', $arr ) );
            }
        }

        if ( ! empty( $config_data ) ) {
            $config_data['updated_at'] = current_time( 'mysql' );
            $wpdb->update( $config_table, $config_data, [ 'id' => 1 ] );
        }

        return true;
    }
}
