<?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();

// — POST AJAX: actualización inline de campos generales —
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'update_field') {
    header('Content-Type: application/json');
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    $field = (string)($_POST['field'] ?? '');
    $value = $_POST['value'] ?? '';

    $r = cpn_node_request('PATCH', $base . '/api/ordenes/pedidos/' . urlencode((string)$id), $token, [
        'field' => $field,
        'value' => $value,
    ]);
    if (!isset($r['ok']) || $r['ok'] !== true) {
        $msg = $r['error']['message'] ?? 'Error actualizando pedido.';
        echo json_encode(['success' => false, 'error' => $msg]);
        exit;
    }

    echo json_encode(['success' => true]);
    exit;
}

// — Datos generales del pedido —
$idPedido = isset($_GET['id']) ? intval($_GET['id']) : 0;
if (!$idPedido) die('ID de pedido inválido');

$pedidoResp = cpn_node_request('GET', $base . '/api/ordenes/pedidos/' . urlencode((string)$idPedido), $token);
if (!isset($pedidoResp['ok']) || $pedidoResp['ok'] !== true) {
    http_response_code($pedidoResp['_http'] ?? 500);
    die('Error consultando pedido en Node');
}
$pedido = $pedidoResp['data'] ?? [];

$metaResp = cpn_node_request('GET', $base . '/api/ordenes/pedidos/meta', $token);
if (!isset($metaResp['ok']) || $metaResp['ok'] !== true) {
    http_response_code($metaResp['_http'] ?? 500);
    die('Error consultando meta de pedidos en Node');
}
$meta = $metaResp['data'] ?? [];
$lstProveedores = $meta['proveedoresAreas'] ?? [];
$lstEstados = $meta['estados'] ?? [];
$lstEmpresas = $meta['empresas'] ?? [];

// Función para contraste
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 ? '#000' : '#fff';
}
?>
<?php include '../templates/header.php'; ?>

<div class="pedido-container">
    <h1 class="h3 mb-4 text-gray-800">Pedido No. <?= $pedido['id'] ?></h1>

    <!-- PRIMERA FILA: Información general + Resumen -->
    <div class="row align-items-start">
        <div class="col-lg-9">
            <div class="mb-4">
                <div class="form-row">
                    <div class="form-group col-md-2">
                        <label>Fecha</label>
                        <input type="date" name="fechaSolicitud" id="inpFecha"
                            class="form-control"
                            value="<?= !empty($pedido['fechaSolicitud']) ? date('Y-m-d', strtotime($pedido['fechaSolicitud'])) : '' ?>">
                    </div>

                    <!-- ======== Nuevo SELECT “Empresa” ======== -->
                    <div class="form-group col-md-1">
                        <label>Empresa</label>
                        <select name="idEmpresa" id="selEmpresa" class="form-control"
                            style="background-color: <?= htmlspecialchars((string)($pedido['EmpresaColor'] ?? '#fff')) ?>;
                   color: <?= getTextColor((string)($pedido['EmpresaColor'] ?? '#ffffff')) ?>;">
                            <option value="">Seleccione Empresa…</option>
                            <?php foreach ($lstEmpresas as $e):
                                $eid = (int)($e['id'] ?? 0);
                                $sel2 = ($eid && $eid == (int)($pedido['idEmpresa'] ?? 0)) ? 'selected' : '';
                                $col = (string)($e['colorHexa'] ?? '#ffffff');
                            ?>
                                <option value="<?= $eid ?>" <?= $sel2 ?>
                                    style="background-color: <?= htmlspecialchars($col) ?>;
                           color: <?= getTextColor($col) ?>;">
                                    <?= htmlspecialchars((string)($e['sigla'] ?? '')) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <!-- ======== FIN SELECT “Empresa” ======== -->

                    <div class="form-group col-md-3">
                        <label>Proveedor</label>
                        <select name="idProveedorArea" id="selProv" class="form-control">
                            <?php foreach ($lstProveedores as $r):
                                $pid = (int)($r['id'] ?? 0);
                                $text = (string)($r['text'] ?? '');
                                $sel = ($pid && $pid == (int)($pedido['idProveedorArea'] ?? 0)) ? 'selected' : '';
                            ?>
                                <option value="<?= $pid ?>" <?= $sel ?>><?= htmlspecialchars($text) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group col-md-2">
                        <label>Estado</label>
                        <select name="idEstadoOrden" id="selEstado" class="form-control"
                            style="background:<?= htmlspecialchars((string)($pedido['EstadoColor'] ?? '')) ?>;
                   color:<?= getTextColor((string)($pedido['EstadoColor'] ?? '')) ?>">
                            <?php foreach ($lstEstados as $e2):
                                $eid2 = (int)($e2['id'] ?? 0);
                                $sel3 = ($eid2 && $eid2 == (int)($pedido['idEstadoOrden'] ?? 0)) ? 'selected' : '';
                            ?>
                                <option value="<?= $eid2 ?>" <?= $sel3 ?>>
                                    <?= htmlspecialchars((string)($e2['nombre'] ?? '')) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group col-md-2">
                        <label>Fecha Factura</label>
                        <input type="date" name="fechaFactura" id="inpFechaFac" class="form-control"
                            value="<?= (!empty($pedido['fechaFactura']) && $pedido['fechaFactura'] !== '1899-12-30 00:00:00')
                                        ? date('Y-m-d', strtotime($pedido['fechaFactura']))
                                        : '' ?>">
                    </div>
                    <div class="form-group col-md-2">
                        <label>Fecha Vencimiento</label>
                        <input type="date" name="fechaVencimiento" id="inpFechaVen" class="form-control"
                            value="<?= (!empty($pedido['fechaVencimiento']) && $pedido['fechaVencimiento'] !== '1899-12-30 00:00:00')
                                        ? date('Y-m-d', strtotime($pedido['fechaVencimiento']))
                                        : '' ?>">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group col-md-2">
                        <label>Prefijo</label>
                        <input type="text" name="prefijoFactura" id="inpPref" class="form-control"
                            value="<?= htmlspecialchars($pedido['prefijoFactura']) ?>">
                    </div>
                    <div class="form-group col-md-2">
                        <label>No. Factura</label>
                        <input type="text" name="noFactura" id="inpNoFac" class="form-control"
                            value="<?= htmlspecialchars($pedido['noFactura']) ?>">
                    </div>
                    <div class="form-group col-md-4 d-flex align-items-end justify-content-between">
                        <div style="flex: 1; margin-right: 0.5rem;">
                            <label>Siigo ID</label>
                            <input type="text" class="form-control non-edit" id="inpSiigo"
                                value="<?= htmlspecialchars($pedido['siigo_id']) ?>" readonly>
                        </div>
                        <?php
                        $btnText = $pedido['idEstadoOrden'] == 2 ? 'Volver a Enviar' : 'Enviar Pedido';
                        ?>
                        <button id="btnEnviarPedido" class="btn btn-primary btn-sm" style="min-width: 140px; height: 38px;">
                            <?= $btnText ?>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- DERECHA: Resumen -->
        <div class="col-lg-3 align-self-start" id="resumen-container">
            <?php include __DIR__ . '/pedido_resumen.php'; ?>
        </div>
    </div>

    <!-- SEGUNDA FILA: Detalle (full width) -->
    <div class="row">
        <div class="col-12">
            <div id="detalle-container">
                <?php include __DIR__ . '/pedido_detalle.php'; ?>
            </div>
        </div>
    </div>

</div>
<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>

<!-- Modal Enviar Pedido -->
<div class="modal fade" id="enviarModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form id="formEnviarPedido" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Enviar Orden de Compra</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="destino" class="form-label">Para</label>
                    <input type="email" id="destino" class="form-control">
                </div>
                <div class="mb-3">
                    <label for="cco" class="form-label">CCO</label>
                    <input type="email" id="cco" class="form-control" value="ventas@compranet.com.co" readonly>
                </div>
                <div class="mb-3">
                    <label for="asunto" class="form-label">Asunto</label>
                    <input type="text" id="asunto" class="form-control">
                </div>
                <div class="mb-3">
                    <label class="form-label">Adjunto</label><br>
                    <a id="linkPdf" href="#" target="_blank"></a>
                </div>
                <div class="mb-3">
                    <label for="mensaje" class="form-label">Mensaje</label>
                    <textarea id="mensaje" class="form-control" rows="5">Buen Día
Adjunto a la presente remitimos la orden de compra del asunto.
Agradecemos su atención y colaboración
Cordialmente,

COMPRANET COMERCIO ELECTRONICO S.A.S.

PBX: (1) 758 7999
Bogota D.C. – Colombia
Pagina Web: http://www.compranet.com.co
No imprima este correo a menos que sea absolutamente necesario. El medio ambiente es responsabilidad de todos</textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <button type="submit" class="btn btn-primary">Enviar</button>
            </div>
        </form>
    </div>
</div>

<!-- Modal Deducciones -->
<div class="modal fade" id="modalDeds" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content p-3">
            <h5 class="mb-3">Deducciones</h5>
            <table id="tablaDeds" class="table table-sm table-bordered mb-3">
                <thead>
                    <tr>
                        <th>Concepto</th>
                        <th class="text-end">% </th>
                        <th class="text-end">Valor</th>
                        <th>×</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <hr>
            <div class="mb-2">
                <label>Concepto</label>
                <select id="dedTipo" class="form-select mb-2"></select>
            </div>
            <div class="mb-2">
                <label>% Deducción</label>
                <input type="number" id="dedPct" class="form-control mb-2">
            </div>
            <div class="mb-2">
                <label>Valor</label>
                <input type="number" id="dedVal" class="form-control mb-2">
            </div>
            <div class="text-end">
                <button id="closeDeds" class="btn btn-secondary">Cerrar</button>
                <button id="saveDed" class="btn btn-primary">Guardar</button>
            </div>
        </div>
    </div>
</div>

<!-- Dependencias JS -->
<!-- 1) jQuery primero -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- 2) Bootstrap Bundle desde CDN (incluye Popper y expone global `bootstrap`) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<!-- 3) Select2 -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<!-- ───── SCRIPT UNIFICADO: pedido.js ───── -->
<script>
    /*──────────  CONSTANTES GLOBALES  ──────────*/
    const idPedido = <?= $idPedido ?>;
    const canEdit = <?= ((int)($pedido['idEstadoOrden'] ?? 0) === 6) ? 'false' : 'true' ?>; // ≡ Estado 6 = Cerrada
    const proveedorCorreo = '<?= addslashes((string)($pedido['correoElectronico'] ?? '')) ?>';
    const proveedorArea = '<?= addslashes((string)($pedido['Area'] ?? '')) ?>';

    $(function() {

        /*──────────  INSTANCIAS BOOTSTRAP  ──────────*/
        const dedModal = new bootstrap.Modal($('#modalDeds'));
        const modalEnviar = new bootstrap.Modal($('#enviarModal'));
        const btnEnviar = $('#btnEnviarPedido');

        /*──────────  BLOQUEAR CONTROLES SI NO HAY EDICIÓN  ──────────*/
        if (!canEdit) {
            $('#inpFecha,#selProv,#selEstado,#inpFechaFac,#inpFechaVen,#inpPref,#inpNoFac').prop('disabled', true);
            $('#btnEnviarPedido,#addDedBtn,#saveDed').prop('disabled', true);
        }

        /*──────────  ACTUALIZACIÓN INLINE  ──────────*/
        if (canEdit) {
            $('#inpFecha,#selEmpresa,#selProv,#selEstado,#inpFechaFac,#inpFechaVen,#inpPref,#inpNoFac')
                .on('change', function() {
                    $.post(`pedido.php?id=${idPedido}`, {
                        action: 'update_field',
                        field: this.name, // incluye fechaVencimiento gracias al name del input
                        value: this.value
                    }).always(() => {
                        reloadDetalle();
                        reloadResumen();
                    });
                });
        }

        /*──────────  RECARGA PARCIAL  ──────────*/
        function reloadDetalle() {
            $('#detalle-container').load(`pedido_detalle.php?id=${idPedido} #detalle-pedido`, initDetalle);
        }

        function reloadResumen() {
            $('#resumen-container').load(`pedido_resumen.php?id=${idPedido} #resumen-pedido`, initResumen);
        }

        /*──────────  DETALLE  ──────────*/
        function initDetalle() {

            // si no se puede editar, deshabilita todo y sale
            if (!canEdit) {
                $('#detalle-pedido input, #detalle-pedido select, #detalle-pedido button:not(.btn-kardex), #new-variant')
                    .prop('disabled', true);
                return;
            }

            const $vars = $('#detalle-pedido .variant-select');

            // destruir select2 anteriores
            $vars.each(function() {
                if ($(this).hasClass('select2-hidden-accessible')) {
                    $(this).select2('destroy').next('.select2').remove();
                }
            });

            // volver a crear select2
            $vars.select2({
                    ajax: {
                        url: '../productos/producto_search.php',
                        dataType: 'json',
                        delay: 250,
                        data: p => ({
                            q: p.term
                        }),
                        processResults: d => ({
                            results: d.results
                        })
                    },
                    placeholder: 'Variante…',
                    minimumInputLength: 2,
                    width: '100%'
                })
                .off('select2:select')
                .on('select2:select', function(e) {
                    const idDet = $(this).data('id'),
                        idVar = e.params.data.id;
                    if (idDet) { // update existente
                        $.post('update_pedido_detalle.php', {
                            id: idDet,
                            field: 'idProductoVariante',
                            value: idVar
                        }).always(() => {
                            reloadDetalle();
                            reloadResumen();
                        });
                    } else { // agregar nuevo
                        $.post('add_pedido_item.php', {
                                idPedido,
                                idProductoVariante: idVar
                            })
                            .done(() => {
                                reloadDetalle();
                                reloadResumen();
                            });
                    }
                });

            // inline edits (cantidad / precioCompra / etc.)
            $('#detalle-pedido').off('change', '.edit').on('change', '.edit', function() {
                $.post('update_pedido_detalle.php', {
                    id: $(this).data('id'),
                    field: $(this).data('field'),
                    value: this.value
                }).always(() => {
                    reloadDetalle();
                    reloadResumen();
                });
            });

            // cambio de impuesto
            $('#detalle-pedido').off('change', '.select-impuesto').on('change', '.select-impuesto', function() {
                const idDet = this.dataset.id;
                const frac = parseFloat($(this).find('option:selected').data('valor')); // 0.x
                const pct = frac * 100;

                $.post('update_pedido_detalle.php', {
                    id: idDet,
                    field: 'idImpuesto',
                    value: this.value
                });
                $.post('update_pedido_detalle.php', {
                        id: idDet,
                        field: 'porcentajeImpuesto',
                        value: pct
                    })
                    .always(() => {
                        reloadDetalle();
                        reloadResumen();
                    });
            });

            // entregado
            $('#detalle-pedido').off('change', '.delivered').on('change', '.delivered', function() {
                $.post('update_pedido_detalle.php', {
                    id: $(this).data('id'),
                    field: 'entregado',
                    value: this.checked ? 1 : 0
                }).always(() => {
                    reloadDetalle();
                    reloadResumen();
                });
            });

            // eliminar ítem
            $('#detalle-pedido').off('click', '.remove-item').on('click', '.remove-item', function() {
                if (!confirm('Eliminar ítem?')) return;
                $.post('delete_pedido_item.php', {
                        id: $(this).data('id')
                    }, null, 'json')
                    .done(resp => {
                        if (!resp || resp.success !== true) {
                            alert(resp?.error || 'No se pudo eliminar el item.');
                        }
                    })
                    .fail(() => alert('No se pudo eliminar el item.'))
                    .always(() => {
                        reloadDetalle();
                        reloadResumen();
                    });
            });
        }

        /*──────────  RESUMEN (DEDUCCIONES)  ──────────*/
        function initResumen() {
            if (!canEdit) {
                $('#addDedBtn').hide();
                return;
            }

            loadDeds();
            $('#addDedBtn').off('click').on('click', () => dedModal.show());
        }

        function loadDeds() {
            $.getJSON('pedido_deducciones_api.php', {
                action: 'list',
                idPedido
            }, data => {
                const $tb = $('#tablaDeds tbody').empty();
                data.forEach(d => {
                    $tb.append(`
                    <tr data-id="${d.id}">
                        <td>${d.nombre}</td>
                        <td class="text-end">${(d.porcentajeDeduccion*100).toFixed(0)}%</td>
                        <td class="text-end">${d.valorDeduccion.toLocaleString('es-CO',{style:'currency',currency:'COP'})}</td>
                        <td><button class="btn btn-sm btn-danger del-ded">×</button></td>
                    </tr>`);
                });
                $.getJSON('pedido_deducciones_api.php', {
                    action: 'listsel'
                }, sel => {
                    let opts = '<option></option>';
                    sel.lista.forEach(o => opts += `<option value="${o.id}">${o.nombre}</option>`);
                    $('#dedTipo').html(opts);
                });
            });
        }

        // guardar deducción
        $('#saveDed').on('click', () => {
            if (!canEdit) return;
            const tipo = $('#dedTipo').val(),
                pct = $('#dedPct').val() / 100,
                val = $('#dedVal').val();
            if (!tipo) return alert('Seleccione deducción');
            $.post('pedido_deducciones_api.php', {
                action: 'add',
                idPedido,
                idDeduccion: tipo,
                porcentajeDeduccion: pct,
                valorDeduccion: val
            }).done(() => {
                dedModal.hide();
                reloadResumen();
            });
        });

        // eliminar deducción
        $(document).on('click', '.del-ded', function() {
            if (!canEdit) return;
            $.post('pedido_deducciones_api.php', {
                    action: 'delete',
                    idRegistro: $(this).closest('tr').data('id')
                })
                .done(() => {
                    loadDeds();
                    reloadResumen();
                });
        });

        // cerrar modal deducciones
        $('#closeDeds').on('click', () => dedModal.hide());

        /*──────────  ENVÍO DE CORREO  (DESHABILITADO SI !canEdit) ──────────*/
        if (canEdit) {
            btnEnviar.on('click', () => {
                btnEnviar.prop('disabled', true).text('Generando PDF…');
                fetch(`generate_pedido_pdf.php?id=${idPedido}`)
                    .then(r => r.json())
                    .then(d => {
                        if (!d.success) throw new Error(d.error || 'Error al generar PDF');
                        $('#destino').val(proveedorCorreo);
                        $('#asunto').val(`Orden de Compra No. ${idPedido} - ${proveedorArea}`);
                        $('#linkPdf').text(d.filename).attr('href', d.url);
                        modalEnviar.show();
                    })
                    .catch(err => alert(err))
                    .finally(() => btnEnviar.prop('disabled', false).text('Enviar Pedido'));
            });

            $('#formEnviarPedido').on('submit', function(e) {
                e.preventDefault();
                $.post('send_pedido_email.php', {
                    id: idPedido,
                    pdf: $('#linkPdf').attr('href'),
                    destino: $('#destino').val(),
                    cco: $('#cco').val(),
                    asunto: $('#asunto').val(),
                    mensaje: $('#mensaje').val()
                }, resp => {
                    if (resp.success) {
                        modalEnviar.hide();
                        location.reload();
                    } else alert(resp.error || 'Error enviando correo');
                }, 'json');
            });
        }

        /*──────────  KARDEX  ──────────*/
        $(document).on('click', '.btn-kardex', function() {
            $('#modalKardex iframe')
                .attr('src', '/productos/kardex_producto.php?id=' + this.dataset.varId);
            new bootstrap.Modal('#modalKardex').show();
        });

        /*──────────  INICIALIZAR VISTAS  ──────────*/
        initDetalle();
        initResumen();
    });
</script>
<!-- ───── FIN DEL SCRIPT ───── -->

<?php include '../templates/footer.php'; ?>