<?php
header('Content-Type: application/json');
require_once __DIR__ . '/db/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Invalid request method']);
    exit;
}

$token = $_POST['bot_token'] ?? '';
$vc_id = $_POST['voice_channel_id'] ?? '';
$time = $_POST['sahur_time'] ?? '';
$source = $_POST['sahur_source'] ?? '';

try {
    $db = db();
    $stmt = $db->prepare("UPDATE bot_settings SET setting_value = ? WHERE setting_key = ?");
    
    $stmt->execute([$token, 'bot_token']);
    $stmt->execute([$vc_id, 'voice_channel_id']);
    $stmt->execute([$time, 'sahur_time']);
    $stmt->execute([$source, 'sahur_source']);

    // Log the change
    $logStmt = $db->prepare("INSERT INTO bot_logs (log_level, message) VALUES ('info', 'Settings updated by administrator')");
    $logStmt->execute();

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
