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

$pdo = db();
$username = $_POST["username"] ?? "";
$amount = intval($_POST["amount"] ?? 100);
$message = $_POST["message"] ?? "";

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

try {
    $pdo->beginTransaction();

    // Get current DJ
    $stmt = $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'current_dj'");
    $dj = $stmt->fetchColumn() ?: "Lili";

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

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

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

    // Log tip
    $stmt = $pdo->prepare("INSERT INTO dj_tips (sender_name, dj_name, amount, message) VALUES (?, ?, ?, ?)");
    $stmt->execute([$username, $dj, $amount, $message]);

    $pdo->commit();

    echo json_encode([
        "success" => true, 
        "message" => "¡Has enviado flores a $dj!",
        "dj" => $dj
    ]);

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