<?php
// Limpiar cualquier output previo
if (ob_get_length()) ob_clean();
require_once 'config.php';

if (!isset($_SESSION['user_id'])) response(["error" => "No autorizado"], 401);

$role = strtolower($_SESSION['user_role']);
$propertyId = $_SESSION['property_id'] ?? 0;
// Soporte expl¨ªcito para board, admin y programmer
$isAdmin = in_array($role, ['admin', 'programmer', 'board']);

try {
    $stmt = $pdo->query("SELECT * FROM data_forms ORDER BY created_at DESC");
    $forms = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($forms as &$form) {
        $form['id'] = (int)$form['id'];
        $form['fields'] = json_decode($form['fields_json'] ?? '[]', true) ?: [];
        unset($form['fields_json']);

        // Recuperar respuestas con l¨®gica de privacidad
        if ($isAdmin) {
            $resStmt = $pdo->prepare("SELECT property_id, user_id, data_json, submitted_at FROM data_form_responses WHERE form_id = ?");
            $resStmt->execute([$form['id']]);
        } else {
            $resStmt = $pdo->prepare("SELECT property_id, user_id, data_json, submitted_at FROM data_form_responses WHERE form_id = ? AND property_id = ?");
            $resStmt->execute([$form['id'], $propertyId]);
        }
        
        $responses = $resStmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($responses as &$r) {
            $r['propertyId'] = (int)$r['property_id'];
            $r['userId'] = (int)$r['user_id'];
            $r['submittedAt'] = $r['submitted_at'];
            
            if ($isAdmin || $r['propertyId'] == $propertyId) {
                $decoded = json_decode($r['data_json'] ?? '{}', true) ?: [];
                
                /**
                 * NORMALIZADOR INTELIGENTE
                 * Si la data_json contiene un campo 'data', significa que es un registro antiguo anidado.
                 * Lo aplanamos para que el frontend siempre reciba el mapa directo f1, f2, etc.
                 */
                if (isset($decoded['data']) && is_array($decoded['data'])) {
                    $r['data'] = $decoded['data'];
                } else {
                    $r['data'] = $decoded;
                }
            } else {
                $r['data'] = (object)[]; 
            }
            unset($r['data_json'], $r['property_id'], $r['user_id'], $r['submitted_at']);
        }
        $form['responses'] = $responses;
    }

    response($forms);
} catch (PDOException $e) {
    response(["error" => "Database Error", "details" => $e->getMessage()], 500);
} catch (Exception $e) {
    response(["error" => "General Error", "details" => $e->getMessage()], 500);
}
?>