<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

require_once 'db/config.php';
require_once __DIR__ . '/includes/tipo_paquete.php';

function getStatusStyle($status) {
    $style = 'color: white;'; // Default text color
    $bgColor = '#0dcaf0'; // Default info blue

    switch (strtoupper(trim($status))) {
        case 'ROTULADO':
            $bgColor = '#ffc107'; // yellow
            $style = 'color: black;';
            break;
        case 'EN TRANSITO':
            $bgColor = '#90EE90'; // light green
            $style = 'color: black;';
            break;
        case 'EN DESTINO':
            $bgColor = '#800080'; // purple
            break;
        case 'COMPLETADO':
        case 'COMPLETADO ✅':
            $bgColor = '#198754'; // dark green
            break;
        case 'GESTION':
            $bgColor = '#6c757d'; // secondary grey
            break;
        case 'RUTA_CONTRAENTREGA':
            $bgColor = '#007bff'; // primary blue
            break;
        case 'PENDIENTE':
            $bgColor = '#fff3cd'; // cream
            $style = 'color: #5f4700;';
            break;
        case 'ENTREGA EXITOSA':
            $bgColor = '#198754'; // dark green
            break;
        case 'RETORNADO':
            $bgColor = '#dc3545'; // red
            break;
        case 'NO CONTESTO, DEVOLVER LLAMADA':
        case 'NO CONTESTO, VOLVER A LLAMAR':
            $bgColor = '#fd7e14'; // orange
            break;
        case 'CANCELADO':
        case 'CANCELAR':
            $bgColor = '#8b1e2d'; // guinda/red for cancelled
            break;
        case 'REPROGRAMADO':
            $bgColor = '#6f42c1'; // indigo/purple
            break;
    }
    return "background-color: {$bgColor} !important; {$style}";
}

function getPaqueteStyle($paquete) {
    if ($paquete === 'RUTA') return 'background-color: #0dcaf0; color: black;'; // Info cyan
    if ($paquete === 'CONTRAENTREGA') return 'background-color: #ffc107; color: black;'; // Warning yellow
    if ($paquete === 'NO CONTESTA, VOLVER A LLAMAR') return 'background-color: #fd7e14; color: white;'; // Orange
    if ($paquete === 'PENDIENTE A RETORNO') return 'background-color: #dc3545; color: white;'; // Red
    if ($paquete === 'COMPLETADO') return 'background-color: #198754; color: white;'; // Success green
    if ($paquete === 'PREPARADO') return 'background-color: #20c997; color: white;'; // Preparado
    if ($paquete === 'EMPAQUETADO') return 'background-color: #20c997; color: white;'; // Legacy alias
    if ($paquete === 'RETORNADO') return 'background-color: #dc3545; color: white;'; // Same red as PENDIENTE A RETORNO
    if ($paquete === 'ANULADO') return 'background-color: #212529; color: white;'; // Dark
    return 'background-color: #6c757d; color: white;'; // Secondary grey
}

function getFechaEntregaStyle($fecha) {
    if (empty($fecha) || $fecha === '0000-00-00') {
        return 'background-color: #f8f9fa; color: #6c757d;'; // Light grey for N/A
    }
    // Check if the date is in the past
    if (strtotime($fecha) < time()) {
        return 'background-color: #f8d7da; color: #721c24;'; // Light red for past dates
    }
    return 'background-color: #e0f7fa; color: black;'; // Light cyan background for upcoming dates
}

$pdo = db();
ensureTipoPaqueteEnumDefinition($pdo);

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['user_role'] ?? 'Asesor';

// Fetch years for the filter
$years_query = "SELECT DISTINCT YEAR(created_at) as year FROM pedidos";
if ($user_role === 'Asesor') {
    $years_query .= " WHERE asesor_id = ?";
    $years_stmt = $pdo->prepare($years_query);
    $years_stmt->execute([$user_id]);
} else {
    $years_stmt = $pdo->query($years_query);
}
$years = $years_stmt->fetchAll(PDO::FETCH_COLUMN);


// Filter logic
$selected_month = $_GET['mes'] ?? '';
$selected_year = $_GET['año'] ?? '';
$search_query = $_GET['q'] ?? '';

$period = $_GET['period'] ?? '';
$date_condition = '';
$label_period = '';

if (!empty($period)) {
    switch ($period) {
        case 'today':
            $date_condition = "DATE(p.created_at) = CURDATE()";
            $label_period = "Hoy";
            break;
        case 'yesterday':
            $date_condition = "DATE(p.created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
            $label_period = "Ayer";
            break;
        case '7':
            $date_condition = "DATE(p.created_at) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
            $label_period = "Últimos 7 días";
            break;
        case '15':
            $date_condition = "DATE(p.created_at) >= DATE_SUB(CURDATE(), INTERVAL 15 DAY)";
            $label_period = "Últimos 15 días";
            break;
        case 'month':
            $date_condition = "MONTH(p.created_at) = MONTH(CURDATE()) AND YEAR(p.created_at) = YEAR(CURDATE())";
            $label_period = "Este Mes";
            break;
    }
}

$sql = "SELECT p.*, u.nombre_asesor as asesor_nombre FROM pedidos p LEFT JOIN users u ON p.asesor_id = u.id WHERE p.estado IN ('RUTA_CONTRAENTREGA', 'PENDIENTE', 'NO CONTESTO, VOLVER A LLAMAR', 'NO CONTESTO, DEVOLVER LLAMADA', 'CANCELADO', 'REPROGRAMADO', 'ENTREGA EXITOSA', 'RETORNADO')";
$params = [];

if ($user_role === 'Asesor') {
    $sql .= " AND p.asesor_id = ?";
    $params[] = $user_id;
}

if (!empty($search_query)) {
    $sql .= " AND (p.nombre_completo LIKE ? OR p.dni_cliente LIKE ? OR p.celular LIKE ?)";
    $params[] = "%$search_query%";
    $params[] = "%$search_query%";
    $params[] = "%$search_query%";
}

if (!empty($date_condition)) {
    $sql .= " AND $date_condition";
} else {
    if (!empty($selected_month)) {
        $sql .= " AND MONTH(p.created_at) = ?";
        $params[] = $selected_month;
    }
    if (!empty($selected_year)) {
        $sql .= " AND YEAR(p.created_at) = ?";
        $params[] = $selected_year;
    }
}

$sql .= " ORDER BY p.created_at DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$pedidos = $stmt->fetchAll();

// Obtener el template de WhatsApp para contraentrega
$stmt_template = db()->prepare('SELECT valor FROM configuracion WHERE clave = ?');
$stmt_template->execute(['whatsapp_template_contraentrega']);
$whatsapp_template = $stmt_template->fetchColumn();
if ($whatsapp_template === false) {
    // Fallback to a default message if not set in DB
    $whatsapp_template = 'Hola, te escribo para confirmar que tu pedido ya llegó a destino. El monto que debes es {monto} y la dirección de entrega será {direccion}.';
}

$months = [
    1 => 'Enero', 2 => 'Febrero', 3 => 'Marzo', 4 => 'Abril', 5 => 'Mayo', 6 => 'Junio',
    7 => 'Julio', 8 => 'Agosto', 9 => 'Septiembre', 10 => 'Octubre', 11 => 'Noviembre', 12 => 'Diciembre'
];

function splitProvinciaDistrito($value) {
    $value = trim((string)($value ?? ''));
    if ($value === '') {
        return ['N/A', 'N/A'];
    }

    $parts = preg_split('/\s*(?:\/|\||,|-)\s*/', $value, 2);
    $provincia = trim($parts[0] ?? '');
    $distrito = trim($parts[1] ?? '');

    return [
        $provincia !== '' ? $provincia : 'N/A',
        $distrito !== '' ? $distrito : 'N/A',
    ];
}

?>
<?php 
$pageTitle = "Ruta Contraentrega";
include 'layout_header.php'; 
?>

<?php if (isset($_SESSION['flash_message'])):
    $flash = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);
?>
<div class="alert alert-<?php echo htmlspecialchars($flash['type']); ?> alert-dismissible fade show" role="alert">
    <?php echo htmlspecialchars($flash['message']); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>

<style>
    /* Ajustes puntuales para Ruta Contraentrega: opciones largas sin invadir columnas vecinas */
    #pedidos-table {
        min-width: 1850px;
    }
    #pedidos-table th:nth-child(3),
    #pedidos-table td:nth-child(3) {
        width: 230px !important;
        min-width: 230px !important;
        max-width: 230px !important;
    }
    #pedidos-table th:nth-child(4),
    #pedidos-table td:nth-child(4) {
        width: 280px !important;
        min-width: 280px !important;
        max-width: 280px !important;
    }
    #pedidos-table .editable-paquete .badge,
    #pedidos-table .editable-estado .badge {
        display: inline-block;
        width: 100%;
        white-space: normal;
        line-height: 1.25;
        text-align: center;
        padding: 0.45rem 0.55rem;
    }
    #pedidos-table .editable-paquete select,
    #pedidos-table .editable-estado select {
        width: 100%;
        min-width: 100%;
        white-space: normal;
        font-size: 0.82rem;
    }


    /* Contraentrega: icono para ver/subir verificación (foto + tracking) */
    #pedidos-table .cc-verificacion-btn {
        width: 36px;
        height: 36px;
        padding: 0;
        border-radius: 12px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        line-height: 1;
        font-size: 1.1rem;
    }
    #pedidos-table .cc-verificacion-btn.cc-status-none {
        background: #e9ecef;
        color: #0d6efd;
        border: 1px solid rgba(0,0,0,0.06);
    }
    #pedidos-table .cc-verificacion-btn.cc-status-pending {
        background: #fff3cd;
        color: #5f4700;
        border: 1px solid rgba(0,0,0,0.06);
    }
    #pedidos-table .cc-verificacion-btn.cc-status-match {
        background: #198754;
        color: #fff;
        border: 1px solid rgba(0,0,0,0.06);
    }
    .cc-verificacion-img-preview {
        max-width: 100%;
        max-height: 360px;
        object-fit: contain;
        background: #f8f9fa;
        border-radius: 14px;
        border: 1px solid rgba(0,0,0,0.06);
    }
    .cc-inline-code {
        font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
        word-break: break-word;
    }

</style>

            <div class="card mb-4">
                <div class="card-body">
                    <form method="GET" action="ruta_contraentrega.php" class="row g-3 align-items-center">
                        <div class="col-auto">
                            <label for="q" class="form-label">Buscar</label>
                            <input type="text" name="q" id="q" class="form-control" value="<?php echo htmlspecialchars($search_query); ?>" placeholder="Nombre, DNI o Celular">
                        </div>
                        <div class="col-auto">
                            <label for="mes" class="form-label">Mes</label>
                            <select name="mes" id="mes" class="form-select">
                                <option value="">Todos</option>
                                <?php foreach ($months as $num => $name): ?>
                                    <option value="<?php echo $num; ?>" <?php echo $selected_month == $num ? 'selected' : ''; ?>><?php echo $name; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-auto">
                            <label for="año" class="form-label">Año</label>
                            <select name="año" id="año" class="form-select">
                                <option value="">Todos</option>
                                <?php foreach ($years as $year): ?>
                                    <option value="<?php echo $year; ?>" <?php echo $selected_year == $year ? 'selected' : ''; ?>><?php echo $year; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php
                            $qParam = !empty($search_query) ? '&q=' . urlencode((string)$search_query) : '';
                        ?>
                        <div class="col-12">
                            <div class="d-flex flex-wrap gap-2 align-items-center">
                                <span class="text-muted fw-semibold me-2">Fecha:</span>
                                <a href="ruta_contraentrega.php?period=today<?php echo htmlspecialchars($qParam, ENT_QUOTES, 'UTF-8'); ?>" class="btn btn-outline-primary btn-sm <?php echo $period == 'today' ? 'active' : ''; ?>">Hoy</a>
                                <a href="ruta_contraentrega.php?period=yesterday<?php echo htmlspecialchars($qParam, ENT_QUOTES, 'UTF-8'); ?>" class="btn btn-outline-primary btn-sm <?php echo $period == 'yesterday' ? 'active' : ''; ?>">Ayer</a>
                                <a href="ruta_contraentrega.php?period=7<?php echo htmlspecialchars($qParam, ENT_QUOTES, 'UTF-8'); ?>" class="btn btn-outline-primary btn-sm <?php echo $period == '7' ? 'active' : ''; ?>">7 Días</a>
                                <a href="ruta_contraentrega.php?period=15<?php echo htmlspecialchars($qParam, ENT_QUOTES, 'UTF-8'); ?>" class="btn btn-outline-primary btn-sm <?php echo $period == '15' ? 'active' : ''; ?>">15 Días</a>
                                <a href="ruta_contraentrega.php?period=month<?php echo htmlspecialchars($qParam, ENT_QUOTES, 'UTF-8'); ?>" class="btn btn-outline-primary btn-sm <?php echo $period == 'month' ? 'active' : ''; ?>">Este Mes</a>
                            </div>
                        </div>
                        <div class="col-auto mt-2">
                            <button type="submit" class="btn btn-info">Filtrar</button>
                            <a href="ruta_contraentrega.php" class="btn btn-secondary">Limpiar</a>
                            <?php if (in_array($user_role, ['Administrador', 'admin', 'Asesor'], true)): ?>
                                <button type="button" class="btn btn-primary ms-2" data-bs-toggle="modal" data-bs-target="#nuevoPedidoContraentregaModal">
                                    AGREGAR PEDIDOS CONTRAENTREGA
                                </button>
                            <?php endif; ?>
                            <?php
                            $excelParams = array_filter([
                                'q' => $search_query,
                            ], static function ($value) {
                                return $value !== '' && $value !== null;
                            });
                            $excelUrl = 'download_ruta_contraentrega.php' . (!empty($excelParams) ? '?' . http_build_query($excelParams) : '');
                            ?>
                            <a href="<?php echo htmlspecialchars($excelUrl); ?>" class="btn btn-success">
                                <i class="fas fa-file-excel me-1"></i> Descargar Excel (Mañana)
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <div class="card">
                <div class="card-body p-0">
                    <div class="excel-container cc-ruta-contraentrega-container">
                        <table id="pedidos-table" class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th style="width: 120px;">ID</th>
                                    <th style="width: 120px;">Seguimiento</th>
                                    <th style="width: 130px;">Paquete</th>
                                    <th style="width: 180px;">Estado</th>
                                    <th style="width: 180px;">Cliente</th>
                                    
                                    <th style="width: 120px;">Celular</th>
                                    <th style="width: 250px;">Dirección</th>
                                    <th style="width: 200px;">Referencia</th>
                                    <th style="width: 140px;">Departamento</th>
                                    <th style="width: 140px;">Provincia</th>
                                    <th style="width: 140px;">Distrito</th>
                                    <th style="width: 150px;">Coordenadas</th>
                                    <th style="width: 200px;">Producto</th>
                                    <th style="width: 320px;">Dedicatoria / Obs.</th>
                                    <th style="width: 80px;">Cant.</th>
                                    <?php if ($user_role !== 'Logistica'): ?>
                                        <th style="width: 100px;">Total</th>
                                        <th style="width: 100px;">Debe</th>
                                    <?php endif; ?>
                                    <th style="width: 120px;">F. Entrega</th>
                                    <?php if ($user_role !== 'Asesor'): ?><th style="width: 120px;">Asesor</th><?php endif; ?>
                                    <th style="width: 150px;">F. Creación</th>
                                    <th style="width: 120px;">Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($pedidos as $pedido): ?>
                                    <tr>
                                        <?php
                                            $ccVerifTracking = trim((string)($pedido['contraentrega_verificacion_tracking'] ?? ''));
                                            $ccVerifImg = trim((string)($pedido['contraentrega_verificacion_imagen_path'] ?? ''));
                                            $ccVerifReady = $ccVerifTracking !== '' && $ccVerifImg !== '';
                                            $ccSeguimiento = trim((string)($pedido['seguimiento'] ?? ''));
                                            $ccVerifMatch = $ccVerifReady && $ccSeguimiento !== '' && $ccSeguimiento === $ccVerifTracking;

                                            $ccVerifBtnClass = $ccVerifMatch ? 'cc-status-match' : ($ccVerifReady ? 'cc-status-pending' : 'cc-status-none');
                                            $ccVerifIcon = $ccVerifMatch ? '✅' : '📷';
                                        ?>
                                        <td data-order="<?php echo (int)$pedido['id']; ?>">
                                            <div class="cc-id-verif d-flex align-items-center gap-2">
                                                <span class="cc-order-id"><?php echo htmlspecialchars($pedido['id']); ?></span>
                                                <button type="button" class="btn btn-sm cc-verificacion-btn <?php echo $ccVerifBtnClass; ?>"
                                                    data-bs-toggle="modal" data-bs-target="#contraentregaVerificacionModal"
                                                    data-pedido-id="<?php echo htmlspecialchars((string)$pedido['id'], ENT_QUOTES, 'UTF-8'); ?>"
                                                    data-nombre-completo="<?php echo htmlspecialchars((string)($pedido['nombre_completo'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>"
                                                    data-celular="<?php echo htmlspecialchars((string)($pedido['celular'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>"
                                                    data-verificacion-tracking="<?php echo htmlspecialchars($ccVerifTracking, ENT_QUOTES, 'UTF-8'); ?>"
                                                    data-verificacion-imagen="<?php echo htmlspecialchars($ccVerifImg, ENT_QUOTES, 'UTF-8'); ?>"
                                                    data-seguimiento="<?php echo htmlspecialchars($ccSeguimiento, ENT_QUOTES, 'UTF-8'); ?>"
                                                    aria-label="Verificación de contraentrega">
                                                    <?php echo $ccVerifIcon; ?>
                                                </button>
                                            </div>
                                        </td>
                                        <td class="editable" data-id="<?php echo $pedido['id']; ?>" data-field="seguimiento"><?php echo htmlspecialchars($pedido['seguimiento'] ?? ''); ?></td>
                                        <td class="editable-paquete" data-id="<?php echo $pedido['id']; ?>" data-value="<?php echo htmlspecialchars($pedido['tipo_paquete'] ?? ''); ?>" style="cursor: pointer;">
                                            <span class="badge" style="<?php echo getPaqueteStyle($pedido['tipo_paquete'] ?? ''); ?>">
                                                <?php echo htmlspecialchars(!empty($pedido['tipo_paquete']) ? $pedido['tipo_paquete'] : 'Seleccionar'); ?>
                                            </span>
                                        </td>
                                        <td class="editable-estado" data-id="<?php echo $pedido['id']; ?>" data-value="<?php echo htmlspecialchars($pedido['estado'] ?? ''); ?>" style="cursor: pointer;">
                                            <span class="badge" style="<?php echo getStatusStyle($pedido['estado'] ?? ''); ?>">
                                                <?php echo htmlspecialchars(!empty($pedido['estado']) ? $pedido['estado'] : 'Seleccionar'); ?>
                                            </span>
                                        </td>
                                        <td><?php echo htmlspecialchars($pedido['nombre_completo']); ?></td>
                                        
                                        <td>
                                            <?php 
                                            $celular = htmlspecialchars($pedido['celular']);
                                            // Basic validation to ensure it's a potential number
                                            if (!empty($celular)) {
                                                // Prepend country code if missing (assuming Peru's country code '51')
                                                $whatsapp_number = $celular;
                                                if (strlen($celular) == 9 && substr($celular, 0, 1) == '9') {
                                                    $whatsapp_number = '51' . $celular;
                                                }

                                                $monto_debe = htmlspecialchars($pedido['monto_debe']);
                                                $monto_formateado = 'S/' . $monto_debe;
                                                $direccion = htmlspecialchars($pedido['direccion_exacta'] ?? 'N/A');
                                                $cliente = htmlspecialchars($pedido['nombre_completo']);

                                                // Reemplazar placeholders en la plantilla
                                                $mensaje = str_replace(
                                                    ['{cliente}', '{monto}', '{direccion}'],
                                                    [$cliente, $monto_formateado, $direccion],
                                                    $whatsapp_template
                                                );
                                                $mensaje_encoded = urlencode($mensaje);
                                                
                                                $whatsapp_url = 'https://wa.me/' . $whatsapp_number . '?text=' . $mensaje_encoded;

                                                echo $celular;
                                                echo ' <a href="' . $whatsapp_url . '" target="_blank" rel="noopener noreferrer" style="text-decoration: none;">';
                                                echo '<i class="fab fa-whatsapp" style="color: green; font-size: 1.5em; vertical-align: middle;"></i>';
                                                echo '</a>';
                                            } else {
                                                echo 'N/A';
                                            }
                                            ?>
                                        </td>
                                        <td><?php echo htmlspecialchars($pedido['direccion_exacta'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($pedido['referencia_domicilio'] ?? 'N/A'); ?></td>
                                        <?php [$provinciaPedido, $distritoPedido] = splitProvinciaDistrito($pedido['codigo_rastreo'] ?? ''); ?>
                                        <td><?php echo htmlspecialchars($pedido['sede_envio'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($provinciaPedido); ?></td>
                                        <td><?php echo htmlspecialchars($distritoPedido); ?></td>
                                        <td><?php echo htmlspecialchars($pedido['coordenadas'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($pedido['producto']); ?></td>
                                        <?php
                                            $nota_adicional = trim((string)($pedido['nota_adicional'] ?? ''));
                                            if ($nota_adicional === '') {
                                                $nota_adicional = trim((string)($pedido['descargo'] ?? ''));
                                            }
                                            $nota_adicional_display = $nota_adicional !== '' ? $nota_adicional : 'N/A';
                                        ?>
                                        <td style="max-width: 320px; white-space: normal; word-break: break-word;">
                                            <?php echo htmlspecialchars($nota_adicional_display); ?>
                                        </td>
                                        <td><?php echo htmlspecialchars($pedido['cantidad']); ?></td>
                                        <?php if ($user_role !== 'Logistica'): ?>
                                            <td><?php echo htmlspecialchars($pedido['monto_total']); ?></td>
                                            <td><?php echo htmlspecialchars($pedido['monto_debe']); ?></td>
                                        <?php endif; ?>
                                        <td><span class="badge" style="<?php echo getFechaEntregaStyle($pedido['fecha_entrega']); ?>"><?php echo htmlspecialchars(!empty($pedido['fecha_entrega']) && $pedido['fecha_entrega'] != '0000-00-00' ? date('d/m/Y', strtotime($pedido['fecha_entrega'])) : 'N/A'); ?></span></td>
                                        <?php if ($user_role !== 'Asesor'): ?><td><?php echo htmlspecialchars($pedido['asesor_nombre'] ?? 'N/A'); ?></td><?php endif; ?>
                                        <td><?php echo htmlspecialchars($pedido['created_at']); ?></td>
                                        <td>
                                            <a href="pedidos_contraentrega.php?id=<?php echo $pedido['id']; ?>" class="btn btn-sm btn-warning">Editar</a>
                                            <?php if ($user_role === 'Administrador'): ?>
                                                <a href="delete_pedido.php?id=<?php echo $pedido['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('¿Estás seguro de que quieres eliminar este pedido?');">Eliminar</a>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        <?php if (empty($pedidos)): ?>
                            <p class="text-center">No hay pedidos que coincidan con el filtro.</p>
                        <?php endif; ?>
                        </table>
                    </div>
                </div>
            </div>





<?php if (in_array($user_role, ['Administrador', 'admin', 'Asesor'], true)): ?>
<div class="modal fade" id="nuevoPedidoContraentregaModal" tabindex="-1" aria-labelledby="nuevoPedidoContraentregaModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable" style="max-width: 95vw;">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="nuevoPedidoContraentregaModalLabel">Agregar Pedidos Contraentrega</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body p-0">
                <iframe id="nuevoPedidoContraentregaIframe" title="Formulario de pedidos contraentrega" src="about:blank" style="width:100%; height:90vh; border:0;"></iframe>
            </div>
        </div>
    </div>
</div>


<?php endif; ?><div class="modal fade" id="contraentregaVerificacionModal" tabindex="-1" aria-labelledby="contraentregaVerificacionModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable" style="max-width: 95vw;">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="contraentregaVerificacionModalLabel">Verificación Contraentrega (Foto + Tracking)</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>

            <div class="modal-body">
                <div class="row g-3">
                    <div class="col-md-7">
                        <div class="mb-2">
                            <div class="text-muted small">Pedido #<span id="ccVerifPedidoIdText"></span></div>
                        </div>

                        <div class="mb-3">
                            <img id="ccVerifPreviewImg" class="cc-verificacion-img-preview" src="" alt="Imagen de verificación" style="display:none;">
                            <div id="ccVerifNoImg" class="text-muted" style="display:none;">Sin imagen cargada todavía.</div>

                            <div class="mt-2">
                                <div class="fw-semibold fs-3" id="ccVerifNombreDestinatario"></div>
                                <div class="text-muted fs-3" id="ccVerifNumeroDestinatario"></div>
                            </div>
                        </div>

                        <div class="alert alert-info mb-0" role="alert" style="padding: 0.6rem 0.85rem;">
                            <div class="small">
                                <strong>Tip:</strong> La otra persona debe revisar que el <em>tracking</em> coincida con el <em>nombre del destinatario</em> que aparece en la foto.
                            </div>
                        </div>
                    </div>

                    <div class="col-md-5">
                        <input type="hidden" id="ccVerifPedidoIdHidden" value="">

                        <div id="ccVerifEditSection" style="<?php echo ($user_role === 'Logistica') ? 'display:none;' : ''; ?>">
                            <div class="mb-3">
                                <label for="ccVerifImageInput" class="form-label">Subir imagen del paquete</label>
                                <input type="file" class="form-control" id="ccVerifImageInput" accept="image/*">
                                <div class="form-text">Foto del estado del paquete donde se vea el tracking y el nombre.</div>
                            </div>

                            <div class="mb-3">
                                <label for="ccVerifTrackingInput" class="form-label">Tracking (código)</label>
                                <input type="text" class="form-control" id="ccVerifTrackingInput" placeholder="Ej: 123456...">
                            </div>

                            <button type="button" class="btn btn-primary w-100" id="ccVerifSaveBtn">Guardar verificación</button>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Tracking guardado (para copiar a “Seguimiento”)</label>
                            <div class="p-2 rounded bg-light">
                                <span id="ccVerifTrackingSaved" class="cc-inline-code text-break"></span>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Seguimiento actual (campo editable en la tabla)</label>
                            <div class="p-2 rounded bg-light">
                                <span id="ccVerifSeguimientoActual" class="cc-inline-code text-break"></span>
                            </div>
                        </div>

                        <div class="d-grid gap-2">
                            <button type="button" class="btn btn-success" id="ccVerifCopyBtn" disabled>Copiar tracking</button>
                            <div class="text-muted small" id="ccVerifCopyHint">Luego pegalo en la celda “Seguimiento”.</div>
                        </div>

                        <div id="ccVerifErrorBox" class="alert alert-danger mt-3 d-none" role="alert"></div>
                        <div id="ccVerifSuccessBox" class="alert alert-success mt-3 d-none" role="alert"></div>
                    </div>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
            </div>
        </div>
    </div>
</div>

<script>
(() => {
    const modalEl = document.getElementById('contraentregaVerificacionModal');
    if (!modalEl) return;

    const pedidoIdText = document.getElementById('ccVerifPedidoIdText');
    const pedidoIdHidden = document.getElementById('ccVerifPedidoIdHidden');
    const nombreEl = document.getElementById('ccVerifNombreDestinatario');
    const numeroEl = document.getElementById('ccVerifNumeroDestinatario');

    const previewImg = document.getElementById('ccVerifPreviewImg');
    const noImgEl = document.getElementById('ccVerifNoImg');

    const trackingSavedEl = document.getElementById('ccVerifTrackingSaved');
    const seguimientoActualEl = document.getElementById('ccVerifSeguimientoActual');

    const editSection = document.getElementById('ccVerifEditSection');
    const imageInput = document.getElementById('ccVerifImageInput');
    const trackingInput = document.getElementById('ccVerifTrackingInput');

    const saveBtn = document.getElementById('ccVerifSaveBtn');
    const copyBtn = document.getElementById('ccVerifCopyBtn');

    const errorBox = document.getElementById('ccVerifErrorBox');
    const successBox = document.getElementById('ccVerifSuccessBox');

    function showBox(boxEl, msg) {
        boxEl.textContent = msg;
        boxEl.classList.remove('d-none');
    }
    function hideBoxes() {
        errorBox.classList.add('d-none');
        errorBox.textContent = '';
        successBox.classList.add('d-none');
        successBox.textContent = '';
    }

    function setPreviewImage(imgPath) {
        if (imgPath) {
            previewImg.src = imgPath;
            previewImg.style.display = 'block';
            noImgEl.style.display = 'none';
        } else {
            previewImg.src = '';
            previewImg.style.display = 'none';
            noImgEl.style.display = 'block';
        }
    }

    modalEl.addEventListener('show.bs.modal', (event) => {
        const btn = event.relatedTarget;
        if (!btn) return;

        hideBoxes();

        const pedidoId = btn.getAttribute('data-pedido-id') || '';
        const nombre = btn.getAttribute('data-nombre-completo') || '';
        const celular = btn.getAttribute('data-celular') || '';
        const verifTracking = btn.getAttribute('data-verificacion-tracking') || '';
        const verifImg = btn.getAttribute('data-verificacion-imagen') || '';
        const seguimiento = btn.getAttribute('data-seguimiento') || '';

        pedidoIdHidden.value = pedidoId;
        if (pedidoIdText) pedidoIdText.textContent = pedidoId;
        if (nombreEl) nombreEl.textContent = nombre;
        if (numeroEl) numeroEl.textContent = celular || 'N/A';

        trackingSavedEl.textContent = verifTracking || 'N/A';
        seguimientoActualEl.textContent = seguimiento || 'N/A';

        if (editSection && editSection.style.display !== 'none') {
            // Solo precargar tracking si hay editor visible (evita confusiones a Logistica)
            if (trackingInput) trackingInput.value = verifTracking || '';
        }

        setPreviewImage(verifImg);

        // Copy button enabled only when there is a saved tracking and an image
        copyBtn.disabled = !(verifTracking && verifImg);

        // Reset file input
        if (imageInput) {
            imageInput.value = '';
        }
    });

    if (imageInput) {
        imageInput.addEventListener('change', () => {
            const file = imageInput.files && imageInput.files[0] ? imageInput.files[0] : null;
            if (!file) return;

            const reader = new FileReader();
            reader.onload = (e) => {
                previewImg.src = e.target.result;
                previewImg.style.display = 'block';
                if (noImgEl) noImgEl.style.display = 'none';
            };
            reader.readAsDataURL(file);
        });
    }

    if (saveBtn) {
        saveBtn.addEventListener('click', async () => {
            hideBoxes();

            const pedidoId = pedidoIdHidden.value;
            const tracking = (trackingInput && trackingInput.value ? trackingInput.value : '').trim();
            const file = imageInput && imageInput.files && imageInput.files[0] ? imageInput.files[0] : null;

            if (!tracking) {
                showBox(errorBox, 'Ingresá el tracking (código) para guardar la verificación.');
                return;
            }

            if (!file) {
                showBox(errorBox, 'Seleccioná una imagen para guardar la verificación.');
                return;
            }

            saveBtn.disabled = true;
            const oldText = saveBtn.textContent;
            saveBtn.textContent = 'Guardando...';

            try {
                const fd = new FormData();
                fd.append('pedido_id', pedidoId);
                fd.append('tracking_verificacion', tracking);
                fd.append('imagen', file);

                const resp = await fetch('save_contraentrega_verificacion.php', {
                    method: 'POST',
                    body: fd
                });

                const data = await resp.json();
                if (!data || !data.success) {
                    showBox(errorBox, (data && data.error) ? data.error : 'No se pudo guardar la verificación.');
                    return;
                }

                showBox(successBox, 'Verificación guardada ✅');

                const modalInstance = bootstrap.Modal.getInstance(modalEl) || new bootstrap.Modal(modalEl);
                modalInstance.hide();

                // Reload to update icon/status
                window.location.href = window.location.pathname + window.location.search;
            } catch (e) {
                console.error(e);
                showBox(errorBox, 'Error de conexión al guardar.');
            } finally {
                saveBtn.disabled = false;
                saveBtn.textContent = oldText;
            }
        });
    }

    async function copyTextToClipboard(text) {
        if (navigator.clipboard && navigator.clipboard.writeText) {
            await navigator.clipboard.writeText(text);
            return true;
        }

        const ta = document.createElement('textarea');
        ta.value = text;
        ta.style.position = 'fixed';
        ta.style.top = '-1000px';
        ta.style.left = '-1000px';
        document.body.appendChild(ta);
        ta.focus();
        ta.select();
        let ok = false;
        try {
            ok = document.execCommand('copy');
        } catch (err) {
            ok = false;
        }
        document.body.removeChild(ta);
        return ok;
    }

    if (copyBtn) {
        copyBtn.addEventListener('click', async () => {
            hideBoxes();

            const text = (trackingSavedEl && trackingSavedEl.textContent ? trackingSavedEl.textContent : '').trim();
            if (!text) {
                showBox(errorBox, 'No hay tracking guardado para copiar.');
                return;
            }

            try {
                const ok = await copyTextToClipboard(text);
                if (!ok) {
                    showBox(errorBox, 'No se pudo copiar al portapapeles.');
                    return;
                }
                showBox(successBox, 'Copiado ✅ Pegalo en la celda “Seguimiento”.');
            } catch (e) {
                console.error(e);
                showBox(errorBox, 'No se pudo copiar al portapapeles.');
            }
        });
    }
})();
</script>



<script>
document.addEventListener('DOMContentLoaded', function() {
    const nuevoPedidoModalEl = document.getElementById('nuevoPedidoContraentregaModal');
    if (!nuevoPedidoModalEl) return;

    const nuevoPedidoIframe = document.getElementById('nuevoPedidoContraentregaIframe');
    let nuevoPedidoModalReloadGuard = false;

    window.addEventListener('message', function(event) {
        const data = event.data;
        if (!data || typeof data !== 'object') return;
        if (data.type === 'pedido_contraentrega_form_success') {
            if (nuevoPedidoModalReloadGuard) return;
            nuevoPedidoModalReloadGuard = true;

            const modalInstance = bootstrap.Modal.getInstance(nuevoPedidoModalEl) || new bootstrap.Modal(nuevoPedidoModalEl);
            modalInstance.hide();
            window.location.reload();
        }
    });

    nuevoPedidoModalEl.addEventListener('show.bs.modal', function() {
        nuevoPedidoModalReloadGuard = false;
        if (nuevoPedidoIframe) {
            nuevoPedidoIframe.src = 'pedidos_contraentrega.php?embed=1&t=' + Date.now();
        }
    });

    if (nuevoPedidoIframe) {
        nuevoPedidoIframe.addEventListener('load', function() {
            if (nuevoPedidoModalReloadGuard) return;

            const src = nuevoPedidoIframe.src || '';
            if (src.includes('success=1')) {
                nuevoPedidoModalReloadGuard = true;
                const modalInstance = bootstrap.Modal.getInstance(nuevoPedidoModalEl) || new bootstrap.Modal(nuevoPedidoModalEl);
                modalInstance.hide();
                window.location.reload();
            }
        });
    }
});
</script>

<script>
function getPaqueteStyleJS(paquete) {
    if (paquete === 'RUTA') return 'background-color: #0dcaf0; color: black;';
    if (paquete === 'ANULADO') return 'background-color: #212529; color: white;';
    if (paquete === 'PENDIENTE A RETORNO') return 'background-color: #dc3545; color: white;';
    if (paquete === 'RETORNADO') return 'background-color: #dc3545; color: white;';
    if (paquete === 'COMPLETADO') return 'background-color: #198754; color: white;';
    if (paquete === 'PREPARADO') return 'background-color: #20c997; color: white;';
    if (paquete === 'EMPAQUETADO') return 'background-color: #20c997; color: white;';
    return 'background-color: #6c757d; color: white;';
}

function normalizeTipoPaqueteValueClient(value) {
    if (!value) return '';

    const cleaned = String(value)
        .replace(/[\u00A0\u200B-\u200D\uFEFF]/g, ' ')
        .replace(/[\x00-\x1F\x7F]/g, ' ')
        .trim()
        .replace(/\s+/g, ' ')
        .toUpperCase();

    const compact = cleaned.replace(/[^A-Z]+/g, '');
    const aliases = {
        RUTA: 'RUTA',
        CONTRAENTREGA: 'CONTRAENTREGA',
        NOCONTESTAVOLVERALLAMAR: 'NO CONTESTA, VOLVER A LLAMAR',
        PENDIENTEARETORNO: 'PENDIENTE A RETORNO',
        COMPLETADO: 'COMPLETADO',
        EMPAQUETADO: 'PREPARADO',
        PREPARADO: 'PREPARADO',
        EMPAQUETARDO: 'PREPARADO',
        RETORNADO: 'RETORNADO',
        ANULADO: 'ANULADO'
    };

    return aliases[compact] || cleaned;
}

function getStatusStyleJS(status) {
    let bgColor = '#0dcaf0';
    let style = 'color: white;';
    
    switch (status.toUpperCase().trim()) {
        case 'RUTA_CONTRAENTREGA':
            bgColor = '#007bff';
            break;
        case 'PENDIENTE':
            bgColor = '#fff3cd';
            style = 'color: #5f4700;';
            break;
        case 'NO CONTESTO, VOLVER A LLAMAR':
            bgColor = '#fd7e14';
            break;
        case 'CANCELADO':
        case 'CANCELAR':
            bgColor = '#8b1e2d';
            break;
        case 'REPROGRAMADO':
            bgColor = '#6f42c1';
            break;
        case 'ENTREGA EXITOSA':
            bgColor = '#198754';
            break;
        case 'RETORNADO':
            bgColor = '#dc3545';
            break;
        case 'NO CONTESTO, DEVOLVER LLAMADA':
            bgColor = '#fd7e14';
            break;
        default:
            bgColor = '#6c757d';
    }
    return `background-color: ${bgColor} !important; ${style}`;
}

$(document).ready(function() {
    $('#pedidos-table').DataTable({
        "language": {
            "url": "//cdn.datatables.net/plug-ins/1.10.25/i18n/Spanish.json"
        },
        "order": [[ 0, "desc" ]],
        "paging": false,
        "lengthChange": false,
        "info": false,
        "scrollX": false // Desactivamos scrollX de DataTables para usar nuestro excel-container
    });
});

document.addEventListener('DOMContentLoaded', function() {
    const table = document.querySelector('.table');

    table.addEventListener('click', function(e) {
        // Handle Paquete editing
        if (e.target && (e.target.classList.contains('editable-paquete') || e.target.closest('.editable-paquete'))) {
            const cell = e.target.classList.contains('editable-paquete') ? e.target : e.target.closest('.editable-paquete');
            
            if (cell.querySelector('select')) return; // Already editing

            const currentVal = cell.dataset.value;
            const pedidoId = cell.dataset.id;

            const select = document.createElement('select');
            select.className = 'form-select form-select-sm';
            
            const options = <?php echo json_encode(array_merge(
                [['val' => '', 'text' => 'Seleccionar']],
                array_map(static function ($paquete) {
                    return ['val' => $paquete, 'text' => $paquete];
                }, tipoPaquetePrimarySelectorValues())
            ), JSON_UNESCAPED_UNICODE); ?>;

            options.forEach(opt => {
                const option = document.createElement('option');
                option.value = opt.val;
                option.text = opt.text;
                if (opt.val === currentVal) option.selected = true;
                select.appendChild(option);
            });

            // Save original content to restore if needed
            const originalContent = cell.innerHTML;
            
            cell.innerHTML = '';
            cell.appendChild(select);
            select.focus();

            const save = () => {
                const newVal = normalizeTipoPaqueteValueClient(select.value);
                
                // Optimistic update
                cell.dataset.value = newVal;
                cell.innerHTML = `<span class="badge" style="${getPaqueteStyleJS(newVal)}">${newVal || 'Seleccionar'}</span>`;

                if (newVal === currentVal) return; // No change

                const formData = new URLSearchParams();
                formData.append('pedido_id', pedidoId);
                formData.append('tipo_paquete', newVal);

                fetch('update_paquete.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: formData
                })
                .then(r => r.json())
                .then(data => {
                    if (!data.success) {
                        alert('Error: ' + (data.message || 'No se pudo actualizar.'));
                        cell.innerHTML = originalContent; // Revert
                        cell.dataset.value = currentVal;
                    }
                })
                .catch(err => {
                    console.error(err);
                    alert('Error de conexión.');
                    cell.innerHTML = originalContent; // Revert
                    cell.dataset.value = currentVal;
                });
            };

            select.addEventListener('change', save);
            select.addEventListener('blur', save);
        }

        // Handle Estado editing
        if (e.target && (e.target.classList.contains('editable-estado') || e.target.closest('.editable-estado'))) {
            const cell = e.target.classList.contains('editable-estado') ? e.target : e.target.closest('.editable-estado');
            
            if (cell.querySelector('select')) return; // Already editing

            const currentVal = cell.dataset.value;
            const pedidoId = cell.dataset.id;

            const select = document.createElement('select');
            select.className = 'form-select form-select-sm';
            
            const options = [
                {val: 'RUTA_CONTRAENTREGA', text: 'RUTA_CONTRAENTREGA'},
                {val: 'PENDIENTE', text: 'PENDIENTE'},
                {val: 'NO CONTESTO, DEVOLVER LLAMADA', text: 'NO CONTESTO, DEVOLVER LLAMADA'},
                {val: 'CANCELADO', text: 'CANCELADO'},
                {val: 'REPROGRAMADO', text: 'REPROGRAMADO'},
                {val: 'ENTREGA EXITOSA', text: 'ENTREGA EXITOSA'}
            ];

            options.forEach(opt => {
                const option = document.createElement('option');
                option.value = opt.val;
                option.text = opt.text;
                if (opt.val === 'CANCELADO') {
                    option.style.backgroundColor = '#8b1e2d';
                    option.style.color = '#ffffff';
                }
                if (opt.val === 'PENDIENTE') {
                    option.style.backgroundColor = '#fff3cd';
                    option.style.color = '#5f4700';
                }
                if (opt.val === currentVal) option.selected = true;
                select.appendChild(option);
            });

            const originalContent = cell.innerHTML;
            
            cell.innerHTML = '';
            cell.appendChild(select);
            select.focus();

            const save = () => {
                const newVal = select.value;
                
                if (newVal === currentVal) {
                    cell.innerHTML = originalContent;
                    return;
                }

                // Optimistic update
                cell.dataset.value = newVal;
                cell.innerHTML = `<span class="badge" style="${getStatusStyleJS(newVal)}">${newVal}</span>`;

                const formData = new URLSearchParams();
                formData.append('pedido_id', pedidoId);
                formData.append('estado', newVal);

                fetch('update_estado.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: formData
                })
                .then(r => r.json())
                .then(data => {
                    if (!data.success) {
                        alert('Error: ' + (data.message || 'No se pudo actualizar.'));
                        cell.innerHTML = originalContent; // Revert
                        cell.dataset.value = currentVal;
                    }
                })
                .catch(err => {
                    console.error(err);
                    alert('Error de conexión.');
                    cell.innerHTML = originalContent; // Revert
                    cell.dataset.value = currentVal;
                });
            };

            select.addEventListener('change', save);
            select.addEventListener('blur', save);
        }

        if (e.target && e.target.classList.contains('editable')) {
            const cell = e.target;
            if (cell.querySelector('input')) {
                return; // Already in edit mode
            }

            const originalContent = cell.textContent.trim();
            const input = document.createElement('input');
            input.type = 'text';
            input.className = 'form-control form-control-sm';
            input.value = originalContent === 'N/A' ? '' : originalContent;
            
            cell.innerHTML = '';
            cell.appendChild(input);
            input.focus();

            const saveChanges = function() {
                const newValue = input.value.trim();
                const pedidoId = cell.dataset.id;
                const field = cell.dataset.field;

                let endpoint = 'update_tracking.php'; // Default endpoint
                if (field === 'clave') {
                    endpoint = 'update_clave.php';
                }

                // Restore original content visually
                cell.textContent = newValue === '' ? 'N/A' : newValue;

                // Send data to server
                fetch(endpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({ id: pedidoId, field: field, value: newValue })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        console.error('Error:', data.error);
                        // Optionally revert the change and show an error message
                        cell.textContent = originalContent;
                        return;
                    }

                    // Si se actualizó "Seguimiento", actualizamos el icono de verificación en la misma fila
                    if (field === 'seguimiento') {
                        const row = cell.closest('tr');
                        if (row) {
                            const btn = row.querySelector('button.cc-verificacion-btn');
                            if (btn) {
                                const verifTracking = (btn.getAttribute('data-verificacion-tracking') || '').trim();
                                const verifImg = (btn.getAttribute('data-verificacion-imagen') || '').trim();

                                const hasVerif = verifTracking !== '' && verifImg !== '';
                                const match = hasVerif && (newValue === verifTracking);

                                btn.classList.remove('cc-status-none', 'cc-status-pending', 'cc-status-match');

                                if (!hasVerif) {
                                    btn.classList.add('cc-status-none');
                                } else if (match) {
                                    btn.classList.add('cc-status-match');
                                } else {
                                    btn.classList.add('cc-status-pending');
                                }

                                btn.textContent = match ? '✅' : '📷';
                                btn.setAttribute('data-seguimiento', newValue);
                            }
                        }
                    }
                })
                .catch(error => {
                    console.error('Fetch Error:', error);
                    cell.textContent = originalContent;
                });
            };

            input.addEventListener('blur', saveChanges);
            input.addEventListener('keydown', function(e) {
                if (e.key === 'Enter') {
                    input.blur();
                }
            });
        }
    });
});
</script>

<?php include 'layout_footer.php'; ?>