<?php
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();

// 1) PROCESAR “Solicitar” (crear orden)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'solicitar') {
    $idProveedorArea = intval($_POST['solicit_area']);

    $items = [];
    foreach (($_POST['items'] ?? []) as $idx => $varianteId) {
        $items[] = [
            'idProductoVariante' => intval($varianteId),
            'cantidad' => intval($_POST['qty'][$idx] ?? 0),
            'precioCompra' => floatval($_POST['price'][$idx] ?? 0),
            'porcentajeImpuesto' => floatval($_POST['tax'][$idx] ?? 0),
        ];
    }

    $r = cpn_node_request('POST', $base . '/api/ordenes/pedidos/por-solicitar', $token, [
        'idProveedorArea' => $idProveedorArea,
        'items' => $items,
    ]);
    if (!isset($r['ok']) || $r['ok'] !== true) {
        $msg = $r['error']['message'] ?? 'No se pudo generar la orden de compra';
        // Fallback simple (no pantalla en blanco)
        include '../templates/header.php';
        echo '<div class="container-fluid"><div class="alert alert-danger">' . htmlspecialchars($msg) . '</div></div>';
        include '../templates/footer.php';
        exit;
    }

    $idOrden = intval($r['data']['id'] ?? 0);
    header("Location: pedido.php?id=$idOrden");
    exit;
}

// 2) Cargar data desde Node (Node es la única capa DB)
$datosResp = cpn_node_request('GET', $base . '/api/ordenes/pedidos/por-solicitar', $token, null);
$proveedores = [];
if (isset($datosResp['ok']) && $datosResp['ok'] === true) {
    $proveedores = $datosResp['data']['proveedores'] ?? [];
}

include '../templates/header.php';
?>

<div class="container-fluid pedidos-por-solicitar">
    <h1 class="h3 mb-4 text-gray-800">Pedidos por solicitar</h1>

    <?php foreach ($proveedores as $prov):
        $provId = intval($prov['id'] ?? 0);
    ?>
        <div class="mb-5 proveedor-seccion">
            <div class="d-flex align-items-center mb-2 proveedor-header border-bottom pb-2">
                <h3 class="mb-0 text-primary fw-bold fs-4">
                    <?= htmlspecialchars($prov['nombre'] ?? '') ?>
                </h3>
                <button class="btn btn-primary btn-sm btn-solicitar ms-4"
                    data-prov="<?= $provId ?>">
                    Solicitar
                </button>
            </div>

            <table class="table table-sm table-bordered">
                <thead>
                    <tr>
                        <th><input type="checkbox" class="check-all" checked></th>
                        <th class="text-center">Img</th>
                        <th class="text-center">CPN</th>
                        <th class="text-center">K</th>
                        <th class="text-center">RefProv</th>
                        <th>Producto</th>
                        <th class="text-center bg-secondary text-white fw-bold">Und</th>

                        <!-- NUEVAS COLUMNAS -->
                        <th class="text-right">Precio Lista</th>
                        <th class="text-right">% Desc</th>
                        <th class="text-right">Precio</th>

                        <th class="text-right">Subtotal</th>
                        <th class="text-right">Total</th>
                        <th class="text-right">Bodega</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach (($prov['items'] ?? []) as $it):
                        $pct = floatval($it['descuentoPct'] ?? 0);
                        $precioLista = floatval($it['precioLista'] ?? ($it['precioCompra'] ?? 0));
                        $precioFinal = floatval($it['precioFinal'] ?? ($it['precioNeto'] ?? 0));
                        $qty = intval($it['cantidad'] ?? 0);
                    ?>
                        <tr data-prov="<?= $provId ?>"
                            data-var="<?= intval($it['variante_id'] ?? 0) ?>"
                            data-qty="<?= $qty ?>"
                            data-price="<?= $precioFinal ?>"
                            data-tax="<?= floatval($it['porcentajeImpuesto'] ?? 0) ?>">
                            <td><input type="checkbox" class="row-check" checked></td>
                            <td class="text-center">
                                <?php if (!empty($it['linkImagen'])): ?>
                                    <img src="<?= str_ireplace(['J:/', 'j:/'], ['https://sistema.compranet.com.co/', 'https://sistema.compranet.com.co/'], $it['linkImagen']) ?>"
                                        style="height:60px">
                                <?php endif; ?>
                            </td>
                            <td class="text-center"><?= htmlspecialchars($it['referenciaCPN'] ?? '') ?></td>
                            <td class="text-center">
                                <button type="button"
                                    class="btn btn-sm btn-primary btn-kardex"
                                    data-var-id="<?= intval($it['variante_id'] ?? 0) ?>">
                                    K
                                </button>
                            </td>
                            <td class="text-center"><?= htmlspecialchars($it['referenciaProveedor'] ?? '') ?></td>
                            <td><?= htmlspecialchars(($it['producto_nombre'] ?? '') . ' – ' . ($it['variante_color'] ?? '')) ?></td>
                            <td class="text-center bg-secondary text-white fw-bold">
                                <?= $qty ?>
                            </td>

                            <!-- Precio Lista -->
                            <td class="text-right">
                                <?= '$ ' . number_format($precioLista, 0, ',', '.') ?>
                            </td>
                            <!-- % Desc -->
                            <td class="text-right <?= $pct > 0 ? 'text-danger' : '' ?>">
                                <?= $pct > 0 ? round($pct * 100) . '%' : '-' ?>
                            </td>
                            <!-- Precio (final) -->
                            <td class="text-right <?= $pct > 0 ? 'text-danger' : '' ?>">
                                <?= '$ ' . number_format($precioFinal, 0, ',', '.') ?>
                            </td>

                            <td class="text-right subtotal-cell">0</td>
                            <td class="text-right total-cell">0</td>
                            <td class="text-center"><?= htmlspecialchars($it['Bodega'] ?? '') ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endforeach; ?>
</div>

<!-- Modal Solicitar -->
<div class="modal fade" id="modalSolicitar" tabindex="-1">
    <div class="modal-dialog">
        <form method="post" class="modal-content">
            <input type="hidden" name="action" value="solicitar">
            <input type="hidden" name="solicit_proveedor" id="solicitProveedor">
            <div class="modal-header">
                <h5 class="modal-title">Confirmar pedido</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label>Área de proveedor</label>
                    <select name="solicit_area" id="solicitArea" class="form-control" required></select>
                </div>
                <h6>Resumen:</h6>
                <ul id="resumenItems"></ul>
                <p><strong>Subtotal:</strong> <span id="resModalSub">0.00</span></p>
                <p><strong>Total con IVA:</strong> <span id="resModalTot">0.00</span></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <button type="submit" class="btn btn-success">Generar Orden de Compra</button>
            </div>
        </form>
    </div>
</div>

<!-- Modal Kardex -->
<div class="modal fade" id="modalKardex" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Kardex Producto</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-0">
                <iframe src="" frameborder="0" style="width:100%;height:80vh;"></iframe>
            </div>
        </div>
    </div>
</div>

<?php include '../templates/footer.php'; ?>

<script>
    $(function() {
        // Al hacer click en "Solicitar"
        $('.btn-solicitar').on('click', function() {
            const provId = $(this).data('prov');
            const $modal = $('#modalSolicitar');
            const $form = $modal.find('form');

            $('#solicitProveedor').val(provId);
            $('#solicitArea').empty();
            $form.find('input[name="items[]"],input[name="qty[]"],input[name="price[]"],input[name="tax[]"]').remove();
            $('#resumenItems').empty();

            // Cargo áreas
            $.getJSON('get_areas.php', {
                proveedor: provId
            }, areas => {
                areas.forEach(a => {
                    $('#solicitArea').append(
                        `<option value="${a.id}">${a.nombreArea}</option>`
                    );
                });
            });

            let sub = 0,
                tot = 0;
            $(`tr[data-prov="${provId}"]`).each(function() {
                const $tr = $(this);
                if (!$tr.find('.row-check').is(':checked')) return;

                const varId = $tr.data('var'),
                    qty = +$tr.data('qty'),
                    price = +$tr.data('price'),
                    tax = +$tr.data('tax'),
                    subr = qty * price,
                    totr = subr * (1 + tax);

                sub += subr;
                tot += totr;

                // resumen
                $('#resumenItems').append(
                    `<li>${$tr.find('td').eq(4).text()} x${qty} @ $${price.toLocaleString('es-CO')}</li>`
                );

                // inputs hidden
                $form.append(`<input type="hidden" name="items[]" value="${varId}">`);
                $form.append(`<input type="hidden" name="qty[]"   value="${qty}">`);
                $form.append(`<input type="hidden" name="price[]" value="${price}">`);
                $form.append(`<input type="hidden" name="tax[]"   value="${tax}">`);

                // actualizo celdas subtotal/total
                $tr.find('.subtotal-cell')
                    .text('$ ' + subr.toLocaleString('es-CO'));
                $tr.find('.total-cell')
                    .text('$ ' + totr.toLocaleString('es-CO'));
            });

            $('#resModalSub').text('$ ' + sub.toLocaleString('es-CO'));
            $('#resModalTot').text('$ ' + tot.toLocaleString('es-CO'));

            new bootstrap.Modal($modal[0]).show();
        });

        function recalcSection($sec) {
            $sec.find('tbody tr').each(function() {
                const $tr = $(this);
                const chk = $tr.find('.row-check').is(':checked');
                // si quieres ocultar filas desmarcadas, puedes hacer:
                //          $tr.toggle(chk);

                const qty = +$tr.data('qty');
                const price = +$tr.data('price');
                const tax = +$tr.data('tax');

                const sub = qty * price;
                const tot = sub * (1 + tax);

                $tr.find('.subtotal-cell')
                    .text('$ ' + sub.toLocaleString('es-CO', {
                        minimumFractionDigits: 0
                    }));
                $tr.find('.total-cell')
                    .text('$ ' + tot.toLocaleString('es-CO', {
                        minimumFractionDigits: 0
                    }));
            });
        }

        // 1) Al cargar la página: recálculo inicial
        $('.proveedor-seccion').each(function() {
            recalcSection($(this));
        });

        // 2) Cuando cambie un “check all” o un row-check, recalc esa sección
        $('.check-all').on('change', function() {
            recalcSection($(this).closest('.proveedor-seccion'));
        });
        $('.row-check').on('change', function() {
            recalcSection($(this).closest('.proveedor-seccion'));
        });


        // Kardex
        $('.btn-kardex').on('click', function() {
            $('#modalKardex iframe')
                .attr('src', '/productos/kardex_producto.php?id=' + this.dataset.varId);
            new bootstrap.Modal(document.getElementById('modalKardex')).show();
        });

        // Check-All
        $('.check-all').on('change', function() {
            const c = $(this).is(':checked');
            $(this).closest('table').find('.row-check').prop('checked', c);
        });
    });
</script>
