<?php
// ════════════════════════════════════════════════════════
// SYSTEM SETTINGS API
// Place in: Triangle_Tree_Life_Number/api/system/settings.php
// ════════════════════════════════════════════════════════

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once '../config/db.php';
require_once '../config/helpers.php';

// Get authorization token
$headers = getallheaders();
$token = isset($headers['Authorization']) ? str_replace('Bearer ', '', $headers['Authorization']) : null;

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized - No token provided']);
    exit();
}

// Verify token
$currentUser = verifyToken($token);
if (!$currentUser) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized - Invalid token']);
    exit();
}

$method = $_SERVER['REQUEST_METHOD'];

// ════════════════════════════════════════════════════════
// GET - Load all system settings
// ════════════════════════════════════════════════════════
if ($method === 'GET') {
    try {
        $stmt = $pdo->query("
            SELECT setting_key, setting_value, setting_type, description 
            FROM system_settings 
            ORDER BY setting_key
        ");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Convert to key-value object
        $settings = [];
        foreach ($rows as $row) {
            $value = $row['setting_value'];
            
            // Type conversion
            if ($row['setting_type'] === 'number') {
                $value = strpos($value, '.') !== false ? (float)$value : (int)$value;
            } elseif ($row['setting_type'] === 'boolean') {
                $value = $value === '1' || $value === 'true';
            } elseif ($row['setting_type'] === 'json') {
                $value = json_decode($value, true);
            }
            
            $settings[$row['setting_key']] = $value;
        }
        
        // Map DB keys back to frontend camelCase keys
        $mapped = [];
        $keyMap = [
            'lang_mode'         => 'langMode',
            'lang_primary'      => 'primaryLang',
            'lang_secondary'    => 'secondaryLang',
            'lang_tertiary'     => 'tertiaryLang',
            'jiazi_base_date'   => 'jiaziBaseDate',
            'app_font_size'     => 'fontSize',
            'app_desc_collapsed'   => 'descCollapsed',
            'app_show_sensitive'            => 'showSensitive',
            'app_energy_num_generator'      => 'energySection_numGenerator',
            'app_energy_letter_generator'   => 'energySection_letterGenerator',
            'app_energy_huajie'             => 'energySection_huajie',
            'app_energy_warnings'           => 'energySection_warnings',
            'dev_force_reload'              => 'devForceReload',
        ];
        foreach ($settings as $k => $v) {
            $frontendKey = $keyMap[$k] ?? $k;
            $mapped[$frontendKey] = $v;
        }
        // Rebuild abuse sub-object
        $abuse = [];
        $abuseMap = [
            'abuse_device_fingerprint' => 'deviceFingerprint',
            'abuse_ip_limit'           => 'ipLimit',
            'abuse_recaptcha'          => 'recaptcha',
            'abuse_email_domain'       => 'emailDomain',
            'abuse_trust_score'        => 'trustScore',
            'abuse_social_login'       => 'socialLogin',
            'abuse_email_otp'          => 'emailOtp',
            'abuse_device_max_reports' => 'deviceMaxReports',
            'abuse_ip_max_accounts'    => 'ipMaxAccounts',
            'abuse_recaptcha_site_key' => 'recaptchaSiteKey',
            'abuse_recaptcha_secret_key' => 'recaptchaSecretKey',
            'abuse_recaptcha_min_score'  => 'recaptchaMinScore',
            'abuse_trust_threshold'    => 'trustThreshold',
            'abuse_email_otp_expiry'   => 'emailOtpExpiry',
        ];
        foreach ($abuseMap as $dbKey => $jsKey) {
            if (isset($settings[$dbKey])) {
                $abuse[$jsKey] = $settings[$dbKey];
                unset($mapped[$dbKey]);
            }
        }
        if (!empty($abuse)) $mapped['abuse'] = $abuse;

        echo json_encode([
            'success' => true,
            'settings' => $mapped
        ]);
        exit();
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to load settings', 'details' => $e->getMessage()]);
        exit();
    }
}

// ════════════════════════════════════════════════════════
// POST - Save system settings (super_admin only)
// ════════════════════════════════════════════════════════
if ($method === 'POST') {
    // Only super_admin can save settings
    if ($currentUser['role'] !== 'super_admin') {
        http_response_code(403);
        echo json_encode(['error' => 'Forbidden - Super Admin access required']);
        exit();
    }
    
    $input = json_decode($GLOBALS['__RAW_BODY'] ?? file_get_contents('php://input'), true);
    
    if (!isset($input['settings'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Settings object required']);
        exit();
    }
    
    try {
        $settings = $input['settings'];
        
        // Prepare settings for database
        $settingsToSave = [];
        
        // Language settings
        if (isset($settings['langMode'])) {
            $settingsToSave['lang_mode'] = ['value' => $settings['langMode'], 'type' => 'string'];
        }
        if (isset($settings['primaryLang'])) {
            $settingsToSave['lang_primary'] = ['value' => $settings['primaryLang'], 'type' => 'string'];
        }
        if (isset($settings['secondaryLang'])) {
            $settingsToSave['lang_secondary'] = ['value' => $settings['secondaryLang'], 'type' => 'string'];
        }
        if (isset($settings['tertiaryLang'])) {
            $settingsToSave['lang_tertiary'] = ['value' => $settings['tertiaryLang'], 'type' => 'string'];
        }
        if (isset($settings['jiaziBaseDate'])) {
            $settingsToSave['jiazi_base_date'] = ['value' => $settings['jiaziBaseDate'], 'type' => 'string'];
        }

        // App display settings
        if (isset($settings['fontSize'])) {
            $settingsToSave['app_font_size'] = ['value' => (string)$settings['fontSize'], 'type' => 'number'];
        }
        if (isset($settings['descCollapsed'])) {
            $settingsToSave['app_desc_collapsed'] = ['value' => $settings['descCollapsed'] ? '1' : '0', 'type' => 'boolean'];
        }
        if (isset($settings['showSensitive'])) {
            $settingsToSave['app_show_sensitive'] = ['value' => $settings['showSensitive'] ? '1' : '0', 'type' => 'boolean'];
        }
        if (isset($settings['energySection_numGenerator'])) {
            $settingsToSave['app_energy_num_generator'] = ['value' => $settings['energySection_numGenerator'] ? '1' : '0', 'type' => 'boolean'];
        }
        if (isset($settings['energySection_letterGenerator'])) {
            $settingsToSave['app_energy_letter_generator'] = ['value' => $settings['energySection_letterGenerator'] ? '1' : '0', 'type' => 'boolean'];
        }
        if (isset($settings['energySection_huajie'])) {
            $settingsToSave['app_energy_huajie'] = ['value' => $settings['energySection_huajie'] ? '1' : '0', 'type' => 'boolean'];
        }
        if (isset($settings['energySection_warnings'])) {
            $settingsToSave['app_energy_warnings'] = ['value' => $settings['energySection_warnings'] ? '1' : '0', 'type' => 'boolean'];
        }
        if (isset($settings['devForceReload'])) {
            $settingsToSave['dev_force_reload'] = ['value' => $settings['devForceReload'] ? '1' : '0', 'type' => 'boolean'];
        }
        
        // Anti-abuse settings
        if (isset($settings['abuse'])) {
            $abuse = $settings['abuse'];
            
            // Boolean options
            $settingsToSave['abuse_device_fingerprint'] = ['value' => $abuse['deviceFingerprint'] ? '1' : '0', 'type' => 'boolean'];
            $settingsToSave['abuse_ip_limit'] = ['value' => $abuse['ipLimit'] ? '1' : '0', 'type' => 'boolean'];
            $settingsToSave['abuse_recaptcha'] = ['value' => $abuse['recaptcha'] ? '1' : '0', 'type' => 'boolean'];
            $settingsToSave['abuse_email_domain'] = ['value' => $abuse['emailDomain'] ? '1' : '0', 'type' => 'boolean'];
            $settingsToSave['abuse_trust_score'] = ['value' => $abuse['trustScore'] ? '1' : '0', 'type' => 'boolean'];
            $settingsToSave['abuse_social_login'] = ['value' => $abuse['socialLogin'] ? '1' : '0', 'type' => 'boolean'];
            $settingsToSave['abuse_email_otp'] = ['value' => $abuse['emailOtp'] ? '1' : '0', 'type' => 'boolean'];
            
            // Configuration values
            $settingsToSave['abuse_device_max_reports'] = ['value' => (string)$abuse['deviceMaxReports'], 'type' => 'number'];
            $settingsToSave['abuse_ip_max_accounts'] = ['value' => (string)$abuse['ipMaxAccounts'], 'type' => 'number'];
            $settingsToSave['abuse_recaptcha_site_key'] = ['value' => $abuse['recaptchaSiteKey'], 'type' => 'string'];
            $settingsToSave['abuse_recaptcha_secret_key'] = ['value' => $abuse['recaptchaSecretKey'], 'type' => 'string'];
            $settingsToSave['abuse_recaptcha_min_score'] = ['value' => (string)$abuse['recaptchaMinScore'], 'type' => 'number'];
            $settingsToSave['abuse_trust_threshold'] = ['value' => (string)$abuse['trustThreshold'], 'type' => 'number'];
            $settingsToSave['abuse_email_otp_expiry'] = ['value' => (string)$abuse['emailOtpExpiry'], 'type' => 'number'];
        }
        
        // Save all settings
        $pdo->beginTransaction();
        
        foreach ($settingsToSave as $key => $data) {
            $stmt = $pdo->prepare("
                INSERT INTO system_settings (setting_key, setting_value, setting_type, updated_by) 
                VALUES (?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE 
                    setting_value = VALUES(setting_value),
                    setting_type = VALUES(setting_type),
                    updated_by = VALUES(updated_by),
                    updated_at = CURRENT_TIMESTAMP
            ");
            $stmt->execute([$key, $data['value'], $data['type'], $currentUser['id']]);
        }
        
        $pdo->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Settings saved successfully',
            'updated_count' => count($settingsToSave)
        ]);
        exit();
        
    } catch (Exception $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode(['error' => 'Failed to save settings', 'details' => $e->getMessage()]);
        exit();
    }
}

http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
?>
