<?php
/**
 * SAC 2026 - MONTHLY DEBT STATUS ENGINE v1.0
 * Kernel V4.1.96
 * Retorna el convenio de pago, meses pendientes y saldo a favor de una propiedad.
 */
require_once 'config.php';

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

$propertyId = $_GET['propertyId'] ?? null;

if (!$propertyId) {
    response(["error" => "Parámetros insuficientes"], 400);
}

// Verificación de Seguridad: Usuarios regulares solo ven su propia unidad
if (!in_array($_SESSION['user_role'], ['admin', 'programmer'])) {
    if ($propertyId != ($_SESSION['property_id'] ?? 0)) {
        response(["error" => "No tiene permiso para visualizar esta unidad"], 403);
    }
}

try {
    // 1. Datos de la Propiedad y Propietario
    $stmtProp = $pdo->prepare("SELECT p.id, p.code, p.number, p.type, p.initial_debt, p.credit_balance,
                              (SELECT u.full_name FROM residents r JOIN users u ON r.user_id = u.id WHERE r.property_id = p.id AND r.is_owner = 1 LIMIT 1) as ownerName
                              FROM properties p WHERE p.id = ?");
    $stmtProp->execute([$propertyId]);
    $property = $stmtProp->fetch();

    if (!$property) {
        response(["error" => "Propiedad no encontrada"], 404);
    }

    // 2. Meses Pendientes (Ordenados de más antiguo a más nuevo)
    $stmtDebts = $pdo->prepare("SELECT f.month, f.year, (d.amount_usd - d.paid_amount) as pending_amount
                               FROM property_debts d
                               JOIN monthly_fees f ON d.fee_id = f.id
                               WHERE d.property_id = ? AND (d.amount_usd - d.paid_amount) > 0.01
                               ORDER BY f.year ASC, f.month ASC");
    $stmtDebts->execute([$propertyId]);
    $pendingMonths = $stmtDebts->fetchAll();

    response([
        "success" => true,
        "property" => [
            "id" => $property['id'],
            "code" => $property['code'],
            "number" => $property['number'],
            "type" => $property['type'],
            "ownerName" => $property['ownerName'] ?? 'PROPIETARIO NO ASIGNADO',
            "initialDebt" => (float)$property['initial_debt'],
            "creditBalance" => (float)$property['credit_balance']
        ],
        "pendingMonths" => $pendingMonths
    ]);

} catch (PDOException $e) {
    response(["error" => "Error de Kernel: " . $e->getMessage()], 500);
}
?>