<?php
// venta_detalle.php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
require_once __DIR__ . '/../includes/session_control.php';
require_once __DIR__ . '/../cotizaciones/api/_node.php';

$idVenta = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$idVenta) die('ID de venta inválido');

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();
$url = $base . '/api/ventas/ordenes/' . urlencode((string)$idVenta) . '/detalle';
$r = cpn_node_request('GET', $url, $token);

if (!isset($r['ok']) || $r['ok'] !== true) {
    http_response_code($r['_http'] ?? 500);
    die('Error consultando detalle en Node');
}

$data = $r['data'] ?? [];
$items = $data['items'] ?? [];
$services = $data['services'] ?? [];
$serviceTypes = $data['serviceTypes'] ?? [];
$taxList = $data['impuestos'] ?? [];
// pivot servicios
$svByDetalle = [];
foreach ($services as $sv) {
    $svByDetalle[$sv['idVentaDetalle']][$sv['idServicioTipo']] = $sv['precioVentaAntesImpuestos'];
}
?>




<div id="detalle-venta" class="mt-3">

    <div class="table-responsive">
        <table id="detalleventa" class="table table-bordered">
            <thead>
                <tr>
                    <th>CPN</th>
                    <th class="text-center">K</th>
                    <th>Img</th>
                    <th>Descripción</th>

                    <th class="text-end">Cant</th>
                    <th class="text-end">P. Sug</th>
                    <th class="text-end">$ Venta</th>
                    <?php foreach ($serviceTypes as $st): ?>
                        <th class="text-end service-col"><?= htmlspecialchars($st['nombreCol']) ?></th>
                    <?php endforeach; ?>
                    <th>% 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>Acción</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($items as $row):
                    // precio sugerido
                    $ps = ($row['PVPreducidoantesImpuestos'] && $row['PVPreducidoantesImpuestos'] > 0)
                        ? min($row['PVPantesImpuestos'], $row['PVPreducidoantesImpuestos'])
                        : $row['PVPantesImpuestos'];
                    // suma servicios
                    $sumSv = array_sum($svByDetalle[$row['idVentaDetalle']] ?? []);
                    $vrTop = $row['precioVenta'] + $sumSv;

                    $ivaUnitario = round($vrTop * $row['porcentajeImpuesto'], 2);
                    $vrBot = round($vrTop + $ivaUnitario, 2);

                    $totTop = round($vrTop * $row['cantidad'], 2);
                    $totIVA = round($ivaUnitario * $row['cantidad'], 2);
                    $totBot = round($vrBot * $row['cantidad'], 2);
                ?>
                    <tr data-id="<?= $row['idVentaDetalle'] ?>" data-minventa="<?= (int)($row['minVenta'] ?? 1) ?>" data-multiplo="<?= (int)($row['multiploVenta'] ?? 1) ?>">
                        <!-- Cod -->
                        <td>
                            <select class="form-select variant-select" data-id="<?= $row['idVentaDetalle'] ?>">
                                <option value="<?= $row['idVariante'] ?>" selected><?= $row['referenciaCPN'] ?></option>
                            </select>
                        </td>
                        <td class="text-center">
                            <button type="button"
                                class="btn btn-sm btn-primary btn-kardex"
                                data-var-id="<?= $row['idVariante'] ?>">
                                K
                            </button>
                        </td>
                        <!-- Img -->
                        <td>
                            <?php
                            $link = str_ireplace('J:/', 'https://sistema.compranet.com.co/', $row['linkImagen']);
                            ?>
                            <img src="<?= $link ?>" alt="">
                        </td>
                        <!-- Desc -->
                        <!-- Descripción y color juntos -->
                        <td>
                            <?= htmlspecialchars($row['nombre'] . ' – ' . $row['color']) ?>
                        </td>

                        <!-- Cant -->
                        <td class="text-end qty-col">
                            <input type="number" class="form-control edit" step="1"
                                data-field="cantidad" value="<?= (int)$row['cantidad'] ?>"
                                data-id="<?= $row['idVentaDetalle'] ?>">
                        </td>
                        <!-- P. Sug -->
                        <td class="text-end nowrap-col"><?= '$ ' . number_format($ps, 0, ',', '.') ?></td>
                        <!-- VR Prod -->
                        <td class="text-end">
                            <input type="number" class="form-control edit text-end" step="1"
                                data-field="precioVentaAntesImpuestos"
                                value="<?= (int)$row['precioVenta'] ?>"
                                data-id="<?= $row['idVentaDetalle'] ?>">
                        </td>
                        <!-- Servicios -->
                        <?php foreach ($serviceTypes as $st):
                            $sv = $svByDetalle[$row['idVentaDetalle']][$st['id']] ?? 0;
                        ?>
                            <td class="text-end service-col">
                                <?php if ($sv): ?>
                                    <div class="service-val">
                                        <?= '$ ' . number_format($sv, 0, ',', '.') ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                        <?php endforeach; ?>

                        <!-- Imp -->
                        <td class="imp-col">
                            <select class="form-select select-impuesto"
                                data-id="<?= $row['idVentaDetalle'] ?>">
                                <?php foreach ($taxList as $tax): ?>
                                    <option
                                        value="<?= $tax['id'] ?>"
                                        data-valor="<?= $tax['valor'] ?>"
                                        <?= $tax['id'] == $row['idImpuesto'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($tax['nombre']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                        <!-- Vr Unit -->
                        <td class="text-end unit-col">
                            <div class="before-tax"><?= '$ ' . number_format($vrTop, 0, ',', '.') ?></div>
                            <div class="after-tax"><?= '$ ' . number_format($vrBot, 0, ',', '.') ?></div>
                        </td>
                        <!-- Total -->
                        <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>
                        <!-- Stock -->
                        <td class="text-end"><?= $row['inventario'] ?></td>
                        <!-- Acción -->
                        <td class="text-center">
                            <button type="button" class="btn btn-sm btn-success add-service" data-id="<?= $row['idVentaDetalle'] ?>" data-bs-toggle="modal" data-bs-target="#serviceModal" onclick="if(window.openVentaServiceModal){window.openVentaServiceModal(<?= (int)$row['idVentaDetalle'] ?>);} return false;">+</button>
                            <button class="btn btn-sm btn-danger remove-item" data-id="<?= $row['idVentaDetalle'] ?>">×</button>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <tr id="new-item-row">
                    <!-- Cod: select2 vacío, sin data-id -->
                    <td>
                        <select id="new-variant" class="form-select variant-select"></select>
                    </td>
                    <!-- El resto de columnas en blanco -->
                    <td colspan="<?= 11 + count($serviceTypes) ?>"></td>
                </tr>

            </tbody>
        </table>
    </div>
</div>
