<?php
/**
 * SAC 2026 - GET OWNER PAYMENT REPORTS
 * Arquitecto: Andres Mathison
 * Objetivo: Listar todos los reportes de pago pendientes de revisión.
 */
require_once 'config.php';

checkAccess(['admin', 'programmer', 'board']);

try {
    $stmt = $pdo->query("SELECT 
                            pd.id,
                            pd.property_id as propertyId,
                            p.code as propertyCode,
                            r.full_name as ownerName,
                            pd.fee_id as feeId,
                            mf.month,
                            mf.year,
                            pd.pending_payment_json as pending_payment_json,
                            pd.report_seen as seen,
                            pd.status
                         FROM property_debts pd
                         JOIN properties p ON pd.property_id = p.id
                         JOIN monthly_fees mf ON pd.fee_id = mf.id
                         LEFT JOIN residents r ON p.id = r.property_id AND r.is_owner = 1
                         WHERE pd.pending_payment_json IS NOT NULL
                         ORDER BY mf.year DESC, mf.month DESC, pd.id DESC");
    
    $reports = $stmt->fetchAll();
    
    foreach ($reports as &$report) {
        $report['pendingPayment'] = json_decode($report['pending_payment_json'], true);
        $report['seen'] = (bool)$report['seen'];
        unset($report['pending_payment_json']);
    }

    response($reports);

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