<?php
include 'db.php';

$id = intval($_POST['id'] ?? 0);
$code = $_POST['code'] ?? '';
$value = ($_POST['value'] ?? '') === '1' ? '1' : ($_POST['value'] ?? '');

// Validate timezone if it's a timezone setting
if ($code === 'system_timezone') {
    if (!in_array($value, DateTimeZone::listIdentifiers())) {
        http_response_code(400);
        echo "Invalid timezone: $value";
        exit;
    }
}

if ($id > 0) {
    // Update by ID
    $stmt = $conn->prepare("UPDATE settings SET value = ? WHERE id = ?");
    if (!$stmt) {
        echo "Prepare failed: " . $conn->error;
        exit;
    }
    $stmt->bind_param("si", $value, $id);
    if ($stmt->execute()) {
        echo "success";
    } else {
        echo "Execute failed: " . $stmt->error;
    }
    $stmt->close();
} elseif ($code) {
    // Update by code
    $stmt = $conn->prepare("UPDATE settings SET value = ? WHERE code = ?");
    if (!$stmt) {
        echo "Prepare failed: " . $conn->error;
        exit;
    }
    $stmt->bind_param("ss", $value, $code);
    if ($stmt->execute()) {
        echo "success";
    } else {
        echo "Execute failed: " . $stmt->error;
    }
    $stmt->close();
} else {
    http_response_code(400);
    echo "Invalid parameters: id=$id, code=$code, value=$value";
}
