<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
require_once __DIR__ . '/../includes/session_control.php';
require_once __DIR__ . '/../cotizaciones/api/_node.php';

// Solo roles 1, 2, 4
$roleId = isset($_SESSION['user']['roleId']) ? (int)$_SESSION['user']['roleId'] : 0;
$isSuper = isset($_SESSION['user']['isSuper']) && (int)$_SESSION['user']['isSuper'] === 1;
$canSeeContabilidad = $isSuper || in_array($roleId, [1, 2, 4], true);

if (!$canSeeContabilidad) {
    http_response_code(403);
    die('No autorizado');
}

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">Contabilidad - Cartera Ventas</h1>
    <p class="text-muted">Vista de solo lectura para análisis contable</p>

    <?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">
            <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">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>
                </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"><?= htmlspecialchars((string)($r['refExt'] ?? '')) ?></td>
                        <td class="text-center" style="background-color: <?= htmlspecialchars((string)($r['estadoColor'] ?? '')) ?>; color: <?= getTextColor((string)($r['estadoColor'] ?? '#ffffff')) ?>; padding: 2px;">
                            <?= htmlspecialchars((string)($r['estado'] ?? '')) ?>
                        </td>
                        <td class="text-center" style="background-color: <?= htmlspecialchars((string)($r['tipoColor'] ?? '')) ?>; color: <?= getTextColor((string)($r['tipoColor'] ?? '#ffffff')) ?>; padding: 2px;">
                            <?= htmlspecialchars((string)($r['Tipo'] ?? '')) ?>
                        </td>
                        <td class="text-center"><?= htmlspecialchars((string)($r['medio'] ?? '')) ?></td>
                        <td><?= htmlspecialchars(trim((string)($r['cliNombre'] ?? '') . ' ' . (string)($r['cliApellido'] ?? ''))) ?></td>
                        <td class="text-right"><?= fmt($r['subtotal'] ?? 0) ?></td>
                        <td class="text-right"><?= fmt($r['impuesto'] ?? 0) ?></td>
                        <td class="text-right"><?= fmt($r['envio'] ?? 0) ?></td>
                        <td class="text-right"><strong><?= fmt($r['total'] ?? 0) ?></strong></td>
                        <td class="text-right"><?= fmt($r['pagos'] ?? 0) ?></td>
                        <td class="text-right"><?= fmt($r['deducciones'] ?? 0) ?></td>
                        <td class="text-right <?= $cls ?>"><strong><?= fmt($saldo) ?></strong></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot class="thead-light">
                <tr>
                    <th colspan="10" class="text-right">Totales</th>
                    <th class="text-right"><strong><?= fmt($sumTotal) ?></strong></th>
                    <th class="text-right"><?= fmt($sumPagos) ?></th>
                    <th class="text-right"><?= fmt($sumDeducciones) ?></th>
                    <th class="text-right"><strong><?= fmt($sumSaldo) ?></strong></th>
                </tr>
            </tfoot>
        </table>
    </div>

</div>
<?php include '../templates/footer.php'; ?>