<?php
require_once 'auth/session.php';
header('Content-Type: application/json');

// Detailed log
$log = [
    'date' => date('Y-m-d H:i:s'),
    'method' => $_SERVER['REQUEST_METHOD'],
    'post' => $_POST,
    'session' => $_SESSION
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user = getCurrentUser();
    if (!$user) {
        $log['error'] = 'Unauthorized';
        file_put_contents('requests.log', json_encode($log) . "\n", FILE_APPEND);
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
        exit;
    }

    $log['user_id'] = $user['id'];

    $username = !empty($_POST['username']) ? $_POST['username'] : $user['username'];
    $avatar_url = isset($_POST['avatar_url']) ? $_POST['avatar_url'] : $user['avatar_url'];
    $dnd_mode = isset($_POST['dnd_mode']) ? (int)$_POST['dnd_mode'] : 0;
    $sound_notifications = isset($_POST['sound_notifications']) ? (int)$_POST['sound_notifications'] : 0;
    $theme = !empty($_POST['theme']) ? $_POST['theme'] : $user['theme'];

    try {
        $stmt = db()->prepare("UPDATE users SET username = ?, avatar_url = ?, dnd_mode = ?, sound_notifications = ?, theme = ? WHERE id = ?");
        $success = $stmt->execute([$username, $avatar_url, $dnd_mode, $sound_notifications, $theme, $user['id']]);
        
        $log['db_success'] = $success;
        file_put_contents('requests.log', json_encode($log) . "\n", FILE_APPEND);
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        $log['db_error'] = $e->getMessage();
        file_put_contents('requests.log', json_encode($log) . "\n", FILE_APPEND);
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

echo json_encode(['success' => false, 'error' => 'Invalid request']);
