<?php
require_once 'config.php';

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

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

try {
    /**
     * SAC 2026 - DIRECTORIO DE RESIDENCIA
     * Admin: Ve el universo completo de residentes.
     * Propietario: Ve solo su propio registro para autovalidación de nombre.
     */
    $sql = "SELECT r.id, u.full_name as fullName, u.cedula, r.property_id as propertyId, r.phone, r.is_owner as isOwner, p.code as propertyCode, p.number as propertyNumber, p.type as propertyType
            FROM residents r
            JOIN users u ON r.user_id = u.id
            JOIN properties p ON r.property_id = p.id ";

    if (!in_array($role, ['admin', 'programmer', 'board'])) {
        $stmt = $pdo->prepare($sql . " WHERE r.user_id = ?");
        $stmt->execute([$userId]);
    } else {
        $stmt = $pdo->query($sql . " ORDER BY p.code ASC");
    }

    response($stmt->fetchAll());

} catch (PDOException $e) {
    response(["error" => "Error de acceso al directorio"], 500);
}
?>