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

$pdo = db();
$action = $_POST["action"] ?? "";
$username = $_POST["username"] ?? "";
$value = $_POST["value"] ?? "";

if (!$username) {
    echo json_encode(["success" => false, "error" => "Inicia sesión para comprar"]);
    exit;
}

$perks = [
    "pinned_message" => ["cost" => 500, "duration" => 3600], // 1 hour
    "background" => ["cost" => 1000, "duration" => 1800],    // 30 mins
];

if (!isset($perks[$action])) {
    echo json_encode(["success" => false, "error" => "Producto no encontrado"]);
    exit;
}

$perk = $perks[$action];

try {
    $pdo->beginTransaction();

    // Check points
    $stmt = $pdo->prepare("SELECT points FROM fans WHERE name = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if (!$user || $user["points"] < $perk["cost"]) {
        echo json_encode(["success" => false, "error" => "No tienes suficientes puntos (" . $perk["cost"] . " requeridos)"]);
        $pdo->rollBack();
        exit;
    }

    // Deduct points
    $stmt = $pdo->prepare("UPDATE fans SET points = points - ? WHERE name = ?");
    $stmt->execute([$perk["cost"], $username]);

    // Activate perk
    $expires_at = date("Y-m-d H:i:s", time() + $perk["duration"]);
    $stmt = $pdo->prepare("INSERT INTO shop_perks (perk_type, perk_value, user_name, expires_at) VALUES (?, ?, ?, ?)");
    $stmt->execute([$action, $value, $username, $expires_at]);

    $pdo->commit();
    echo json_encode(["success" => true, "message" => "¡Compra exitosa! Perk activado."]);
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(["success" => false, "error" => $e->getMessage()]);
}
