<?php
/**
 * SAC 2026 - DETAILED ACCOUNT STATUS ENGINE v1.0
 * Kernel V4.1.41
 * Genera un reporte detallado de movimientos (cargos y abonos) para una propiedad en un mes específico.
 */
require_once 'config.php';

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

$propertyId = $_GET['propertyId'] ?? null;
$month = isset($_GET['month']) ? (int)$_GET['month'] : null;
$year = isset($_GET['year']) ? (int)$_GET['year'] : null;

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

try {
    // 1. Datos de la Propiedad y Propietario
    $stmtProp = $pdo->prepare("SELECT p.id, p.code, p.number, p.type, p.aliquot, p.initial_debt as current_debt,
                              (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. Cuota del Mes Seleccionado
    $stmtFee = $pdo->prepare("SELECT f.id as fee_id, f.total_usd as fee_total_usd, d.amount_usd as property_amount_usd, d.paid_amount as property_paid_amount, d.status
                             FROM monthly_fees f
                             JOIN property_debts d ON f.id = d.fee_id
                             WHERE d.property_id = ? AND f.month = ? AND f.year = ?");
    $stmtFee->execute([$propertyId, $month, $year]);
    $currentMonthFee = $stmtFee->fetch();

    // 3. Todos los pagos realizados EN el mes seleccionado (independientemente de qué deuda paguen)
    // Buscamos en la tabla 'payments' filtrando por fecha
    $startDate = sprintf("%04d-%02d-01", $year, $month + 1);
    $endDate = date("Y-m-t", strtotime($startDate));

    $stmtPayments = $pdo->prepare("SELECT p.payment_date as date, p.amount_usd as amount, p.method, p.reference, p.time_slot as slot, f.month as fee_month, f.year as fee_year
                                  FROM payments p
                                  JOIN property_debts d ON p.debt_id = d.id
                                  JOIN monthly_fees f ON d.fee_id = f.id
                                  WHERE d.property_id = ? AND p.payment_date BETWEEN ? AND ?
                                  ORDER BY p.payment_date ASC");
    $stmtPayments->execute([$propertyId, $startDate, $endDate]);
    $monthlyPayments = $stmtPayments->fetchAll();

    // 4. Pagos de Deuda Histórica (Convenios) realizados EN el mes seleccionado
    // Estos se registran en bank_transactions con una descripción específica
    $propCode = trim($property['code']);
    $stmtHistory = $pdo->prepare("SELECT date, description, amount_usd as amount, reference 
                                 FROM bank_transactions 
                                 WHERE (description LIKE ? OR description LIKE ?)
                                 AND date BETWEEN ? AND ?
                                 ORDER BY date ASC");
    
    $stmtHistory->execute([
        "RECUPERACIÓN DEUDA HISTÓRICA: $propCode%",
        "RECUPERACIÓN DEUDA ANTERIOR: $propCode%",
        $startDate,
        $endDate
    ]);
    $historyPaymentsRaw = $stmtHistory->fetchAll();

    // Filtrado estricto para evitar que la propiedad #4 vea abonos de la #41
    $historyPayments = array_filter($historyPaymentsRaw, function($h) use ($propCode) {
        $desc = $h['description'];
        // Buscamos el patrón exacto: "PREFIX: CODE" seguido de espacio o fin de cadena
        $pattern = "/RECUPERACIÓN DEUDA (HISTÓRICA|ANTERIOR): " . preg_quote($propCode) . "([^0-9]|$)/";
        return preg_match($pattern, $desc);
    });

    // Consolidar todos los abonos del mes
    $allAbonos = [];
    foreach ($monthlyPayments as $p) {
        $allAbonos[] = [
            "date" => $p['date'],
            "amount" => (float)$p['amount'],
            "method" => $p['method'],
            "reference" => $p['reference'],
            "description" => "Pago Cuota " . ($p['fee_month'] + 1) . "/" . $p['fee_year']
        ];
    }
    foreach ($historyPayments as $h) {
        $allAbonos[] = [
            "date" => $h['date'],
            "amount" => (float)$h['amount'],
            "method" => "Transferencia/Depósito",
            "reference" => $h['reference'],
            "description" => "Abono a Convenio / Deuda Histórica"
        ];
    }

    // Ordenar abonos por fecha
    usort($allAbonos, fn($a, $b) => strcmp($a['date'], $b['date']));

    // 5. Saldo Total Pendiente (Deuda Actual)
    // Sumamos todas las deudas pendientes de property_debts + initial_debt de la propiedad
    $stmtTotalDebt = $pdo->prepare("SELECT SUM(amount_usd - paid_amount) as pending_fees FROM property_debts WHERE property_id = ?");
    $stmtTotalDebt->execute([$propertyId]);
    $pendingFees = (float)$stmtTotalDebt->fetchColumn();
    
    $totalDebt = round($pendingFees + (float)$property['current_debt'], 2);

    response([
        "success" => true,
        "property" => [
            "id" => $property['id'],
            "code" => $property['code'],
            "number" => $property['number'],
            "type" => $property['type'],
            "aliquot" => (float)$property['aliquot'],
            "ownerName" => $property['ownerName'] ?? 'PROPIETARIO NO ASIGNADO'
        ],
        "currentMonthFee" => $currentMonthFee ? [
            "billed" => (float)$currentMonthFee['property_amount_usd'],
            "paid" => (float)$currentMonthFee['property_paid_amount'],
            "status" => $currentMonthFee['status']
        ] : null,
        "movements" => $allAbonos,
        "totalDebt" => $totalDebt
    ]);

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