<?php
/**
 * SAC 2026 - DETAILED REVENUE ENGINE v1.1
 * Kernel V4.1.42
 * Objetivo: Cruzar todos los abonos (Mes + Histórico) para auditoría de vouchers.
 */
require_once 'config.php';

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

try {
    /**
     * UNIÓN ATÓMICA DE FUENTES DE INGRESO
     * Fuente A: Tabla payments (Abonos a cuotas actuales)
     * Fuente B: Tabla bank_transactions (Abonos a deudas históricas)
     */
    $sql = "
        -- ABONOS A CUOTAS ACTUALES
        SELECT 
            p.payment_date as fecha,
            prop.code as prop_code,
            u.full_name as owner_name,
            p.amount_usd as monto_usd,
            0 as monto_bs, -- El BS se recupera del banco en el frontend si es necesario
            p.method as metodo,
            p.reference as referencia,
            0 as is_historical
        FROM payments p
        JOIN property_debts d ON p.debt_id = d.id
        JOIN properties prop ON d.property_id = prop.id
        JOIN residents r ON prop.id = r.property_id AND r.is_owner = 1
        JOIN users u ON r.user_id = u.id

        UNION ALL

        -- ABONOS A DEUDAS HISTÓRICAS (EXTRAÍDOS DE BANCO)
        SELECT 
            bt.date as fecha,
            SUBSTRING_INDEX(TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(bt.description, ':', 2), ':', -1)), ' ', 1) as prop_code,
            (SELECT u2.full_name 
             FROM residents r2 
             JOIN users u2 ON r2.user_id = u2.id 
             JOIN properties p2 ON r2.property_id = p2.id 
             WHERE p2.code = SUBSTRING_INDEX(TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(bt.description, ':', 2), ':', -1)), ' ', 1) AND r2.is_owner = 1 LIMIT 1) as owner_name,
            bt.amount_usd as monto_usd,
            bt.amount_bs as monto_bs,
            IF(bt.description LIKE '%EFECTIVO%', 'Efectivo / Divisa', 'Transferencia') as metodo,
            bt.reference as referencia,
            1 as is_historical
        FROM bank_transactions bt
        WHERE bt.type = 'Ingreso' 
        AND (bt.description LIKE 'RECUPERACIÓN DEUDA HISTÓRICA%' OR bt.description LIKE 'RECUPERACIÓN DEUDA ANTERIOR%')
        
        ORDER BY fecha DESC
    ";

    $stmt = $pdo->query($sql);
    $data = $stmt->fetchAll();
    
    response(["success" => true, "data" => $data]);

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