<?php
require_once 'config.php';
if (!isset($_SESSION['user_id'])) response(["error" => "No autorizado"], 401);

$rif = $_GET['rif'] ?? '';
if (empty($rif)) response([], 200);

try {
    // 1. Obtener el nombre del proveedor para buscar coincidencias de texto en las tablas de egresos
    $stmtName = $pdo->prepare("SELECT name FROM providers WHERE rif = ?");
    $stmtName->execute([$rif]);
    $providerName = $stmtName->fetchColumn();

    if (!$providerName) response([], 200);

    // 2. Buscamos en facturas pendientes (pending_bills) y transacciones de banco (bank_transactions)
    // Usamos LIKE para capturar registros donde el nombre del proveedor aparezca en la descripción o campo provider
    
    // FACTURAS
    $sqlBills = "SELECT id, creation_date as date, description, amount_usd as amountUsd, amount_bs as amountBs, status, 'Factura' as type 
                 FROM pending_bills 
                 WHERE provider LIKE :name OR description LIKE :name_desc";
    
    $stmtB = $pdo->prepare($sqlBills);
    $stmtB->execute([':name' => "%$providerName%", ':name_desc' => "%$providerName%"]);
    $bills = $stmtB->fetchAll();

    // PAGOS REALES EN BANCO
    $sqlBank = "SELECT id, date, description, amount_usd as amountUsd, amount_bs as amountBs, 'Pagado' as status, 'Pago Directo' as type, reference
                FROM bank_transactions 
                WHERE type = 'Egreso' AND (description LIKE :name OR category LIKE :name_cat)";
    
    $stmtBk = $pdo->prepare($sqlBank);
    $stmtBk->execute([':name' => "%$providerName%", ':name_cat' => "%$providerName%"]);
    $bank = $stmtBk->fetchAll();

    // Combinar y normalizar
    $history = array_merge($bills, $bank);
    
    // Ordenar por fecha descendente
    usort($history, function($a, $b) {
        return strcmp($b['date'], $a['date']);
    });

    response($history);

} catch (PDOException $e) {
    response(["error" => $e->getMessage()], 500);
}