<?php
/**
 * SAC 2026 - DETAILED EXCEL REPORT ENGINE v1.2
 * Kernel V4.1.12
 */
require_once 'config.php';

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

$month = $_GET['month'] ?? null;
$year = $_GET['year'] ?? null;
$type = $_GET['type'] ?? 'receivable'; // 'receivable' o 'payable'

if (!$month || !$year) {
    response(["error" => "Mes y Año son requeridos"], 400);
}

try {
    $data = [];

    if ($type === 'receivable') {
        // CUENTAS POR COBRAR (INGRESOS)
        // Obtenemos todas las propiedades para asegurar que aparezcan las 34 (o las que sean)
        // Y unimos con la deuda que corresponda al mes/año solicitado
        $stmt = $pdo->prepare("
            SELECT 
                p.code as property_code,
                p.number as owner_name,
                pd_month.id as debt_id,
                pd_month.amount_usd as total_debt_usd,
                pd_month.status as current_status
            FROM properties p
            LEFT JOIN (
                SELECT pd2.* FROM property_debts pd2
                JOIN monthly_fees mf2 ON pd2.fee_id = mf2.id
                WHERE mf2.month = ? AND mf2.year = ?
            ) pd_month ON p.id = pd_month.property_id
            ORDER BY p.code ASC
        ");
        $stmt->execute([$month, $year]);
        $debts = $stmt->fetchAll();

        foreach ($debts as $debt) {
            if (!$debt['debt_id']) {
                // Propiedad sin deuda generada para este mes
                $data[] = [
                    'Propiedad' => $debt['property_code'],
                    'Propietario' => $debt['owner_name'],
                    'Estatus' => 'SIN DEUDA GENERADA',
                    'Monto Deuda ($)' => 0,
                    'Monto Pagado ($)' => 0,
                    'Saldo ($)' => 0,
                    'Fecha Pago' => '-',
                    'Referencia' => '-',
                    'Método' => '-',
                    'Tasa' => '-',
                    'Monto (Bs)' => '-',
                    'Periodo Pagado' => '-'
                ];
                continue;
            }

            // Obtener pagos para esta deuda
            // Filtramos por el mes solicitado para evitar "data de otros meses"
            $payStmt = $pdo->prepare("
                SELECT 
                    payment_date as date,
                    amount_usd as amount,
                    amount_bs as amount_bs,
                    method,
                    reference,
                    time_slot as slot,
                    exchange_rate as rate
                FROM payments 
                WHERE debt_id = ?
                  AND MONTH(payment_date) = ? AND YEAR(payment_date) = ?
            ");
            $payStmt->execute([$debt['debt_id'], $month, $year]);
            $payments = $payStmt->fetchAll();

            if (empty($payments)) {
                // Si no hay pagos EN ESTE MES, mostramos el registro con su estatus actual
                $data[] = [
                    'Propiedad' => $debt['property_code'],
                    'Propietario' => $debt['owner_name'],
                    'Estatus' => strtoupper($debt['current_status']),
                    'Monto Deuda ($)' => (float)$debt['total_debt_usd'],
                    'Monto Pagado ($)' => 0,
                    'Saldo ($)' => (float)$debt['total_debt_usd'],
                    'Fecha Pago' => '-',
                    'Referencia' => '-',
                    'Método' => '-',
                    'Tasa' => '-',
                    'Monto (Bs)' => '-',
                    'Periodo Pagado' => '-'
                ];
            } else {
                $acumulado = 0;
                foreach ($payments as $p) {
                    $acumulado += (float)$p['amount'];
                    $data[] = [
                        'Propiedad' => $debt['property_code'],
                        'Propietario' => $debt['owner_name'],
                        'Estatus' => strtoupper($debt['current_status']),
                        'Monto Deuda ($)' => (float)$debt['total_debt_usd'],
                        'Monto Pagado ($)' => (float)$p['amount'],
                        'Saldo ($)' => (float)($debt['total_debt_usd'] - $acumulado),
                        'Fecha Pago' => $p['date'],
                        'Referencia' => $p['reference'],
                        'Método' => $p['method'],
                        'Tasa' => (float)($p['rate'] ?? 0),
                        'Monto (Bs)' => (float)($p['amount_bs'] ?? 0),
                        'Periodo Pagado' => $p['slot']
                    ];
                }
            }
        }
    } else {
        // CUENTAS POR PAGAR (EGRESOS)
        // Filtro estricto por target_month y target_year para evitar facturas de otros meses
        $stmt = $pdo->prepare("
            SELECT 
                id, provider, description, amount_usd, amount_bs, status, creation_date, creation_rate, due_date
            FROM pending_bills 
            WHERE target_month = ? AND target_year = ?
            ORDER BY creation_date ASC
        ");
        $stmt->execute([$month, $year]);
        $bills = $stmt->fetchAll();

        foreach ($bills as $bill) {
            $billId = $bill['id'];
            // Pagos realizados EN EL MES solicitado
            $payStmt = $pdo->prepare("
                SELECT 
                    payment_date, amount_usd, amount_bs, reference, source
                FROM pending_bill_payments 
                WHERE bill_id = ?
                  AND MONTH(payment_date) = ? AND YEAR(payment_date) = ?
            ");
            $payStmt->execute([$billId, $month, $year]);
            $payments = $payStmt->fetchAll();

            if (empty($payments)) {
                $data[] = [
                    'Proveedor' => $bill['provider'],
                    'Descripción' => $bill['description'],
                    'Estatus Factura' => strtoupper($bill['status']),
                    'Monto Total Factura ($)' => (float)$bill['amount_usd'],
                    'Monto Pagado en este Registro ($)' => 0,
                    'Saldo Pendiente ($)' => (float)$bill['amount_usd'],
                    'Fecha de Pago' => '-',
                    'Referencia de Pago' => '-',
                    'Fuente de Fondos' => '-',
                    'Monto en Bs (Factura)' => (float)$bill['amount_bs'],
                    'Fecha Vencimiento' => $bill['due_date'],
                    'Fecha Creación' => $bill['creation_date'],
                    'Tasa Creación' => (float)$bill['creation_rate']
                ];
            } else {
                $acumulado = 0;
                foreach ($payments as $p) {
                    $acumulado += (float)$p['amount_usd'];
                    $data[] = [
                        'Proveedor' => $bill['provider'],
                        'Descripción' => $bill['description'],
                        'Estatus Factura' => strtoupper($bill['status']),
                        'Monto Total Factura ($)' => (float)$bill['amount_usd'],
                        'Monto Pagado en este Registro ($)' => (float)$p['amount_usd'],
                        'Saldo Pendiente ($)' => (float)($bill['amount_usd'] - $acumulado),
                        'Fecha de Pago' => $p['payment_date'],
                        'Referencia de Pago' => $p['reference'],
                        'Fuente de Fondos' => $p['source'],
                        'Monto en Bs (Pago)' => (float)$p['amount_bs'],
                        'Fecha Vencimiento' => $bill['due_date'],
                        'Fecha Creación' => $bill['creation_date'],
                        'Tasa Creación' => (float)$bill['creation_rate']
                    ];
                }
            }
        }
    }

    response($data);
} catch (PDOException $e) {
    response(["error" => "Fallo en motor de reportes detallados: " . $e->getMessage()], 500);
}
?>