<?php
header('Content-Type: application/json');
require 'db_connect.php';

$data = json_decode(file_get_contents("php://input"));
$uid = $data->google_id;

if(!$uid) { echo json_encode(["success"=>false, "msg"=>"No ID"]); exit; }

// 1. Verificar saldo actual
$sql = "SELECT credits FROM users WHERE google_id = '$uid'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $current_credits = intval($row['credits']);

    if ($current_credits > 0) {
        // 2. Tiene saldo, RESTAMOS 1
        $new_balance = $current_credits - 1;
        $update = "UPDATE users SET credits = $new_balance WHERE google_id = '$uid'";
        
        if ($conn->query($update) === TRUE) {
            echo json_encode(["success"=>true, "new_credits"=>$new_balance]);
        } else {
            echo json_encode(["success"=>false, "msg"=>"Error DB"]);
        }
    } else {
        // 3. No tiene saldo
        echo json_encode(["success"=>false, "msg"=>"sin_saldo"]);
    }
} else {
    echo json_encode(["success"=>false, "msg"=>"Usuario no encontrado"]);
}
$conn->close();
?>
