<?php
/**
 * SAC 2025 - GET MAINTENANCE
 * Recupera tickets con cronología de atención (Reporte, Atención, Cierre).
 */
require_once 'config.php';

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

$role = $_SESSION['user_role'];
$userId = $_SESSION['user_id'];

try {
    // Consulta base con JOINs obligatorios para info de propiedad y solicitante
    $sql = "SELECT 
                m.id, 
                m.type, 
                m.description, 
                m.status, 
                m.request_date as requestDate,
                m.attended_at as attendedAt,
                m.closed_at as closedAt,
                u.full_name as requestedBy,
                m.requested_by_id as requestedById,
                p.code as propertyCode
            FROM maintenance_requests m
            JOIN users u ON m.requested_by_id = u.id
            LEFT JOIN properties p ON m.property_id = p.id ";

    if (!in_array($role, ['admin', 'programmer', 'board'])) {
        // Los propietarios solo ven sus propios reportes
        $stmt = $pdo->prepare($sql . " WHERE m.requested_by_id = ? ORDER BY m.created_at DESC");
        $stmt->execute([$userId]);
    } else {
        // Administradores ven todo el historial (Incluso pendientes de validación)
        $stmt = $pdo->query($sql . " ORDER BY m.status DESC, m.created_at DESC");
    }

    $results = $stmt->fetchAll();
    
    // Formateo de tipos para el Frontend
    foreach($results as &$row) {
        $row['id'] = (int)$row['id'];
        $row['requestedById'] = (int)$row['requestedById'];
        
        // Formatear fechas para que se vean bien en la línea de tiempo si no son nulas
        if ($row['attendedAt']) $row['attendedAt'] = date('d/m H:i', strtotime($row['attendedAt']));
        if ($row['closedAt']) $row['closedAt'] = date('d/m H:i', strtotime($row['closedAt']));
    }

    response($results);

} catch (PDOException $e) {
    // Si la tabla no existe o falla el JOIN, devolvemos error descriptivo
    response(["error" => "Error de consulta: " . $e->getMessage()], 500);
}
?>