<?php
session_start();
require_once "../config.php";

if (!isset($_SESSION['user_id'])) {
    die(json_encode(["error" => "Not logged in"]));
}

$user = $_SESSION['user_id'];
$action = $_GET['action'] ?? '';

if ($action === "get") {
    $stmt = $conn->prepare("SELECT wallpaper, theme FROM user_settings WHERE user_id = ?");
    $stmt->bind_param("i", $user);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();

    echo json_encode($result ?: [
        "wallpaper" => "assets/wallpapers/default.jpg",
        "theme" => "default"
    ]);
    exit;
}

if ($action === "set") {
    $wallpaper = $_POST['wallpaper'] ?? "assets/wallpapers/default.jpg";
    $theme = $_POST['theme'] ?? "default";

    // Insert or update
    $stmt = $conn->prepare("
        INSERT INTO user_settings (user_id, wallpaper, theme)
        VALUES (?, ?, ?)
        ON DUPLICATE KEY UPDATE wallpaper = VALUES(wallpaper), theme = VALUES(theme)
    ");
    $stmt->bind_param("iss", $user, $wallpaper, $theme);
    $stmt->execute();

    echo json_encode(["success" => true]);
    exit;
}

echo json_encode(["error" => "Invalid request"]);