<?php
session_start();
include '../includes/session_control.php';
require_once '../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';
}

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

$r = cpn_node_request('GET', $base . '/api/productos/inventario-local', $token, null);
if (empty($r['ok'])) {
    echo 'No se pudo cargar Inventario Local.';
    exit;
}

$neg = $r['data']['neg'] ?? [];
$pos = $r['data']['pos'] ?? [];
$sumNeg = $r['data']['sumNeg'] ?? ['subtotal' => 0, 'iva' => 0, 'total' => 0];
$sumPos = $r['data']['sumPos'] ?? ['subtotal' => 0, 'iva' => 0, 'total' => 0];
?>
<?php include '../templates/header.php'; ?>

<style>
    /* Compacto (solo esta pantalla) */
    #content .container-fluid .table {
        font-size: 12px;
    }

    #content .container-fluid .table th,
    #content .container-fluid .table td {
        padding: .25rem .35rem;
        line-height: 1.15;
        vertical-align: middle;
    }

    #content .container-fluid .btn {
        font-size: 12px;
        padding: .2rem .45rem;
    }

    #content .container-fluid h1.h3,
    #content .container-fluid .h3 {
        font-size: 1.1rem;
    }

    #content .container-fluid h2 {
        font-size: 1rem;
        margin-bottom: .75rem;
    }
</style>

<div class="container-fluid inventario-local-container">
    <h1 class="h3 mb-4 text-gray-800">Inventario Local</h1>

    <?php if (count($neg)): ?>
        <h2 class="mb-3">Inventario por Solicitar</h2>
        <div class="table-responsive mb-5">
            <table class="table table-sm table-bordered">
                <thead>
                    <tr>
                        <th style="text-align:center;">ID</th>
                        <th style="text-align:center;">CPN</th>
                        <th style="text-align:center;">Proveedor</th>
                        <th style="text-align:center; font-size:0.8rem;">ref Proveedor</th>
                        <th style="text-align:center; width:40px; padding:0;">K</th>
                        <th>Imagen</th>
                        <th style="text-align:center;">Producto</th>
                        <th class="text-center">Compra</th>
                        <th class="text-center">Ventas</th>
                        <th class="text-center">Inv.</th>
                        <th class="text-right">Precio Neto</th>
                        <th class="text-right">Subtotal</th>
                        <th class="text-right">IVA</th>
                        <th class="text-right">Total</th>
                        <th class="text-center">Stock Prov.</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($neg as $m): ?>
                        <tr>
                            <td style="text-align:center;"><?= $m['idVariante'] ?></td>
                            <td style="text-align:center;"><?= htmlspecialchars($m['CPN']) ?></td>
                            <td style="text-align:center;"><?= htmlspecialchars($m['Proveedor']) ?></td>
                            <td style="text-align:center;"><?= htmlspecialchars($m['refProveedor']) ?></td>
                            <td class="text-center">
                                <button class="btn btn-sm btn-primary"
                                    data-bs-toggle="modal" data-bs-target="#kModal"
                                    data-id="<?= $m['idVariante'] ?>">K</button>
                            </td>
                            <td class="text-center">
                                <?php if ($m['linkImagen']): ?>
                                    <img src="<?= str_replace(['J:/', 'j:/'], 'https://sistema.compranet.com.co/', $m['linkImagen']) ?>"
                                        style="height:80px;">
                                <?php endif; ?>
                            </td>
                            <td><?= htmlspecialchars($m['Nombre'] . ' – ' . $m['ColorHex']) ?></td>
                            <td class="text-center"><?= number_format($m['total_compras'], 0, ',', '.') ?></td>
                            <td class="text-center"><?= number_format($m['total_ventas'], 0, ',', '.') ?></td>
                            <td class="text-center saldo-cell"><?= number_format($m['saldoLocal'], 0, ',', '.') ?></td>
                            <td class="text-right">$ <?= number_format($m['precioNeto'], 0, ',', '.') ?></td>
                            <td class="text-right">$ <?= number_format($m['subtotal'], 0, ',', '.') ?></td>
                            <td class="text-right">$ <?= number_format($m['iva'], 0, ',', '.') ?></td>
                            <td class="text-right">$ <?= number_format($m['total'], 0, ',', '.') ?></td>
                            <td class="text-center"><?= number_format($m['stockProveedor'], 0, ',', '.') ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="12" class="text-right">Totales:</th>
                        <th class="text-right">$ <?= number_format($sumNeg['subtotal'], 0, ',', '.') ?></th>
                        <th class="text-right">$ <?= number_format($sumNeg['iva'], 0, ',', '.') ?></th>
                        <th class="text-right">$ <?= number_format($sumNeg['total'], 0, ',', '.') ?></th>
                        <th></th>
                    </tr>
                </tfoot>
            </table>
        </div>
    <?php endif; ?>

    <?php if (count($pos)): ?>
        <h2 class="mb-3">Inventario en Bodega</h2>
        <div class="table-responsive mb-5">
            <table class="table table-sm table-bordered">
                <thead>
                    <tr>
                        <th style="text-align:center;">ID</th>
                        <th style="text-align:center;">CPN</th>
                        <th style="text-align:center;">Proveedor</th>
                        <th style="text-align:center; font-size:0.8rem;">ref Proveedor</th>
                        <th style="text-align:center; width:40px; padding:0;">K</th>
                        <th>Imagen</th>

                        <th>Producto</th>
                        <th class="text-center">Compra</th>
                        <th class="text-center">Ventas</th>
                        <th class="text-center">Inv.</th>
                        <th class="text-right">Precio Neto</th>
                        <th class="text-right">Subtotal</th>
                        <th class="text-right">IVA</th>
                        <th class="text-right">Total</th>
                        <th class="text-center">Stock Prov.</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($pos as $m): ?>
                        <tr>
                            <td style="text-align:center;"><?= $m['idVariante'] ?></td>
                            <td style="text-align:center;"><?= htmlspecialchars($m['CPN']) ?></td>
                            <td style="text-align:center;"><?= htmlspecialchars($m['Proveedor']) ?></td>
                            <td style="text-align:center;"><?= htmlspecialchars($m['refProveedor']) ?></td>
                            <td class="text-center">
                                <button class="btn btn-sm btn-primary"
                                    data-bs-toggle="modal" data-bs-target="#kModal"
                                    data-id="<?= $m['idVariante'] ?>">K</button>
                            </td>
                            <td class="text-center">
                                <?php if ($m['linkImagen']): ?>
                                    <img src="<?= str_replace(['J:/', 'j:/'], 'https://sistema.compranet.com.co/', $m['linkImagen']) ?>"
                                        style="height:80px;">
                                <?php endif; ?>
                            </td>
                            <td><?= htmlspecialchars($m['Nombre'] . ' – ' . $m['ColorHex']) ?></td>
                            <td class="text-center"><?= number_format($m['total_compras'], 0, ',', '.') ?></td>
                            <td class="text-center"><?= number_format($m['total_ventas'], 0, ',', '.') ?></td>
                            <td class="text-center saldo-cell"><?= number_format($m['saldoLocal'], 0, ',', '.') ?></td>
                            <td class="text-right">$ <?= number_format($m['precioNeto'], 0, ',', '.') ?></td>
                            <td class="text-right">$ <?= number_format($m['subtotal'], 0, ',', '.') ?></td>
                            <td class="text-right">$ <?= number_format($m['iva'], 0, ',', '.') ?></td>
                            <td class="text-right">$ <?= number_format($m['total'], 0, ',', '.') ?></td>
                            <td class="text-center"><?= number_format($m['stockProveedor'], 0, ',', '.') ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="12" class="text-right">Totales:</th>
                        <th class="text-right">$ <?= number_format($sumPos['subtotal'], 0, ',', '.') ?></th>
                        <th class="text-right">$ <?= number_format($sumPos['iva'], 0, ',', '.') ?></th>
                        <th class="text-right">$ <?= number_format($sumPos['total'], 0, ',', '.') ?></th>
                        <th></th>
                    </tr>
                </tfoot>
            </table>
        </div>
    <?php endif; ?>
</div>

<!-- Modal Kardex -->
<div class="modal fade" id="kModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Kardex</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-0">
                <iframe id="kModalIframe" src="" style="width:100%;height:600px;border:none;"></iframe>
            </div>
        </div>
    </div>
</div>
<script>
    document.getElementById('kModal').addEventListener('show.bs.modal', e => {
        const id = e.relatedTarget.getAttribute('data-id');
        document.getElementById('kModalIframe').src = '/productos/kardex_producto.php?id=' + id;
    });
</script>
<?php include '../templates/footer.php'; ?>