<?php
require_once 'config.php';

/**
 * SAC 2026 - GET FEES ENGINE v33.0 (APPROVAL SYSTEM)
 */

if (!isset($_SESSION['user_id'])) {
    response(["error" => "Inicie sesión"], 401);
}

$role = $_SESSION['user_role'];
$userId = $_SESSION['user_id'];
$propertyId = $_SESSION['property_id'] ?? null;

try {
    $stmt = $pdo->query("SELECT id, month, year, exchange_rate as exchangeRate, reserve_fund_percent as reserveFundPercent, total_usd as totalUsd, total_bs as totalBs, status, created_at as createdAt FROM monthly_fees ORDER BY year DESC, month DESC");
    $fees = $stmt->fetchAll();

    foreach ($fees as &$fee) {
        $feeId = $fee['id'];

        $globalStmt = $pdo->prepare("SELECT SUM(amount_usd) as totalBilled, SUM(paid_amount) as totalCollected FROM property_debts WHERE fee_id = ?");
        $globalStmt->execute([$feeId]);
        $gStats = $globalStmt->fetch();
        $fee['globalStats'] = ["totalBilled" => (float)($gStats['totalBilled'] ?? 0), "totalCollected" => (float)($gStats['totalCollected'] ?? 0)];

        $itemStmt = $pdo->prepare("SELECT description, amount_usd as amountUsd, category, is_uncommon as isUncommon, is_special as isSpecial, special_property_ids as specialPropertyIds FROM monthly_fee_items WHERE fee_id = ?");
        $itemStmt->execute([$feeId]);
        $items = $itemStmt->fetchAll();
        foreach($items as &$it) { $it['specialPropertyIds'] = json_decode($it['specialPropertyIds'] ?? '[]', true); }
        $fee['fixedExpenses'] = array_values(array_filter($items, fn($i) => $i['category'] === 'fixed'));
        $fee['variableExpenses'] = array_values(array_filter($items, fn($i) => $i['category'] === 'variable'));
        $fee['otherExpenses'] = array_values(array_filter($items, fn($i) => $i['category'] === 'other'));

        // CARGA DE DEUDAS INCLUYENDO PENDING_PAYMENT Y REJECTION_MESSAGE
        if (!in_array($role, ['admin', 'programmer', 'board'])) {
            $debtStmt = $pdo->prepare("SELECT id, fee_id as feeId, property_id as propertyId, amount_usd as amountUsd, paid_amount as paidAmount, previous_debt as previousDebt, status, receipt_sent_json as receiptSentJson, pending_payment_json as pendingPaymentJson, rejection_message as rejectionMessage FROM property_debts WHERE fee_id = ? AND property_id = ?");
            $debtStmt->execute([$feeId, $propertyId]);
        } else {
            $debtStmt = $pdo->prepare("SELECT id, fee_id as feeId, property_id as propertyId, amount_usd as amountUsd, paid_amount as paidAmount, previous_debt as previousDebt, status, receipt_sent_json as receiptSentJson, pending_payment_json as pendingPaymentJson, rejection_message as rejectionMessage FROM property_debts WHERE fee_id = ?");
            $debtStmt->execute([$feeId]);
        }
        
        $debts = $debtStmt->fetchAll();
        foreach ($debts as &$d) {
            $payStmt = $pdo->prepare("SELECT id, payment_date as date, amount_usd as amount, method, reference, time_slot as slot FROM payments WHERE debt_id = ?");
            $payStmt->execute([$d['id']]);
            $d['payments'] = $payStmt->fetchAll();
            $d['receiptSent'] = json_decode($d['receiptSentJson'] ?? '{}', true);
            $d['pendingPayment'] = json_decode($d['pendingPaymentJson'] ?? 'null', true);
            $d['rejectionMessage'] = $d['rejectionMessage'] ?? null;
        }
        $fee['debts'] = $debts;
    }
    response($fees);
} catch (PDOException $e) {
    response(["error" => "Fallo en motor de recuperación"], 500);
}
?>