<?php
/**
 * SAC 2026 - API: SALDO DESGLOSADO v1.0
 * Kernel V4.2.03 MC/MB
 */
require_once 'config.php';

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(["success" => false, "error" => "No autorizado"]);
    exit;
}

$propertyId = $_GET['propertyId'] ?? null;
$month = $_GET['month'] ?? null; // 0-11
$year = $_GET['year'] ?? null;

if (!$propertyId || $month === null || !$year) {
    echo json_encode(["success" => false, "error" => "Faltan par¨¢metros"]);
    exit;
}

// Convertir mes a 1-12 para SQL si es necesario, pero aqu¨ª usamos 0-11
$monthNum = (int)$month + 1;
$yearNum = (int)$year;

try {
    // 1. Obtener datos de la propiedad
    $stmtProp = $pdo->prepare("SELECT * FROM properties WHERE id = ?");
    $stmtProp->execute([$propertyId]);
    $property = $stmtProp->fetch();

    if (!$property) {
        echo json_encode(["success" => false, "error" => "Propiedad no encontrada"]);
        exit;
    }

    // 2. Deuda de Meses Anteriores (Acumulada en el sistema)
    $stmtOldSys = $pdo->prepare("
        SELECT COALESCE(SUM(d.amount_usd - d.paid_amount), 0) 
        FROM property_debts d
        JOIN monthly_fees f ON d.fee_id = f.id
        WHERE d.property_id = ? 
        AND (f.year < ? OR (f.year = ? AND f.month < ?))
    ");
    $stmtOldSys->execute([$propertyId, $yearNum, $yearNum, $monthNum]);
    $oldSystemDebt = (float)$stmtOldSys->fetchColumn() ?: 0.00;

    // 3. Saldo de Convenio de Pago (Deuda Hist¨®rica / Inicial)
    // En este sistema, el convenio se guarda en properties.initial_debt
    $agreementBalance = (float)($property['initial_debt'] ?? 0.00);

    // Suma de deuda antes del mes actual
    $initialDebtTotal = $oldSystemDebt + $agreementBalance;

    // 4. Cuota del Mes en curso
    $stmtCurrentFee = $pdo->prepare("
        SELECT COALESCE(d.amount_usd, 0)
        FROM property_debts d
        JOIN monthly_fees f ON d.fee_id = f.id
        WHERE d.property_id = ? AND f.month = ? AND f.year = ?
    ");
    $stmtCurrentFee->execute([$propertyId, $monthNum, $yearNum]);
    $currentFee = (float)$stmtCurrentFee->fetchColumn() ?: 0.00;

    // 5. Pagos hechos en el mes
    // ... rest of the code ...
    $stmtPayments = $pdo->prepare("
        SELECT 
            p.amount_usd, 
            p.payment_date as date, 
            p.reference,
            p.method,
            COALESCE(bt.amount_bs, 0) as amount_bs
        FROM payments p
        JOIN property_debts d ON p.debt_id = d.id
        LEFT JOIN bank_transactions bt ON p.reference = bt.reference AND bt.type = 'Ingreso'
        WHERE d.property_id = ? 
        AND MONTH(p.payment_date) = ? 
        AND YEAR(p.payment_date) = ?
    ");
    $stmtPayments->execute([$propertyId, $monthNum, $yearNum]);
    $paymentsList = $stmtPayments->fetchAll();

    // 6. Amortizaci¨®n y Enriquecimiento de datos
    $remainingOldDebt = $initialDebtTotal;
    $processedPayments = [];
    foreach ($paymentsList as $p) {
        $amountUsd = (float)$p['amount_usd'];
        $amountBs = (float)$p['amount_bs'];
        $rate = ($amountUsd > 0) ? ($amountBs / $amountUsd) : 0;
        
        $appliedToOld = 0;
        $appliedToCurrent = 0;

        if ($remainingOldDebt > 0) {
            if ($amountUsd >= $remainingOldDebt) {
                $appliedToOld = $remainingOldDebt;
                $amountUsd -= $remainingOldDebt;
                $remainingOldDebt = 0;
            } else {
                $appliedToOld = $amountUsd;
                $remainingOldDebt -= $amountUsd;
                $amountUsd = 0;
            }
        }

        if ($amountUsd > 0) {
            $appliedToCurrent = $amountUsd;
        }

        $processedPayments[] = [
            'date' => $p['date'],
            'amount_bs' => $amountBs,
            'amount_usd' => (float)$p['amount_usd'],
            'rate' => round($rate, 4),
            'reference' => $p['reference'],
            'applied_to_old' => $appliedToOld,
            'applied_to_current' => $appliedToCurrent
        ];
    }

    echo json_encode([
        "success" => true,
        "data" => [
            "property" => [
                "code" => $property['code'],
                "type" => $property['type'],
                "number" => $property['number']
            ],
            "initial_debt" => (float)$oldSystemDebt,
            "agreement_balance" => (float)$agreementBalance,
            "current_fee" => (float)$currentFee,
            "payments_count" => count($processedPayments),
            "payments" => $processedPayments,
            "final_balance" => (float)($initialDebtTotal + $currentFee - array_sum(array_column($processedPayments, 'amount_usd')))
        ]
    ]);

} catch (PDOException $e) {
    echo json_encode(["success" => false, "error" => $e->getMessage()]);
}
?>