<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';
header('Content-Type: application/json; charset=utf-8');

$auth = new Auth();
if (!$auth->check() || !$auth->isSuperAdmin()) { jsonResponse(false, 'Unauthorized', [], 401); }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { jsonResponse(false, 'Invalid method.'); }

$csrf = new CSRF();
if (!$csrf->verify($_POST['csrf_token'] ?? '')) { jsonResponse(false, 'Invalid CSRF token.'); }

$db = Database::getInstance();
$settingsData = $_POST['settings'] ?? null;

if ($settingsData !== null) {
    if (is_string($settingsData)) {
        $settingsData = json_decode($settingsData, true);
    }
    if (!is_array($settingsData)) {
        jsonResponse(false, 'Invalid settings data.');
    }

    foreach ($settingsData as $key => $value) {
        $existing = $db->query("SELECT id, setting_type FROM system_settings WHERE setting_key = ?", [$key])->fetch();
        if ($existing) {
            $finalValue = $value;
            if ($existing['setting_type'] === 'boolean') {
                $finalValue = ($value === '1' || $value === 'true') ? '1' : '0';
            } elseif ($existing['setting_type'] === 'integer') {
                $finalValue = (int) $value;
            }
            $db->update('system_settings', ['setting_value' => $finalValue, 'updated_at' => date('Y-m-d H:i:s')], 'setting_key = ?', [$key]);
        } else {
            $db->insert('system_settings', [
                'setting_key' => $key,
                'setting_value' => $value,
                'setting_type' => 'text',
                'group_name' => trim($_POST['group'] ?? 'general'),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
        }
    }

    $activityLog = new ActivityLog();
    $activityLog->log($_SESSION['user_id'], null, 'settings', 'update', 'Updated system settings');
    jsonResponse(true, 'Settings saved successfully.');
}

jsonResponse(false, 'No settings data provided.');
