<?php
require_once 'config.php';
if (!isset($_SESSION['user_id'])) response(["error" => "No autorizado"], 401);

$role = $_SESSION['user_role'];

try {
    // Limitamos a 10 para rendimiento, asumiendo que solo una asamblea está activa a la vez
    $stmt = $pdo->query("SELECT id, question, options_json, status, created_at as createdAt FROM live_votes ORDER BY id DESC LIMIT 10");
    $votes = $stmt->fetchAll();

    foreach ($votes as &$vote) {
        $vote['options'] = json_decode($vote['options_json']);
        unset($vote['options_json']);

        // Incluimos property_id para que el frontend pueda detectar si la unidad ya votó
        $resStmt = $pdo->prepare("SELECT property_id, option_id FROM live_vote_responses WHERE vote_id = ?");
        $resStmt->execute([$vote['id']]);
        $responses = $resStmt->fetchAll();
        
        foreach ($responses as &$r) {
            $r['propertyId'] = (int)$r['property_id'];
            $r['optionId'] = (int)$r['option_id'];
        }
        $vote['responses'] = $responses;
    }
    response($votes);
} catch (PDOException $e) {
    response(["error" => "Fallo al consultar sala de asamblea live"], 500);
}
?>