<?php
session_start();

if (!isset($_SESSION['user'])) {
    http_response_code(401);
    echo json_encode(['error' => 'No autorizado']);
    exit;
}

require '../src/db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['post_id'])) {
    $postId = (int)$_POST['post_id'];
    $userId = $_SESSION['user']['id'];
    
    try {
        // Verificar si el usuario ya dio like a esta publicación
        $stmt = $pdo->prepare("SELECT id FROM likes_post WHERE post_id = ? AND usuario_id = ?");
        $stmt->execute([$postId, $userId]);
        $existingLike = $stmt->fetch();
        
        if ($existingLike) {
            // Si ya existe el like, lo removemos (unlike)
            $stmt = $pdo->prepare("DELETE FROM likes_post WHERE post_id = ? AND usuario_id = ?");
            $stmt->execute([$postId, $userId]);
            
            // Decrementar contador de likes en la publicación
            $stmt = $pdo->prepare("UPDATE publicaciones SET likes = GREATEST(0, likes - 1) WHERE id = ?");
            $stmt->execute([$postId]);
            
            $action = 'unliked';
        } else {
            // Agregar like
            $stmt = $pdo->prepare("INSERT INTO likes_post (post_id, usuario_id, fecha) VALUES (?, ?, NOW())");
            $stmt->execute([$postId, $userId]);
            
            // Incrementar contador de likes en la publicación
            $stmt = $pdo->prepare("UPDATE publicaciones SET likes = COALESCE(likes, 0) + 1 WHERE id = ?");
            $stmt->execute([$postId]);
            
            $action = 'liked';
        }
        
        // Obtener el nuevo contador de likes
        $stmt = $pdo->prepare("SELECT COALESCE(likes, 0) as likes FROM publicaciones WHERE id = ?");
        $stmt->execute([$postId]);
        $newLikes = $stmt->fetchColumn();
        
        echo json_encode([
            'success' => true, 
            'action' => $action,
            'likes' => $newLikes
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Error interno del servidor']);
    }
} else {
    http_response_code(400);
    echo json_encode(['error' => 'Datos inválidos']);
}
?>