<?php
// pedido_detalle.php (con columnas de descuento y diseño actualizado)

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
require_once __DIR__ . '/../includes/session_control.php';
require_once __DIR__ . '/../cotizaciones/api/_node.php';

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

$idPedido = isset($_GET['id']) ? intval($_GET['id']) : 0;
if (!$idPedido) die('ID inválido');

$resp = cpn_node_request('GET', $base . '/api/ordenes/pedidos/' . urlencode((string)$idPedido) . '/detalle', $token);
if (!isset($resp['ok']) || $resp['ok'] !== true) {
    http_response_code($resp['_http'] ?? 500);
    die('Error consultando detalle en Node');
}

$items = $resp['data']['items'] ?? [];
$taxList = $resp['data']['impuestos'] ?? [];
?>

<div id="detalle-pedido">
    <table class="table table-bordered table-sm" id="tablaDetalle">
        <thead>
            <tr>
                <th>CPN</th>
                <th class="text-center">K</th>
                <th>RefProv</th>
                <th>Img</th>
                <th>Descripción</th>
                <th class="text-end">Cant</th>
                <th class="text-end">Precio Lista</th>
                <th class="text-end">% Desc</th>
                <th class="text-end">P. Neto<br><small>Escala</small></th>
                <th class="text-end">$ Compra</th>
                <th class="text-end" style="width:30px">% Imp</th>
                <th class="text-end">Vr Unit<br><small>Ant/Des</small></th>
                <th class="text-end">Total<br><small>Ant/Des</small></th>
                <th class="text-end">Stock</th>
                <th>
                    Entregado
                    <button type="button" id="toggleDeliveredAll"
                        class="btn btn-sm btn-outline-secondary ms-2"
                        title="Marcar/Desmarcar todos">✓</button>
                </th>
                <th>Acción</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($items as $r):
                $pct = (float)($r['descuentoPct'] ?? 0);
                $precioLista = (float)($r['precioLista'] ?? ($r['precioCompra'] ?? 0));
                $precioNeto = (float)($r['precioNeto'] ?? 0);
                $diffAlert = !empty($r['diffAlert']);

                $vrTop = (float)($r['vrTop'] ?? ($r['precioCompra'] ?? 0));
                $bot = (float)($r['vrBot'] ?? 0);
                $totTop = (float)($r['totTop'] ?? 0);
                $totBot = (float)($r['totBot'] ?? 0);
            ?>
                <tr data-id="<?= $r['idDetalle'] ?>">
                    <td>
                        <select class="form-select variant-select" data-id="<?= $r['idDetalle'] ?>">
                            <option value="<?= $r['idVariante'] ?>" selected>
                                <?= htmlspecialchars($r['referenciaCPN']) ?>
                            </option>
                        </select>
                    </td>
                    <td class="text-center">
                        <button type="button"
                            class="btn btn-sm btn-primary btn-kardex"
                            data-var-id="<?= $r['idVariante'] ?>">
                            K
                        </button>
                    </td>
                    <td><?= htmlspecialchars($r['referenciaProveedor']) ?></td>
                    <td>
                        <?php if ($r['linkImagen']): ?>
                            <img src="<?= str_ireplace('J:/', 'https://sistema.compranet.com.co/', $r['linkImagen']) ?>"
                                style="max-height:40px">
                        <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars($r['producto'] . ' – ' . $r['color']) ?></td>

                    <td class="text-center">
                        <input type="number"
                            class="form-control edit text-end"
                            step="1"
                            data-id="<?= $r['idDetalle'] ?>"
                            data-field="cantidad"
                            value="<?= (int)$r['cantidad'] ?>">
                    </td>

                    <td class="text-end">
                        <?= '$ ' . number_format($precioLista, 0, ',', '.') ?>
                    </td>

                    <td class="text-end <?= $pct > 0 ? 'text-danger' : '' ?>">
                        <?= $pct > 0 ? ($pct * 100) . '%' : '-' ?>
                    </td>

                    <td class="text-end <?= $pct > 0 ? 'text-danger' : '' ?>">
                        <?php if ($pct > 0): ?>
                            <span class="nowrap"><?= '$ ' . number_format($precioNeto, 0, ',', '.') ?></span><br>
                            <small><?= htmlspecialchars((string)($r['descuentoEscalaNombre'] ?? '')) ?></small>

                        <?php else: ?>
                            –
                        <?php endif; ?>
                    </td>

                    <td class="text-end">
                        <div style="white-space: nowrap; display: inline-flex; align-items: center;">
                            <span class="input-group-text">$</span>
                            <input type="number"
                                class="form-control edit text-end"
                                step="1"
                                data-id="<?= $r['idDetalle'] ?>"
                                data-field="precioCompra"
                                value="<?= (int)$r['precioCompra'] ?>">
                            <?php if ($diffAlert): ?>
                                <span class="text-danger ms-1">¡</span>
                            <?php endif; ?>
                        </div>
                    </td>

                    <td class="text-end" style="width:30px">
                        <select class="form-select select-impuesto" style="width:80px" data-id="<?= $r['idDetalle'] ?>">
                            <?php foreach ($taxList as $tax): ?>
                                <option value="<?= $tax['id'] ?>"
                                    data-valor="<?= $tax['valor'] ?>"
                                    <?= $tax['id'] == $r['idImpuesto'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($tax['nombre']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>

                    <td class="text-end unit-col">
                        <div class="before-tax">
                            <?= '$ ' . number_format($vrTop, 0, ',', '.') ?>
                        </div>
                        <div class="after-tax">
                            <?= '$ ' . number_format($bot, 0, ',', '.') ?>
                        </div>
                    </td>

                    <td class="text-end total-col">
                        <div class="before-tax">
                            <?= '$ ' . number_format($totTop, 0, ',', '.') ?>
                        </div>
                        <div class="after-tax">
                            <?= '$ ' . number_format($totBot, 0, ',', '.') ?>
                        </div>
                    </td>

                    <td class="text-end"><?= $r['inventario'] ?></td>
                    <td class="text-center">
                        <input type="checkbox"
                            class="delivered"
                            data-id="<?= $r['idDetalle'] ?>"
                            <?= $r['entregado'] ? 'checked' : '' ?>>
                    </td>
                    <td class="text-center">
                        <button class="btn btn-sm btn-danger remove-item"
                            data-id="<?= $r['idDetalle'] ?>">×</button>
                    </td>
                </tr>
            <?php endforeach; ?>
            <tr>
                <td><select id="new-variant" class="form-select variant-select"></select></td>
                <td colspan="14"></td>
            </tr>
        </tbody>
    </table>
</div>

<script>
    document.getElementById('toggleDeliveredAll').addEventListener('click', function() {
        const all = document.querySelectorAll('#tablaDetalle .delivered');
        const toCheck = Array.from(all).some(ch => !ch.checked);
        all.forEach(ch => ch.checked = toCheck);
        all.forEach(ch => ch.dispatchEvent(new Event('change')));
    });
</script>