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

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    echo json_encode(["success" => false, "error" => "Method not allowed"]);
    exit;
}

$input = json_decode(file_get_contents("php://input"), true);
$userName = $input["username"] ?? "";
$color = $input["color"] ?? "";

if (empty($userName) || !preg_match("/^#[a-fA-F0-9]{6}$/", $color)) {
    echo json_encode(["success" => false, "error" => "Invalid input"]);
    exit;
}

try {
    $pdo = db();
    // We only allow top 3 fans to change color, but we'll enforce that in the UI.
    // Here we just update it if they exist in user_likes.
    $stmt = $pdo->prepare("UPDATE user_likes SET custom_color = ? WHERE username = ?");
    $stmt->execute([$color, $userName]);

    if ($stmt->rowCount() > 0) {
        echo json_encode(["success" => true]);
    } else {
        echo json_encode(["success" => false, "error" => "User not found or color already set"]);
    }
} catch (PDOException $e) {
    echo json_encode(["success" => false, "error" => $e->getMessage()]);
}
