<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
require_once __DIR__ . '/../includes/session_control.php';
require_once __DIR__ . '/../cotizaciones/api/_node.php';

function getTextColor(string $hex): string
{
    $h = ltrim($hex, '#');
    $r = hexdec(substr($h, 0, 2));
    $g = hexdec(substr($h, 2, 2));
    $b = hexdec(substr($h, 4, 2));
    $lum = ($r * 0.299 + $g * 0.587 + $b * 0.114) / 255;
    return $lum > 0.5 ? '#000000' : '#ffffff';
}

function fmt($val)
{
    if ($val == 0) return '-';
    return '$ ' . number_format(abs($val), 0, '', '.');
}

function fmtDateTime(?string $val): string
{
    if (!$val) return '-';
    try {
        $dt = new DateTime($val);
        return $dt->format('d-M-y g:i a');
    } catch (Exception $e) {
        return '-';
    }
}

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

$r = cpn_node_request('GET', $base . '/api/ordenes/cartera', $token);
if (!isset($r['ok']) || $r['ok'] !== true) {
    http_response_code($r['_http'] ?? 500);
    die('Error consultando cartera (compras) en Node');
}

$rows = $r['data'] ?? [];
if (!is_array($rows)) $rows = [];

$today = new DateTime('today');
?>

<?php include '../templates/header.php'; ?>
<div class="container-fluid ordenes-container">
    <h1 class="h3 mb-4 text-gray-800">Cartera Compras</h1>

    <div class="table-responsive mb-3">
        <table class="table table-bordered table-sm fixed-table">
            <thead class="thead-light">
                <tr>
                    <th class="text-center">Empresa</th>
                    <th class="text-center">No.</th>
                    <th class="text-center">Solicitud</th>
                    <th class="text-center">Factura</th>
                    <th class="text-center">Fecha Factura</th>
                    <th class="text-center">Vence</th>
                    <th class="text-center">Proveedor</th>
                    <th class="text-right">Total</th>
                    <th class="text-center">Estado</th>
                    <th class="text-center">Siigo</th>
                    <th class="text-center">Acciones</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $sumTotal = 0;
                foreach ($rows as $r):
                    $sumTotal += (float)($r['total'] ?? 0);

                    $venceRaw = $r['fechaVencimiento'] ?? null;
                    $venceClass = '';
                    if ($venceRaw) {
                        try {
                            $vence = new DateTime($venceRaw);
                            if ($vence < $today) {
                                $venceClass = 'table-danger';
                            }
                        } catch (Exception $e) {
                            // ignore
                        }
                    }

                    $fact = trim((string)($r['prefijoFactura'] ?? '') . ' ' . (string)($r['noFactura'] ?? ''));
                    if ($fact === '') $fact = '-';
                    $prov = (string)($r['Proveedor'] ?? '') . (!empty($r['Area']) ? ' (' . (string)$r['Area'] . ')' : '');
                    $iconSiigo = ($r['siigo_id'] ?? null) !== null ? '<strong>S</strong>' : '';
                ?>
                    <tr class="<?= $venceClass ?>">
                        <td class="text-center"
                            style="background-color: <?= htmlspecialchars((string)($r['EmpresaColor'] ?? '')) ?>; color: <?= getTextColor((string)($r['EmpresaColor'] ?? '')) ?>;">
                            <strong><?= htmlspecialchars((string)($r['EmpresaSigla'] ?? '')) ?></strong>
                        </td>
                        <td class="text-center"><strong><?= (int)($r['id'] ?? 0) ?></strong></td>
                        <td class="text-center"><?= fmtDateTime($r['fechaSolicitud'] ?? null) ?></td>
                        <td class="text-center"><strong><?= htmlspecialchars($fact) ?></strong></td>
                        <td class="text-center"><?= fmtDateTime($r['fechaFactura'] ?? null) ?></td>
                        <td class="text-center"><strong><?= fmtDateTime($r['fechaVencimiento'] ?? null) ?></strong></td>
                        <td class="text-center"><strong><?= htmlspecialchars($prov) ?></strong></td>
                        <td class="text-right"><strong><?= fmt($r['total'] ?? 0) ?></strong></td>
                        <td class="text-center"
                            style="background-color: <?= htmlspecialchars((string)($r['EstadoColor'] ?? '')) ?>; color: <?= getTextColor((string)($r['EstadoColor'] ?? '')) ?>;">
                            <strong><?= htmlspecialchars((string)($r['Estado'] ?? '')) ?></strong>
                        </td>
                        <td class="text-center"><?= $iconSiigo ?></td>
                        <td class="text-center">
                            <a href="pedido.php?id=<?= (int)($r['id'] ?? 0) ?>" class="btn btn-sm btn-primary">Ver</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <tr class="font-weight-bold">
                    <td colspan="7" class="text-right">Totales:</td>
                    <td class="text-right"><strong><?= fmt($sumTotal) ?></strong></td>
                    <td colspan="3"></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
<?php include '../templates/footer.php'; ?>