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

$role = $_SESSION['user_role'];
$propertyId = $_SESSION['property_id'] ?? 0;

try {
    $stmt = $pdo->query("SELECT id, title, description, status, created_at as createdAt, questions_json FROM polls ORDER BY created_at DESC");
    $polls = $stmt->fetchAll();

    foreach ($polls as &$poll) {
        $poll['id'] = (int)$poll['id'];
        $poll['questions'] = json_decode($poll['questions_json']);
        unset($poll['questions_json']);

        // Recuperar respuestas con decodificaci¨Žn de JSON para que el conteo en Frontend funcione
        $resStmt = $pdo->prepare("SELECT property_id, answers_json FROM poll_responses WHERE poll_id = ?");
        $resStmt->execute([$poll['id']]);
        $responses = $resStmt->fetchAll();
        
        $processedResponses = [];
        foreach ($responses as $res) {
            $processedResponses[] = [
                "propertyId" => (int)$res['property_id'],
                "answers" => json_decode($res['answers_json'], true) ?: []
            ];
        }
        $poll['responses'] = $processedResponses;
    }
    response($polls);
} catch (PDOException $e) {
    response(["error" => "Error de comunicaci¨Žn con el motor de consultas"], 500);
}
?>