<?php
// cotizaciones/detalle_cotizacion.php?id=123
session_start();
include '../includes/session_control.php';

$idCot = intval($_GET['id'] ?? 0);
if (!$idCot) die('ID de cotización inválido');

require __DIR__ . '/api/_node.php';

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();
$url = $base . '/api/cotizaciones/' . $idCot;
$r = cpn_node_request('GET', $url, $token);

if (!isset($r['ok']) || $r['ok'] !== true || !isset($r['data']) || !is_array($r['data'])) {
    die('Cotización no encontrada');
}

$C = $r['data'];

$obs = trim((string)($C['observaciones'] ?? ''));
if ($obs === '') {
    $obs = "Precio unitario no incluye IVA\n" .
        "- IVA 19%\n" .
        "- Sujeto a disponibilidad de mercancia\n" .
        "- Imágenes solo de Referencia, El producto real puede tener algunas diferencias.\n" .
        "- Precios pueden variar según la cantidad cotizada\n" .
        "- Validez de la oferta: 3 dias habiles\n" .
        "- Tiempo de entrega: 3 días habiles sin marcación  8 dias habiles con marcación despues de aprobada la orden de compra, mas lo que tome la transportadora \n" .
        "- Envio Se cotiza de acuerdo a las unidades a despachar y Ciudad destino \n" .
        "- Forma de Pago Contado para pedidos sin marca \n" .
        "- Con marca 50% para iniciar proceso,  50% restante antes de hacer el Despacho o la entrega";
}
?>
<?php include '../templates/header.php'; ?>
<link rel="stylesheet" href="css/detalle_cotizacion.css">

<div class="container-fluid" id="pageContent">

    <h1 class="h3 mb-1">
        Cotización #<?= $C['id'] ?> —
        <small><?= htmlspecialchars(($C['usuarioNombre'] ?? '') . ' ' . ($C['usuarioApellido'] ?? '')) ?></small>
        <?php
        $estadoId = (int)($C['estadoId'] ?? ($C['idEstado'] ?? 0));
        $estadoClass = 'badge badge-secondary';
        if ($estadoId === 2) $estadoClass = 'badge badge-success';
        else if ($estadoId === 3) $estadoClass = 'badge badge-primary';
        else if ($estadoId === 4) $estadoClass = 'badge badge-danger';
        else if ($estadoId === 5) $estadoClass = 'badge badge-dark';

        $resp = trim((string)($C['responsableNombre'] ?? '') . ' ' . (string)($C['responsableApellido'] ?? ''));
        ?>
        <span id="cot-estado-badge" class="<?= $estadoClass ?>"><?= htmlspecialchars($C['estadoNombre'] ?? '') ?></span>
    </h1>
    <p class="mb-3 small">
        <strong>Beneficiario:</strong>
        <a href="/usuarios/administrar_usuario.php?id=<?= (int)($C['idUsuario'] ?? 0) ?>" target="_blank">
            <?= htmlspecialchars(($C['usuarioNombre'] ?? '') . ' ' . ($C['usuarioApellido'] ?? '')) ?>
        </a>
        <?php if ($resp !== ''): ?>
            &nbsp;|&nbsp; <strong>Responsable:</strong> <?= htmlspecialchars($resp) ?>
        <?php endif; ?>
    </p>

    <!-- Seguimiento -->
    <div class="card shadow-sm mb-3" id="cardSeguimiento">
        <div class="card-header py-2 d-flex justify-content-between align-items-center">
            <h6 class="m-0 font-weight-bold text-primary">Seguimiento</h6>
            <button type="button" class="btn btn-primary btn-sm" id="btnAbrirSeguimiento">Agregar nota</button>
        </div>
        <div class="card-body">
            <div id="alertVencidaSinSeguimiento" class="alert alert-danger d-none mb-2">
                Esta cotización está <strong>vencida</strong> y <strong>no tiene notas de seguimiento</strong>.
            </div>
            <div class="small mb-2">
                <strong>Próximo seguimiento:</strong> <span id="txtProximoSeguimiento">—</span>
                &nbsp;|&nbsp; <strong>Vence:</strong> <span id="txtVence">—</span>
            </div>

            <div class="table-responsive">
                <table class="table table-sm table-bordered" id="tablaSeguimiento">
                    <thead class="thead-light">
                        <tr>
                            <th style="width: 160px;">Fecha</th>
                            <th style="width: 140px;">Resultado</th>
                            <th>Nota</th>
                            <th style="width: 170px;">Próxima gestión</th>
                            <th style="width: 160px;">Responsable</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Botonera superior -->
    <div class="mb-3 d-flex flex-wrap gap-2">
        <button class="btn btn-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#modalBenef">
            Cambiar beneficiario / Empresa
        </button>
        <a href="/usuarios/administrar_usuario.php?id=<?= (int)($C['idUsuario'] ?? 0) ?>" target="_blank"
            class="btn btn-info btn-sm">Editar Beneficiario</a>


    </div>

    <!-- PRIMERA FILA: Información general (10 cols) + Resumen (2 cols) -->
    <div class="row">
        <!-- IZQUIERDA: Información general -->
        <div class="col-lg-10">
            <div class="card mb-4">
                <div class="card-header">Información general</div>
                <div class="card-body small">
                    <div class="row g-3">
                        <!-- PRIMERA FILA: Fecha, Empresa y Tipo -->
                        <div class="col-md-4">
                            <label class="form-label small">Fecha</label>
                            <input
                                id="field-fecha"
                                type="date"
                                class="form-control form-control-sm"
                                value="<?= date('Y-m-d', strtotime((string)($C['fechaCreacion'] ?? ''))) ?>">
                        </div>

                        <div class="col-md-4">
                            <label class="form-label small">Empresa</label>
                            <select id="field-idEmpresa" class="form-control form-control-sm" data-current="<?= (int)($C['idEmpresa'] ?? 0) ?>">
                                <option value="">Cargando…</option>
                            </select>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label small">Tipo</label>
                            <div id="tipoRadios" data-current="<?= (int)($C['idTipo'] ?? 0) ?>"></div>
                        </div>

                        <!-- SEGUNDA FILA (colmna completa) para los botones -->
                        <div class="col-12 mt-3">
                            <div class="d-flex gap-2">
                                <button
                                    class="btn btn-primary btn-sm"
                                    data-bs-toggle="modal"
                                    data-bs-target="#modalBuscador">
                                    + Añadir ítem / marca
                                </button>
                                <button
                                    id="sendCotizacionBtn"
                                    class="btn btn-outline-primary btn-sm">
                                    Enviar Cotización
                                </button>
                                <button
                                    id="viewPdfBtn"
                                    class="btn btn-secondary btn-sm">
                                    Ver PDF
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <!-- DERECHA: Resumen -->
        <div class="col-lg-2" id="asideResumen">
            <div class="card mb-2">
                <div class="card-header small">Resumen</div>
                <div class="card-body small" id="boxResumen" style="font-size: 0.85rem;">
                    <dl class="row">
                        <dt class="col-6">Subtotal</dt>
                        <dd class="col-6 text-right text-nowrap" id="res-sub">$ 0</dd>

                        <dt class="col-6">IVA</dt>
                        <dd class="col-6 text-right text-nowrap" id="res-iva">$ 0</dd>

                        <dt class="col-6">Total</dt>
                        <dd class="col-6 text-right fw-bold text-nowrap" id="res-tot">$ 0</dd>
                    </dl>
                </div>
            </div>
            <!-- Botón "+ Añadir ítem / marca" debajo del Resumen (si aún lo necesitas) -->
            <!-- 
    <button
      class="btn btn-primary btn-sm w-100 mt-2"
      data-bs-toggle="modal"
      data-bs-target="#modalBuscador"
    >
      + Añadir ítem / marca
    </button>
    -->
        </div>
    </div>

    <!-- SEGUNDA FILA: Detalle de ítems (12 columnas) -->
    <div class="row">
        <div class="col-12">
            <div class="table-responsive">
                <table class="table table-bordered table-sm align-middle small" id="tablaItems">
                    <thead class="table-light small">
                        <tr>
                            <th style="width: 5%;">Ref.</th>
                            <th style="width: 5%;">Img</th>
                            <th style="width:24%;">Descripción</th>
                            <th class="text-right" style="width: 4%;">Cant</th>
                            <th class="text-right" style="width: 6%;">P. Prod</th>
                            <th style="width: 6%;">Servicio</th>
                            <th class="text-right" style="width: 6%;">P. Serv</th>
                            <th class="text-right" style="width: 6%;">P. Venta</th>
                            <th class="text-right" style="width: 6%;">Subtotal</th>
                            <th class="text-right" style="width: 4%;">IVA</th>
                            <th style="width: 6%;">Impuesto</th>
                            <th class="text-right" style="width: 6%;">Total</th>
                            <th style="width: 3%;">ImgWP</th>
                            <th style="width:10%;">Obs.</th>
                            <th style="width: 2%;">Eliminar</th>
                        </tr>
                    </thead>

                    <tbody><!-- AJAX llenará aquí las filas --></tbody>
                </table>
            </div>

            <!-- OBSERVACIONES GENERALES: REUBICADO debajo de la tabla de ítems -->
            <!-- OBSERVACIONES GENERALES: REUBICADO debajo de la tabla de ítems -->
            <div class="mt-3">
                <label for="field-observaciones" class="form-label small">Observaciones generales</label>
                <textarea
                    id="field-observaciones"
                    class="form-control form-control-sm"
                    style="font-size:0.75rem; width:100%; overflow:hidden; resize:none; line-height:1.2;"><?= htmlspecialchars($obs) ?></textarea>
            </div>


        </div>
    </div>
</div>

<!-- Modal: Agregar seguimiento -->
<div class="modal fade" id="modalSeguimiento" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Agregar seguimiento</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="formSeguimiento">
                <div class="modal-body">
                    <div class="form-group">
                        <label class="small mb-1" for="segResultado">Resultado</label>
                        <select id="segResultado" class="form-control form-control-sm">
                            <option value="">(Sin resultado)</option>
                            <option value="aprobada">Aprobada</option>
                            <option value="rechazada">Rechazada</option>
                            <option value="recotizar">Se cotizó de nuevo</option>
                            <option value="revisando">Revisando</option>
                            <option value="sin_respuesta">Sin respuesta</option>
                            <option value="interesado">Interesado</option>
                            <option value="no_interesado">No interesado</option>
                        </select>
                        <small class="form-text text-muted">
                            Si eliges <strong>Revisando</strong> y no defines fecha, se agenda a +10 días.
                            Si eliges <strong>Aprobada</strong>/<strong>Rechazada</strong>/<strong>Se cotizó de nuevo</strong>, se actualiza el estado de la cotización.
                        </small>
                    </div>

                    <div class="form-group">
                        <label class="small mb-1" for="segProxima">Próxima gestión</label>
                        <input type="datetime-local" id="segProxima" class="form-control form-control-sm" />
                    </div>

                    <div class="form-group mb-0">
                        <label class="small mb-1" for="segNota">Nota</label>
                        <textarea id="segNota" class="form-control" rows="4" maxlength="5000" required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cerrar</button>
                    <button type="submit" class="btn btn-primary btn-sm">Guardar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Email Modal -->
<div class="modal fade" id="emailModal" tabindex="-1" aria-labelledby="emailModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content small">
            <div class="modal-header">
                <h5 class="modal-title" id="emailModalLabel">Enviar Cotización</h5>
                <button type="button" class="btn-close btn-sm" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body small">
                <form id="emailForm">
                    <div class="mb-2">
                        <label for="email" class="form-label small">Correo Electrónico</label>
                        <input type="email" class="form-control form-control-sm" id="email" required>
                    </div>
                    <div class="mb-2">
                        <label for="subject" class="form-label small">Asunto</label>
                        <input type="text" class="form-control form-control-sm" id="subject" required>
                    </div>
                    <div class="mb-2">
                        <label for="message" class="form-label small">Cuerpo del Mensaje</label>
                        <textarea class="form-control form-control-sm" id="message" rows="5" required>Buen Día

De acuerdo a su amable solicitud enviamos cotización de los productos requeridos.

Si tienes alguna duda adicional, no dudes en contactarnos.

Cordialmente,

COMPRANET COMERCIO ELECTRONICO S.A.S.

Bogotá D.C. – Colombia
Página 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 class="d-flex justify-content-between">
                        <button type="submit" class="btn btn-primary btn-sm">Enviar correo</button>
                        <button type="button" id="viewPdfBtn" class="btn btn-secondary btn-sm">Ver PDF</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include '../templates/footer.php'; ?>

<!-- Modales Funcionales -->
<?php
include __DIR__ . '/modals/beneficiario_modal.php';
include __DIR__ . '/modals/nuevo_usuario_modal.php';
include __DIR__ . '/modals/buscador_modal.php';
?>

<!-- Constantes JS globales -->
<script>
    const ID_COT = <?= $C['id'] ?>;
    const PATH_API = '/cotizaciones/api';
    const COT_FECHA_PROX_SEG = <?= json_encode($C['fechaProximoSeguimiento'] ?? null) ?>;
    const COT_FECHA_VENCE = <?= json_encode($C['fechaVencimiento'] ?? null) ?>;
    const COT_VENCIDA_SIN_SEGUIMIENTO = <?= json_encode((bool)($C['vencidaSinSeguimiento'] ?? false)) ?>;
</script>

<!-- Aquí solo carga tu JS externo -->
<script src="/cotizaciones/js/detalle_cotizacion.js"></script>