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

// Capturar datos
$data = json_decode(file_get_contents("php://input"));
$token = isset($data->token) ? $data->token : null;
$referredBy = isset($data->referredBy) ? (string)$data->referredBy : null;

if(!$token) { 
    echo json_encode(["success" => false, "msg" => "Token no recibido"]); 
    exit; 
}

// 1. Validar con Google usando cURL
$ch = curl_init("https://oauth2.googleapis.com/tokeninfo?id_token=" . $token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$payload = json_decode($response);

if (!isset($payload->sub)) {
    echo json_encode(["success" => false, "msg" => "Token inválido"]);
    exit;
}

$google_id = (string)$payload->sub; // Forzar a texto siempre
$email = $payload->email;
$name = $payload->name;
$picture_url = isset($payload->picture) ? $payload->picture : null; 

// 2. Verificar existencia
$stmt = $conn->prepare("SELECT name, credits, picture_url FROM users WHERE google_id = ?");
$stmt->bind_param("s", $google_id);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
    // USUARIO EXISTENTE
    $stmt->bind_result($db_name, $db_credits, $db_pic);
    $stmt->fetch();
    echo json_encode([
        "success" => true,
        "is_new" => false,
        "name" => $db_name,
        "credits" => $db_credits,
        "google_id" => $google_id,
        "picture" => $db_pic,
        "msg" => "Usuario ya registrado"
    ]);
} else {
    // USUARIO NUEVO
    $stmt->close();
    
    $ins = $conn->prepare("INSERT INTO users (google_id, email, name, credits, picture_url) VALUES (?, ?, ?, 10, ?)");
    $ins->bind_param("ssss", $google_id, $email, $name, $picture_url);
    
    if ($ins->execute()) {
        $ref_status = "Sin invitación detectada";

        // LÓGICA DE REFERIDOS CON COMPARACIÓN ESTRICTA (===)
        // Usamos !== para evitar que PHP los compare como números y pierda precisión
        if ($referredBy && $referredBy !== $google_id) {
            
            // Verificar si el que invitó existe
            $check = $conn->prepare("SELECT credits FROM users WHERE google_id = ?");
            $check->bind_param("s", $referredBy);
            $check->execute();
            $check->store_result();
            
            if ($check->num_rows > 0) {
                // Sumar créditos
                $upd = $conn->prepare("UPDATE users SET credits = credits + 5 WHERE google_id = ?");
                $upd->bind_param("s", $referredBy);
                if($upd->execute()) {
                    $ref_status = "¡ÉXITO! +5 créditos al invitador: " . $referredBy;
                } else {
                    $ref_status = "Error al actualizar invitador";
                }
            } else {
                $ref_status = "El invitador con ID $referredBy no existe en la base de datos";
            }
        } elseif ($referredBy === $google_id) {
            $ref_status = "Auto-invitación bloqueada";
        }

        echo json_encode([
            "success" => true,
            "is_new" => true,
            "name" => $name,
            "credits" => 10,
            "google_id" => $google_id,
            "picture" => $picture_url,
            "referral_info" => $ref_status
        ]);
    } else {
        echo json_encode(["success" => false, "msg" => "Error al crear usuario"]);
    }
}
$conn->close();
?>
