<?php
/**
 * SAC 2026 - GET PENDING BILLS v12.0 (PARTIAL PAYMENTS EDITION)
 * Kernel V4.0.74
 */
require_once 'config.php';

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

try {
    // 1. Obtener cabeceras de facturas
    $stmt = $pdo->query("SELECT 
        id, provider, description, 
        amount_usd as amount, 
        amount_bs as amountBs, 
        paid_amount_usd,
        paid_amount_bs,
        due_date as dueDate, 
        status, 
        creation_date as creationDate, 
        creation_rate as creationRate,
        paid_date as paidDate,
        payment_source as paymentSource,
        prefill_fee,
        fee_category,
        is_uncommon,
        is_special,
        special_props_json,
        target_month,
        target_year,
        is_silent
    FROM pending_bills 
    ORDER BY status ASC, due_date DESC");
    
    $bills = $stmt->fetchAll();
    
    foreach($bills as &$b) {
        $billId = (int)$b['id'];
        $b['id'] = $billId;
        $b['amount'] = (float)$b['amount'];
        $b['amountBs'] = (float)$b['amountBs'];
        $b['paid_amount_usd'] = (float)($b['paid_amount_usd'] ?? 0);
        $b['paid_amount_bs'] = (float)($b['paid_amount_bs'] ?? 0);
        $b['creationRate'] = (float)$b['creationRate'];
        $b['prefill_fee'] = (bool)$b['prefill_fee'];
        $b['is_uncommon'] = (bool)$b['is_uncommon'];
        $b['is_special'] = (bool)$b['is_special'];
        $b['is_silent'] = (bool)($b['is_silent'] ?? false);
        $b['special_props_json'] = json_decode($b['special_props_json'] ?? '[]', true);
        
        // 2. Obtener lista de pagos parciales para trazabilidad v4.0.74
        $payStmt = $pdo->prepare("SELECT id, amount_usd, amount_bs, reference, source, payment_date 
                                  FROM pending_bill_payments 
                                  WHERE bill_id = ? 
                                  ORDER BY payment_date ASC");
        $payStmt->execute([$billId]);
        $b['payments'] = $payStmt->fetchAll();
    }

    response($bills);
} catch (PDOException $e) {
    response(["error" => "Fallo de comunicaci¨®n con el motor de egresos: " . $e->getMessage()], 500);
}
?>