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

$pdo = db();
$data = json_decode(file_get_contents("php://input"), true);
$tipId = intval($data["tip_id"] ?? 0);

if (!$tipId) {
    echo json_encode(["success" => false, "error" => "ID de propina no válido"]);
    exit;
}

try {
    $stmt = $pdo->prepare("UPDATE dj_tips SET thanked_at = NOW() WHERE id = ?");
    $stmt->execute([$tipId]);

    // Award loyalty points to the sender
    $stmt = $pdo->prepare("SELECT sender_name FROM dj_tips WHERE id = ?");
    $stmt->execute([$tipId]);
    $sender = $stmt->fetchColumn();

    if ($sender) {
        $stmt = $pdo->prepare("UPDATE fans SET loyalty_points = loyalty_points + 50 WHERE name = ?");
        $stmt->execute([$sender]);
    }

    echo json_encode([
        "success" => true,
        "message" => "¡Has agradecido la donación!"
    ]);
} catch (Exception $e) {
    echo json_encode(["success" => false, "error" => $e->getMessage()]);
}
