<?php



// sólo arrancar sesión si aún no hay una
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

include '../includes/session_control.php';
require_once __DIR__ . '/../cotizaciones/api/_node.php';

$base  = cpn_node_api_base();
$token = cpn_node_token_or_fail();

$embed = isset($embed) && $embed;

// detectar si venimos desde una venta
$idVenta      = isset($_GET['idVenta']) ? intval($_GET['idVenta']) : 0;
$isVentaMode  = $idVenta > 0;

/**
 * Formatea un valor monetario: 0 → “-”; otro → “$ 1.234”
 */
function fmt($v)
{
    if ($v == 0) return '-';
    // cambio: en lugar de " " usa "&nbsp;" entre el signo y el número
    return '$&nbsp;' . number_format(abs($v), 0, '', '.');
}
if (!$isVentaMode) {
    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';
    }
}
/*──────────────────────────────  CATÁLOGOS  ─────────────────────────────*/
// Se cargan desde Node (fuente de verdad).

/*────────────────────────────  HANDLERS AJAX  ────────────────────────────*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    $act = $_POST['action'];

    if ($act === 'assignImpresor') {
        $resp = cpn_node_request(
            'POST',
            $base . '/api/marcacion/trabajos/assign-impresor',
            $token,
            [
                'idVentaServicio' => intval($_POST['idVentaServicio'] ?? 0),
                'idImpresor'      => intval($_POST['idImpresor'] ?? 0),
            ]
        );
        exit(json_encode(['success' => ($resp['ok'] ?? false) === true]));
    }

    if ($act === 'createExternal') {
        $resp = cpn_node_request(
            'POST',
            $base . '/api/marcacion/trabajos/create-external',
            $token,
            [
                'idImpresor'      => intval($_POST['idImpresor'] ?? 0),
                'fechaOrden'      => strval($_POST['fechaOrden'] ?? ''),
                'cliente'         => strval($_POST['cliente'] ?? ''),
                'producto'        => strval($_POST['producto'] ?? ''),
                'tipoDeMarca'     => strval($_POST['tipoDeMarca'] ?? ''),
                'cantidad'        => intval($_POST['cantidad'] ?? 0),
                'precioUnitario'  => floatval($_POST['precioUnitario'] ?? 0),
                'idImpuestoVenta' => intval($_POST['idImpuestoVenta'] ?? 0),
                'logo'            => strval($_POST['logo'] ?? ''),
            ]
        );
        exit(json_encode(['success' => ($resp['ok'] ?? false) === true]));
    }

    if ($act === 'updateField') {
        $resp = cpn_node_request(
            'POST',
            $base . '/api/marcacion/trabajos/update-field',
            $token,
            [
                'id'    => intval($_POST['id'] ?? 0),
                'field' => strval($_POST['field'] ?? ''),
                'value' => $_POST['value'] ?? null,
            ]
        );
        exit(json_encode(['success' => ($resp['ok'] ?? false) === true]));
    }

    exit(json_encode(['success' => false]));
}
/*────────────────────────────  DATA (NODE)  ────────────────────────────*/
$viewUrl = $base . '/api/marcacion/trabajos/view' . ($isVentaMode ? ('?idVenta=' . urlencode((string)$idVenta)) : '');
$view = cpn_node_request('GET', $viewUrl, $token);

$catalogos = (($view['ok'] ?? false) === true && isset($view['data']['catalogos']) && is_array($view['data']['catalogos']))
    ? $view['data']['catalogos']
    : [];

$impresores = $catalogos['impresores'] ?? [];
$impuestos  = $catalogos['impuestos'] ?? [];
$empresas   = $catalogos['empresas'] ?? [];
$estados    = $catalogos['estados'] ?? [];
$meses      = $catalogos['meses'] ?? [];

$unassigned    = (($view['ok'] ?? false) === true && is_array($view['data']['unassigned'] ?? null)) ? $view['data']['unassigned'] : [];
$procCompranet = (($view['ok'] ?? false) === true && is_array($view['data']['procCompranet'] ?? null)) ? $view['data']['procCompranet'] : [];
$procKolor     = (($view['ok'] ?? false) === true && is_array($view['data']['procKolor'] ?? null)) ? $view['data']['procKolor'] : [];
$finalCompranet = (($view['ok'] ?? false) === true && is_array($view['data']['finalCompranet'] ?? null)) ? $view['data']['finalCompranet'] : [];
$finalKolor     = (($view['ok'] ?? false) === true && is_array($view['data']['finalKolor'] ?? null)) ? $view['data']['finalKolor'] : [];
?>


<?php if (! $isVentaMode): ?>
    <?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;
        }

        #content .container-fluid .form-control,
        #content .container-fluid .custom-select,
        #content .container-fluid .form-select {
            font-size: 12px !important;
            padding: .2rem .4rem;
            height: calc(1.2em + .5rem + 2px);
        }

        #content .container-fluid .btn {
            font-size: 12px;
            padding: .25rem .5rem;
        }
    </style>
    <div class="container-fluid p-4">
    <?php endif; ?>
    <!--──────────────────  TABLA TRABAJOS POR ASIGNAR  ──────────────────-->
    <h2>Trabajos por Asignar</h2>
    <div class="table-responsive">
        <table class="table table-sm table-bordered" id="tblAsignar">
            <thead>
                <tr>
                    <th>ID Serv</th>
                    <th>No. Orden</th>
                    <th>Fecha</th>
                    <th>Cliente</th>
                    <th>Ref CPN</th>
                    <th>Producto</th>
                    <th>Color</th>
                    <th>Cant</th>
                    <th>Seleccione Impresor</th>
                    <th>Acción</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $lastOrden = null;
                $odd      = false;
                foreach ($unassigned as $r):
                    if ($lastOrden !== $r['NoOrden']) {
                        $odd       = !$odd;
                        $lastOrden = $r['NoOrden'];
                    }
                    $rowClass = $odd ? 'table-active' : '';
                ?>
                    <tr data-idservicio="<?= $r['idServicio'] ?>" class="<?= $rowClass ?>">
                        <td><?= $r['idServicio'] ?></td>
                        <td><?= $r['NoOrden'] ?></td>
                        <td><?= date('d-M-y', strtotime($r['fechaOrden'])) ?></td>
                        <td><?= htmlspecialchars($r['nombre'] . ' ' . $r['apellido']) ?></td>
                        <td><?= htmlspecialchars($r['referenciaCPN']) ?></td>
                        <td><?= htmlspecialchars($r['nombreProducto']) ?></td>
                        <td><?= htmlspecialchars($r['txtColor']) ?></td>
                        <td class="text-right"><?= intval($r['cantidad']) ?></td>
                        <td>
                            <select class="form-select selectImpresor">
                                <option value="" disabled selected>–</option>
                                <?php foreach ($impresores as $imp): ?>
                                    <option value="<?= $imp['id'] ?>"><?= htmlspecialchars($imp['nombre']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                        <td><button class="btn btn-sm btn-primary btn-assign">Agregar</button></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <?php if (! $isVentaMode): ?>
        <!--────────────  BOTÓN + MODAL NUEVO TRABAJO EXTERNO  ────────────-->
        <button class="btn btn-success mb-4" data-bs-toggle="modal" data-bs-target="#modalExternal">
            Crear Trabajo Kolor
        </button>
    <?php endif; ?>
    <div class="modal fade" id="modalExternal" tabindex="-1">
        <div class="modal-dialog">
            <form id="formExternal" class="modal-content">
                <input type="hidden" name="action" value="createExternal">
                <div class="modal-header">
                    <h5 class="modal-title">Nuevo Trabajo Externo</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-2"><label>Impresor</label>
                        <select name="idImpresor" class="form-select" required>
                            <option value="" disabled selected>-- Seleccione impresor --</option>
                            <?php foreach ($impresores as $imp): ?>
                                <option value="<?= $imp['id'] ?>"><?= htmlspecialchars($imp['nombre']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-2"><label>Fecha</label>
                        <input type="date" name="fechaOrden" class="form-control" required>
                    </div>

                    <div class="mb-2"><label>Cliente</label><input name="cliente" class="form-control" required></div>
                    <div class="mb-2"><label>Producto</label><input name="producto" class="form-control" required></div>
                    <div class="mb-2"><label>Logo</label>
                        <input type="text" name="logo" class="form-control" placeholder="nombre del logo a imprimir" required>
                    </div>
                    <div class="mb-2"><label>Tipo de Marca</label><input name="tipoDeMarca" class="form-control" required></div>
                    <div class="mb-2"><label>Cantidad</label><input type="number" name="cantidad" class="form-control form-control-sm w-auto" style="width:auto!important; font-size:0.85rem; padding:0.25rem 0.5rem;" step="1" value="1" required></div>
                    <div class="mb-2"><label>Precio Unitario</label><input type="number" name="precioUnitario" class="form-control form-control-sm w-auto" style="width:auto!important; font-size:0.85rem; padding:0.25rem 0.5rem;" step="1" value="0" required></div>
                    <div class="mb-2"><label>Impuesto</label>
                        <select name="idImpuestoVenta" class="form-select" required>
                            <?php foreach ($impuestos as $imp): ?>
                                <option value="<?= $imp['id'] ?>" data-valor="<?= $imp['valor'] ?>">
                                    <?= htmlspecialchars($imp['nombre']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-2"><strong>Subtotal:</strong> <span id="subt">0</span><br>
                        <strong>Total:&nbsp;&nbsp;</strong> <span id="tot">0</span>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" data-bs-dismiss="modal">Salir</button>
                    <button type="submit" class="btn btn-primary">Guardar</button>
                </div>
            </form>
        </div>
    </div>

    <!--──────────────────────────────  PESTAÑAS  ──────────────────────────-->
    <ul class="nav nav-tabs">
        <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tabProceso">Trabajos en Proceso</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tabFinalCompranet">Finalizados Compranet</a></li>
        <?php if (! $isVentaMode): ?>
            <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tabFinalKolor">Finalizados Kolor</a></li>
        <?php endif; ?>
    </ul>
    <div class="tab-content">
        <!--───────────────────  TAB PROCESO – COMPRANET  ───────────────────-->
        <div id="tabProceso" class="tab-pane fade show active">
            <h4 class="mt-3">Compranet y Kolor (Con ventas)</h4>
            <div class="table-responsive">
                <table class="table table-sm table-bordered">
                    <thead>
                        <!-- Fila 1: cabeceras principales -->
                        <tr>
                            <th rowspan="3">Serv</th>
                            <th rowspan="3">NoFact</th>
                            <th rowspan="3">Fecha</th>
                            <th rowspan="3">Cliente</th>
                            <th rowspan="3">Img</th>
                            <th colspan="1">Producto</th>
                            <th rowspan="3">Logo</th>
                            <th colspan="3">Venta</th>
                            <th class="table-secondary" rowspan="3"></th>
                            <th rowspan="3">Info</th>
                            <th rowspan="3">Fechas</th>
                            <th colspan="3">Servicio</th>
                            <th rowspan="3">Dif</th>
                        </tr>
                        <!-- Fila 2: subcabeceras de cada grupo -->
                        <tr>
                            <th>Producto</th>

                            <th>Cant</th>
                            <th>Precio</th>
                            <th>Total</th>
                            <th>Cant</th>
                            <th>Precio</th>
                            <th>Total</th>
                        </tr>
                        <!-- Fila 3: vacía para compensar los rowspan -->
                        <tr></tr>
                    </thead>


                    <tbody>
                        <?php
                        $lastOrden = null;
                        $odd      = false;
                        foreach ($procCompranet as $r):
                            if ($lastOrden !== $r['NoOrden']) {
                                $odd       = !$odd;
                                $lastOrden = $r['NoOrden'];
                            }
                            $rowClass = $odd ? 'table-active' : '';
                        ?>
                            <tr data-id="<?= $r['id'] ?>" class="<?= $rowClass ?>" style="font-size:0.85rem;">
                                <!-- Serv + Empresa -->
                                <td>
                                    <?= $r['id'] ?><br>
                                    <?php
                                    // Para que el <select> muestre el color de la empresa seleccionada como fondo,
                                    // buscamos el colorHexa de la empresa actual:
                                    $selectedColor = '#ffffff';
                                    foreach ($empresas as $ee) {
                                        if ($ee['id'] == $r['idEmpresa']) {
                                            $selectedColor = $ee['colorHexa'];
                                            break;
                                        }
                                    }
                                    ?>
                                    <select
                                        class="form-select form-select-sm field"
                                        style="
          font-size:0.75rem;
          max-width:5rem;
          background-color: <?= htmlspecialchars($selectedColor) ?>;
          color: <?= getTextColor($selectedColor) ?>;
        "
                                        data-field="idEmpresa">
                                        <?php foreach ($empresas as $e): ?>
                                            <option
                                                value="<?= $e['id'] ?>"
                                                <?= $e['id'] == $r['idEmpresa'] ? 'selected' : '' ?>
                                                style="
                  background-color: <?= htmlspecialchars($e['colorHexa']) ?>;
                  color: <?= getTextColor($e['colorHexa']) ?>;
                ">
                                                <?= htmlspecialchars($e['nombre']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>

                                <!-- NoFact -->
                                <td><?= $r['NoOrden'] ?></td>

                                <!-- Fecha -->
                                <td>
                                    <?php $ventaFecha = $r['ventaFecha'] ?? $r['fechaOrden'] ?? ''; ?>
                                    <input
                                        type="date"
                                        class="form-control form-control-sm"
                                        disabled
                                        value="<?= $ventaFecha ? date('Y-m-d', strtotime($ventaFecha)) : '' ?>">

                                </td>

                                <!-- Cliente -->
                                <td><?= htmlspecialchars($r['cliNombre'] . ' ' . $r['cliApellido']) ?></td>

                                <!-- Img -->
                                <td>
                                    <?php if ($r['linkImagen']): ?>
                                        <img src="<?= str_ireplace(['j:', 'J:'], '//sistema.compranet.com.co', $r['linkImagen']) ?>" width="60">
                                    <?php else: ?>
                                        –
                                    <?php endif; ?>
                                </td>

                                <!-- Producto – Marca -->
                                <td>
                                    <?= htmlspecialchars($r['nombreProducto'] . ' ' . $r['txtColor']) ?><br>
                                    <strong><?= htmlspecialchars($r['tipoMarca']) ?></strong>
                                </td>

                                <!-- Logo -->
                                <td>
                                    <input
                                        type="text"
                                        class="form-control form-control-sm field"
                                        style="font-size:0.75rem; max-width:16rem; width:100%;"
                                        data-field="logo"
                                        value="<?= htmlspecialchars($r['logo']) ?>"
                                        placeholder="–">
                                </td>

                                <!-- Venta: Cant -->
                                <td class="text-right"><?= intval($r['ventaCantidad']) ?></td>

                                <!-- Venta: Precio (sin impuesto / con impuesto) -->
                                <td>
                                    <?= fmt($r['precioVentaAntesImpuestos']) ?><br>
                                    <?= fmt($r['precioVentaAntesImpuestos'] * (1 + $r['porcentajeImpuestoServicio'])) ?>
                                </td>
                                <!-- Venta: Total -->
                                <td>
                                    <span class="venta-total-noimp">
                                        <?= fmt($r['ventaCantidad'] * $r['precioVentaAntesImpuestos']) ?>
                                    </span><br>
                                    <span class="venta-total-imp"
                                        data-value="<?= ($r['ventaCantidad'] * $r['precioVentaAntesImpuestos'] * (1 + $r['porcentajeImpuestoServicio'])) ?>">
                                        <?= fmt($r['ventaCantidad'] * $r['precioVentaAntesImpuestos'] * (1 + $r['porcentajeImpuestoServicio'])) ?>
                                    </span>
                                </td>


                                <!-- Separador -->
                                <td class="table-secondary"></td>

                                <!-- Info: Estado / Taller / Mes (stacked) -->
                                <td>
                                    <div class="d-flex flex-column small">
                                        <select
                                            class="form-select form-select-sm mb-1 field"
                                            style="font-size:0.75rem; max-width:6rem; background:<?= $r['estadoColor'] ?>; color:#fff"
                                            data-field="idEstadoTrabajo">
                                            <?php foreach ($estados as $es): ?>
                                                <option value="<?= $es['id'] ?>" <?= $es['id'] == $r['idEstadoTrabajo'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($es['nombre']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>

                                        <select
                                            class="form-select form-select-sm mb-1 field"
                                            style="font-size:0.75rem; max-width:6rem;"
                                            data-field="idImpresor">
                                            <?php foreach ($impresores as $imp): ?>
                                                <option value="<?= $imp['id'] ?>" <?= $imp['id'] == $r['idImpresor'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($imp['nombre']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>

                                        <select
                                            class="form-select form-select-sm field"
                                            style="font-size:0.75rem; max-width:6rem;"
                                            data-field="idMesContable">
                                            <option value="" disabled <?= $r['idMesContable'] ? '' : 'selected' ?>>-- Seleccione mes --</option>
                                            <?php foreach ($meses as $m): ?>
                                                <option value="<?= $m['id'] ?>" <?= $m['id'] == $r['idMesContable'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($m['nombre']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <?php if (!$r['idMesContable']): ?>
                                            <small class="text-danger">Falta Mes contable</small>
                                        <?php endif; ?>
                                    </div>
                                </td>

                                <!-- Fechas: cada una editable, dash si vacío -->
                                <td>
                                    <div class="d-flex flex-column" style="font-size:0.75rem;">
                                        <?php foreach (
                                            [
                                                'fechaMercancia'         => '📦',
                                                'fechaEntregaLogo'       => '🖼️',
                                                'fechaAprobacionMontaje' => '✅',
                                                'fechaCompromisoEntrega' => '🚚'
                                            ] as $fld => $icon
                                        ): ?>
                                            <div class="d-flex align-items-center mb-1">
                                                <span class="me-1" title="<?= $fld ?>"><?= $icon ?></span>
                                                <input
                                                    type="date"
                                                    class="form-control form-control-sm field"
                                                    style="font-size:0.6rem; max-width:6rem;"
                                                    data-field="<?= $fld ?>"
                                                    value="<?= $r[$fld] ? date('Y-m-d', strtotime($r[$fld])) : '' ?>"
                                                    placeholder="–">
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </td>

                                <!-- Servicio: Cantidad -->
                                <td>
                                    <input
                                        type="text"
                                        class="form-control form-control-sm d-inline-block field text-right"
                                        style="width:auto!important; max-width:3rem; font-size:0.75rem;"
                                        data-field="cantidad"
                                        value="<?= $r['cantidadTaller'] ?>"
                                        step="1">
                                </td>

                                <!-- Servicio: Precio + Impuesto selector -->
                                <td>
                                    <input
                                        type="text"
                                        class="form-control form-control-sm d-inline-block mb-1 field text-right"
                                        style="width:auto!important; max-width:6rem; font-size:0.75rem;"
                                        data-field="precioUnitario"
                                        value="<?= intval($r['precioUnitario']) ?>"
                                        step="1"
                                        placeholder="–">
                                    <select
                                        class="form-select form-select-sm d-inline-block field"
                                        style="width:auto!important; max-width:6rem; font-size:0.75rem;"
                                        data-field="idImpuesto">
                                        <option value="" disabled <?= $r['idImpuesto'] ? '' : 'selected' ?>>--</option>
                                        <?php foreach ($impuestos as $imp): ?>
                                            <option
                                                value="<?= $imp['id'] ?>"
                                                data-valor="<?= $imp['valor'] ?>"
                                                <?= $imp['id'] == $r['idImpuesto'] ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($imp['nombre']) ?> (<?= $imp['valor'] * 100 ?>%)
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>

                                <!-- Servicio: Total (sin impuesto / con impuesto) -->
                                <td>
                                    <span class="service-total-noimp">
                                        <?= $r['cantidadTaller'] * $r['precioUnitario'] ?>
                                    </span><br>
                                    <span class="service-total-imp"
                                        data-value="<?= ($r['cantidadTaller'] * $r['precioUnitario'] * (1 + $r['porcentajeImpuesto'])) ?>">
                                        <?= fmt($r['cantidadTaller'] * $r['precioUnitario'] * (1 + $r['porcentajeImpuesto'])) ?>
                                    </span>
                                </td>


                                <!-- Dif (Venta IVA – Servicio IVA) -->
                                <td class="diff-cell">
                                    <?= fmt(
                                        $r['ventaCantidad'] * $r['precioVentaAntesImpuestos'] * (1 + $r['porcentajeImpuestoServicio'])
                                            - $r['cantidadTaller'] * $r['precioUnitario'] * (1 + $r['porcentajeImpuesto'])
                                    ) ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>


                </table>
            </div>

            <!--───────────────────  TAB PROCESO – KOLOR  ───────────────────-->

            <?php if (! $isVentaMode): ?>
                <h4 class="mt-4">Kolor Taller Creativo</h4>
                <div class="table-responsive">
                    <table class="table table-sm table-bordered">
                        <thead>
                            <tr>
                                <th rowspan="3">Serv<br><small>Empresa</small></th>
                                <th rowspan="3">NoFact</th>
                                <th rowspan="3">Fecha</th>
                                <th rowspan="3">Cliente</th>
                                <th rowspan="3">Producto<br><small>Marca</small></th>
                                <th rowspan="3">Logo</th>
                                <th colspan="3">Venta</th>
                                <th class="table-secondary" rowspan="3"></th>
                                <th rowspan="3">Info</th>
                                <th rowspan="3">Fechas</th>
                                <th colspan="3">Servicio</th>
                                <th rowspan="3">Dif</th>
                            </tr>
                            <tr>
                                <th>Cant</th>
                                <th>Precio</th>
                                <th>Total</th>
                                <th>Cant</th>
                                <th>Precio</th>
                                <th>Total</th>
                            </tr>
                            <tr></tr>
                        </thead>
                        <tbody>
                            <?php foreach ($procKolor as $r): ?>
                                <tr data-id="<?= $r['id'] ?>" style="font-size:0.85rem;">

                                    <!-- Serv + Empresa -->
                                    <td>
                                        <?= $r['id'] ?><br>
                                        <?php
                                        $selectedColor = '#ffffff';
                                        foreach ($empresas as $ee) {
                                            if ($ee['id'] == $r['idEmpresa']) {
                                                $selectedColor = $ee['colorHexa'];
                                                break;
                                            }
                                        }
                                        ?>
                                        <select class="form-select form-select-sm field"
                                            style="
          font-size:0.75rem;
          max-width:5rem;
          background-color: <?= htmlspecialchars($selectedColor) ?>;
          color: <?= getTextColor($selectedColor) ?>;
        "
                                            data-field="idEmpresa">
                                            <?php foreach ($empresas as $e): ?>
                                                <option
                                                    value="<?= $e['id'] ?>"
                                                    <?= $e['id'] == $r['idEmpresa'] ? 'selected' : '' ?>
                                                    style="
                  background-color: <?= htmlspecialchars($e['colorHexa']) ?>;
                  color: <?= getTextColor($e['colorHexa']) ?>;
                ">
                                                    <?= htmlspecialchars($e['nombre']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>


                                    <!-- NoFact -->
                                    <td>
                                        <input type="text" class="form-control form-control-sm field mb-1"
                                            style="font-size:0.75rem; max-width:6rem;"
                                            data-field="prefijoFacturaCliente"
                                            value="<?= htmlspecialchars($r['prefijoFacturaCliente']) ?>">
                                        <input type="text" class="form-control form-control-sm field"
                                            style="font-size:0.75rem; max-width:6rem;"
                                            data-field="noFacturaCliente"
                                            value="<?= htmlspecialchars($r['noFacturaCliente']) ?>">
                                    </td>

                                    <!-- Fecha -->
                                    <td>
                                        <input type="date" class="form-control form-control-sm field"
                                            style="font-size:0.75rem; max-width:6rem;"
                                            data-field="fechaOrden"
                                            value="<?= $r['fechaOrden'] ? date('Y-m-d', strtotime($r['fechaOrden'])) : '' ?>">
                                    </td>

                                    <!-- Cliente -->
                                    <td>
                                        <input type="text" class="form-control form-control-sm field"
                                            style="font-size:0.75rem; max-width:8rem;"
                                            data-field="cliente"
                                            value="<?= htmlspecialchars($r['cliente']) ?>">
                                    </td>

                                    <!-- Producto + Marca -->
                                    <td>
                                        <input type="text" class="form-control form-control-sm field mb-1"
                                            style="font-size:0.75rem; max-width:8rem;"
                                            data-field="producto"
                                            value="<?= htmlspecialchars($r['producto']) ?>">
                                        <input type="text" class="form-control form-control-sm field"
                                            style="font-size:0.75rem; max-width:8rem;"
                                            data-field="tipoDeMarca"
                                            value="<?= htmlspecialchars($r['tipoDeMarca']) ?>">
                                    </td>

                                    <!-- Logo -->
                                    <td>
                                        <input type="text" class="form-control form-control-sm field"
                                            style="font-size:0.75rem; max-width:8rem;"
                                            data-field="logo"
                                            value="<?= htmlspecialchars($r['logo']) ?>">
                                    </td>

                                    <!-- Venta: Cant -->
                                    <td>
                                        <input type="number" class="form-control form-control-sm field text-end"
                                            style="font-size:0.75rem; max-width:4rem;"
                                            data-field="cantidadVenta"
                                            value="<?= intval($r['cantidadVenta']) ?>">
                                        <select class="form-select form-select-sm field"
                                            style="font-size:0.75rem; max-width:6rem;"
                                            data-field="idImpuestoVenta">
                                            <?php foreach ($impuestos as $imp): ?>
                                                <option
                                                    value="<?= $imp['id'] ?>"
                                                    data-valor="<?= $imp['valor'] ?>"
                                                    <?= $imp['id'] == $r['idImpuestoVenta'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($imp['nombre']) ?> (<?= $imp['valor'] * 100 ?>%)
                                                </option>
                                            <?php endforeach; ?>
                                        </select>


                                    </td>

                                    <!-- Venta: Precio (sin/con IVA) -->
                                    <td>
                                        <?= fmt($r['precioUnitarioVenta']) ?><br>
                                        <?= fmt($r['precioUnitarioVenta'] * (1 + $r['porcentajeImpuestoVenta'])) ?>
                                    </td>

                                    <!-- Venta: Total (sin/con IVA) -->
                                    <td>
                                        <?= fmt($r['cantidadVenta'] * $r['precioUnitarioVenta']) ?><br>
                                        <?= fmt($r['cantidadVenta'] * $r['precioUnitarioVenta'] * (1 + $r['porcentajeImpuestoVenta'])) ?>
                                    </td>

                                    <!-- Separador -->
                                    <td class="table-secondary"></td>

                                    <!-- Info: Estado / Impresor / Mes -->
                                    <td>
                                        <select class="form-select form-select-sm field mb-1"
                                            style="font-size:0.75rem; max-width:6rem; background:<?= $r['estadoColor'] ?>; color:#fff;"
                                            data-field="idEstadoTrabajo">
                                            <?php foreach ($estados as $es): ?>
                                                <option value="<?= $es['id'] ?>"
                                                    <?= $es['id'] == $r['idEstadoTrabajo'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($es['nombre']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <select class="form-select form-select-sm field mb-1"
                                            style="font-size:0.75rem; max-width:6rem;"
                                            data-field="idImpresor">
                                            <?php foreach ($impresores as $imp): ?>
                                                <option value="<?= $imp['id'] ?>"
                                                    <?= $imp['id'] == $r['idImpresor'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($imp['nombre']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <select class="form-select form-select-sm field"
                                            style="font-size:0.75rem; max-width:6rem;"
                                            data-field="idMesContable">
                                            <option value="" disabled <?= $r['idMesContable'] ? '' : 'selected' ?>>-- Mes --</option>
                                            <?php foreach ($meses as $m): ?>
                                                <option value="<?= $m['id'] ?>"
                                                    <?= $m['id'] == $r['idMesContable'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($m['nombre']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <?php if (!$r['idMesContable']): ?>
                                            <small class="text-danger">Falta Mes contable</small>
                                        <?php endif; ?>
                                    </td>

                                    <!-- Fechas -->
                                    <td>
                                        <div class="d-grid gap-1">
                                            <?php foreach (
                                                [
                                                    'fechaMercancia'         => '📦',
                                                    'fechaEntregaLogo'       => '🖼️',
                                                    'fechaAprobacionMontaje' => '✅',
                                                    'fechaCompromisoEntrega' => '🚚'
                                                ] as $fld => $icon
                                            ): ?>
                                                <div class="d-flex align-items-center">
                                                    <span class="me-1" title="<?= $fld ?>"><?= $icon ?></span>
                                                    <input type="date" class="form-control form-control-sm field"
                                                        style="font-size:0.6rem; max-width:6rem;"
                                                        data-field="<?= $fld ?>"
                                                        value="<?= $r[$fld] ? date('Y-m-d', strtotime($r[$fld])) : '' ?>">
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </td>

                                    <!-- Servicio: Cant -->
                                    <td>
                                        <input type="number" class="form-control form-control-sm field text-end"
                                            style="font-size:0.75rem; max-width:4rem;"
                                            data-field="cantidad"
                                            value="<?= intval($r['cantidadTaller']) ?>">
                                    </td>

                                    <!-- Servicio: Precio + impuesto selector -->
                                    <td>
                                        <input type="number" class="form-control form-control-sm field mb-1 text-end"
                                            style="font-size:0.75rem; max-width:6rem;"
                                            data-field="precioUnitario"
                                            value="<?= intval($r['precioUnitario']) ?>">
                                        <select class="form-select form-select-sm field"
                                            data-field="idImpuestoVenta">
                                            <?php foreach ($impuestos as $imp): ?>
                                                <option
                                                    value="<?= $imp['id'] ?>"
                                                    data-valor="<?= $imp['valor'] ?>"
                                                    <?= $imp['id'] == $r['idImpuestoVenta'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($imp['nombre']) ?> (<?= $imp['valor'] * 100 ?>%)
                                                </option>
                                            <?php endforeach; ?>
                                        </select>

                                    </td>

                                    <!-- Servicio: Total (sin/con IVA) -->
                                    <td>
                                        <?= fmt($r['cantidadTaller'] * $r['precioUnitario']) ?><br>
                                        <?= fmt($r['cantidadTaller'] * $r['precioUnitario'] * (1 + $r['porcentajeImpuesto'])) ?>
                                    </td>

                                    <!-- Dif -->
                                    <td>
                                        <?= fmt(
                                            $r['cantidadVenta'] * $r['precioUnitarioVenta'] * (1 + $r['porcentajeImpuestoVenta'])
                                                - $r['cantidadTaller'] * $r['precioUnitario'] * (1 + $r['porcentajeImpuesto'])
                                        ) ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
        </div><!-- /tab-content -->
    <?php endif; ?>
    <!--──────────────────────  FINALIZADOS COMPRANET  ─────────────────────-->
    <div id="tabFinalCompranet" class="tab-pane fade">
        <h4 class="mt-3">Finalizados Compranet</h4>
        <?php $DATASET = $finalCompranet;
        include __DIR__ . '/finalizados_table.php'; ?>
    </div>

    <!--──────────────────────  FINALIZADOS KOLOR  ─────────────────────-->
    <div id="tabFinalKolor" class="tab-pane fade">
        <h4 class="mt-3">Finalizados Kolor</h4>
        <?php $DATASET = $finalKolor;
        include __DIR__ . '/finalizados_table.php'; ?>
    </div>
    </div><!-- /tab-content -->
    </div>
    <?php if (!$isVentaMode): /* vista independiente */ ?>
        <?php include '../templates/footer.php'; ?>
        <script src="/marcacion/trabajos.js"></script>
    <?php else:           /* embebido en venta */ ?>
        <script src="/marcacion/trabajos.js"></script>
    <?php endif; ?>
