<?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();

$filter_empresa  = isset($_GET['filter_empresa']) && $_GET['filter_empresa'] !== '0' && $_GET['filter_empresa'] !== ''
    ? intval($_GET['filter_empresa'])
    : '';
$filter_mes = trim((string)($_GET['filter_mes'] ?? ''));

$qs = [];
if ($filter_empresa !== '') $qs['filter_empresa'] = $filter_empresa;
if ($filter_mes !== '') $qs['filter_mes'] = $filter_mes;

$url = $base . '/api/ventas/cartera' . (count($qs) ? ('?' . http_build_query($qs)) : '');
$r = cpn_node_request('GET', $url, $token);
if (!isset($r['ok']) || $r['ok'] !== true) {
    http_response_code($r['_http'] ?? 500);
    die('Error consultando cartera en Node');
}

$rows = $r['data'] ?? [];
if (!is_array($rows)) $rows = [];
?>

<?php include '../templates/header.php'; ?>
<div class="container-fluid ordenes-container">
    <h1 class="h3 mb-4 text-gray-800">Cartera Ventas</h1>

    <?php
    // meta para empresas
    $metaResp = cpn_node_request('GET', $base . '/api/ventas/meta', $token);
    $meta = (isset($metaResp['ok']) && $metaResp['ok'] === true) ? ($metaResp['data'] ?? []) : [];
    $empresas = is_array($meta['empresas'] ?? null) ? $meta['empresas'] : [];
    ?>

    <form class="form-inline mb-3" method="get">
        <select name="filter_empresa" class="form-control mr-2 mb-2">
            <option value="0">Todas las empresas</option>
            <?php foreach ($empresas as $emp):
                $eid = (int)($emp['id'] ?? 0);
                $sigla = (string)($emp['sigla'] ?? '');
                $sel = ($filter_empresa !== '' && (int)$filter_empresa === $eid) ? 'selected' : '';
            ?>
                <option value="<?= $eid ?>" <?= $sel ?>><?= htmlspecialchars($sigla) ?></option>
            <?php endforeach; ?>
        </select>

        <input
            type="month"
            name="filter_mes"
            class="form-control mr-2 mb-2"
            value="<?= htmlspecialchars($filter_mes) ?>"
            title="Mes (YYYY-MM)">

        <button class="btn btn-primary mb-2">Filtrar</button>
        <a href="cartera.php" class="btn btn-secondary mb-2 ml-2">Limpiar</a>
    </form>

    <div class="table-responsive mb-3">
        <table class="table table-bordered table-sm fixed-table">
            <colgroup>
                <col style="width: 5%;">
                <col style="width: 6%;">
                <col style="width: 6%;">
                <col style="width: 6%;">
                <col style="width: 6%;">
                <col style="width: 6%;">
                <col style="width: 9%;">
                <col style="width: 7%;">
                <col style="width: 7%;">
                <col style="width: 6%;">
                <col style="width: 7%;">
                <col style="width: 7%;">
                <col style="width: 7%;">
                <col style="width: 7%;">
                <col style="width: 6%;"> <!-- Acciones -->
            </colgroup>
            <thead class="thead-light">
                <tr>
                    <th class="text-center">No.</th>
                    <th class="text-center">Fecha</th>
                    <th class="text-center">Ref</th>
                    <th class="text-center">Estado</th>
                    <th class="text-center">Tipo</th>
                    <th class="text-center">Medio</th>
                    <th class="text-center client-col">Cliente</th>
                    <th class="text-right">Subtotal</th>
                    <th class="text-right">Impuesto</th>
                    <th class="text-right">Envío</th>
                    <th class="text-right">Total</th>
                    <th class="text-right">Pagos</th>
                    <th class="text-right">Deducciones</th>
                    <th class="text-right">Saldo</th>
                    <th class="text-center">Acciones</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $sumTotal = $sumPagos = $sumDeducciones = $sumSaldo = 0;
                foreach ($rows as $r):
                    $sumTotal       += (float)($r['total'] ?? 0);
                    $sumPagos       += (float)($r['pagos'] ?? 0);
                    $sumDeducciones += (float)($r['deducciones'] ?? 0);
                    $sumSaldo       += (float)($r['saldo'] ?? 0);
                    $saldo = (float)($r['saldo'] ?? 0);
                    $cls = $saldo > 0 ? 'positive-money' : ($saldo < 0 ? 'negative-money' : '');
                ?>
                    <tr>
                        <td class="text-center"><strong><?= $r['id'] ?></strong></td>
                        <td class="text-center"><?= fmtDateTime($r['fechaOrden'] ?? null) ?></td>
                        <td class="text-center">
                            <?php
                            $ref = $r['refExt'] ?? '';
                            if (preg_match('/^COT\-(\d+)$/', $ref, $m)) {
                                echo '<a href="/cotizaciones/cotizaciones.php?id='
                                    . $m[1]
                                    . '">'
                                    . htmlspecialchars($ref)
                                    . '</a>';
                            } else {
                                echo htmlspecialchars($ref);
                            }
                            ?>
                        </td>


                        <td class="text-center"
                            style="background-color: <?= $r['estadoColor'] ?>; color: <?= getTextColor($r['estadoColor']) ?>;">
                            <?= htmlspecialchars($r['estado'] ?? '') ?>
                        </td>
                        <td class="text-center"
                            style="background-color: <?= $r['tipoColor'] ?>; color: <?= getTextColor($r['tipoColor']) ?>;">
                            <?= htmlspecialchars($r['Tipo'] ?? '') ?>
                        </td>
                        <td class="text-center"
                            style="background-color: <?= $r['medioColor'] ?>; color: <?= getTextColor($r['medioColor']) ?>;">
                            <?= htmlspecialchars($r['Medio'] ?? '') ?>
                        </td>
                        <td class="text-center client-col">
                            <?= htmlspecialchars(trim(($r['cliNombre'] ?? '') . ' ' . ($r['cliApellido'] ?? ''))) ?>
                        </td>
                        <td class="text-right"><strong><?= fmt($r['subtotal']) ?></strong></td>
                        <td class="text-right"><strong><?= fmt($r['impuesto']) ?></strong></td>
                        <td class="text-right"><strong><?= fmt($r['envio']) ?></strong></td>
                        <td class="text-right"><strong><?= fmt($r['total']) ?></strong></td>
                        <td class="text-right"><strong><?= fmt($r['pagos']) ?></strong></td>
                        <td class="text-right"><strong><?= fmt($r['deducciones']) ?></strong></td>
                        <td class="text-right <?= $cls ?>"><strong><?= fmt($saldo) ?></strong></td>
                        <td class="text-center">
                            <a href="venta.php?id=<?= $r['id'] ?>" class="btn btn-sm btn-primary">Ver</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <tr class="font-weight-bold">
                    <td colspan="10" class="text-right">Totales:</td>
                    <td class="text-right"><strong><?= fmt($sumTotal) ?></strong></td>
                    <td class="text-right"><strong><?= fmt($sumPagos) ?></strong></td>
                    <td class="text-right"><strong><?= fmt($sumDeducciones) ?></strong></td>
                    <td class="text-right"><strong><?= fmt($sumSaldo) ?></strong></td>
                    <td></td> <!-- columna acciones vacía -->
                </tr>
            </tbody>
        </table>
    </div>
</div>
<?php include '../templates/footer.php'; ?>