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

$data = json_decode(file_get_contents("php://input"));
$uid = $conn->real_escape_string($data->user_id);
$pid = (int)$data->project_id;

// 1. Verificar si ya le dio Like
$check = $conn->query("SELECT id FROM likes WHERE user_id = '$uid' AND project_id = $pid");

if ($check->num_rows > 0) {
    // Ya existe -> Quitar Like
    $conn->query("DELETE FROM likes WHERE user_id = '$uid' AND project_id = $pid");
    $status = "unliked";
} else {
    // No existe -> Poner Like
    $conn->query("INSERT INTO likes (user_id, project_id) VALUES ('$uid', $pid)");
    $status = "liked";

    // --- LÓGICA DE XP: Premiar al autor del molde ---
    // A. Buscamos quién es el dueño del proyecto
    $res_owner = $conn->query("SELECT user_id FROM projects WHERE id = $pid LIMIT 1");
    if ($row_owner = $res_owner->fetch_assoc()) {
        $owner_id = $row_owner['user_id'];
        
        // B. Si el que dio like no es el mismo dueño, le damos 10 XP
        if ($owner_id !== $uid) {
            $conn->query("UPDATE users SET xp = xp + 10 WHERE google_id = '$owner_id'");
        }
    }
}

// 2. Contar total de likes actualizados para devolverlo a la interfaz
$res = $conn->query("SELECT COUNT(*) as total FROM likes WHERE project_id = $pid");
$row = $res->fetch_assoc();

echo json_encode([
    "success" => true, 
    "status" => $status, 
    "total" => $row['total']
]);

$conn->close();
?>
