<?php $__env->startSection('content'); ?>
<!-- Font Awesome (CDN) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">

<div class="container-fluid">
    <div class="row">
		<div class="col-md-8 col-md-offset-2">
        <div class="d-flex justify-content-end mb-3">
            <button type="button" class="btn btn-light position-relative" id="notificacionesBtn" data-toggle="modal" data-target="#notificacionesModal">
                <i class="fas fa-bell fa-2x"></i>
                <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" id="badgeNotificaciones" style="display: none;">
                    0
                </span>
            </button>
        </div>
			<div class="panel panel-default">
                <div class="panel-heading"><center>Estado de Mesas</center></div>
                    <div class="panel-body">
                        <div class="card-body">
                            <hr>
                            <?php if(session('success')): ?>
                                <div class="alert alert-success">
                                    <?php echo e(session('success')); ?>

                                </div>
                            <?php endif; ?>
                            <?php if($errors->any()): ?>
                                <div class="alert alert-danger">
                                    <ul>
                                        <?php foreach($errors->all() as $error): ?>
                                            <li><?php echo e($error); ?></li>
                                        <?php endforeach; ?>
                                    </ul>
                                </div>
                            <?php endif; ?>

                            <div class="row">
                              <?php $__empty_1 = true; foreach($mesas as $mesa): $__empty_1 = false; ?>
                                <div class="col-md-2 col-sm-3 col-xs-4 mb-4">
                                    <a href="<?php echo e(route('gestionarMesa', $mesa->idMesa)); ?>" 
                                       class="btn btn-block mesa-btn text-white"
                                       style="background-color: <?php echo e($mesa->estado == 1 ? '#e74c3c' : '#2ecc71'); ?>;">
                                        <div class="text-center">
                                            <i class="fas fa-utensils fa-2x d-block mb-1"></i>
                                            <h5 class="mb-1"><strong><?php echo e($mesa->descripcion); ?></strong></h5>
                                            <span class="badge badge-light mesa-estado">
                                                <?php echo e($mesa->estado == 1 ? '🟥 Ocupada' : '🟩 Libre'); ?>

                                            </span>
                                        </div>
                                    </a>
                                </div>
                              <?php endforeach; if ($__empty_1): ?>
                                <div class="col-12">
                                    <p class="text-center">🚫 No hay mesas registradas.</p>
                                </div>
                              <?php endif; ?>
                            </div>
                        </div>
                    </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal de Notificaciones -->
<div class="modal fade" id="notificacionesModal" tabindex="-1" role="dialog" aria-labelledby="notificacionesModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="notificacionesModalLabel">Pedidos Preparados</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body" id="listaNotificaciones">
        <p class="text-center">🔄 Cargando notificaciones...</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const btn = document.getElementById('notificacionesBtn');
    const badge = document.getElementById('badgeNotificaciones');
    const lista = document.getElementById('listaNotificaciones');

    function cargarNotificaciones() {
        fetch('<?php echo e(route('notificaciones.pedidos')); ?>')
        .then(res => res.json())
        .then(data => {
            if (data.length > 0) {
                badge.style.display = 'inline-block';
                badge.textContent = data.length;

                lista.innerHTML = ''; // Limpiar la lista antes de llenarla con nuevas notificaciones

                data.forEach(pedido => {
                    const div = document.createElement('div');
                    div.className = 'alert alert-info';
                    div.innerHTML = `
                        <strong>Pedido #${pedido.idPedido}</strong><br>
                        Mesa: <strong>${pedido.nombre_mesa}</strong><br>
                        Cliente: <strong>${pedido.cliente}</strong><br>
                        Atendido por: <strong>${pedido.mesero}</strong><br>
                        Fecha: <em>${pedido.created_at}</em><br>
                        Estado: <span class="badge badge-success">Preparado</span><br>
                        <button class="btn btn-sm btn-secondary marcarLeida" data-id="${pedido.idPedido}">Marcar como leída</button>
                    `;
                    lista.appendChild(div);
                });

                document.querySelectorAll('.marcarLeida').forEach(button => {
                    button.addEventListener('click', function () {
                        const idPedido = this.getAttribute('data-id');
                        console.log("Marcando como leída el pedido con ID: " + idPedido);
                        
                        // Modificación aquí: Envía el idPedido directamente en la URL
                        fetch(`/marcar-leida/${idPedido}`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>' // Asegúrate de incluir el token CSRF
                            },
                            // No necesitas un body si el idPedido ya va en la URL
                            // body: JSON.stringify({ idPedido }) // Esto se elimina
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                this.closest('.alert').remove();
                                const count = parseInt(badge.textContent, 10) - 1;
                                badge.textContent = count > 0 ? count : 0;
                                if (count === 0) badge.style.display = 'none';
                            } else {
                                alert('Hubo un error al marcar la notificación como leída');
                            }
                        })
                        .catch(error => {
                            console.error('Error al marcar como leída:', error);
                            alert('Error de red al marcar la notificación.');
                        });
                    });
                });

            } else {
                badge.style.display = 'none';
                lista.innerHTML = '<p class="text-center">✅ No hay pedidos preparados.</p>';
            }
        })
        .catch(error => {
            console.error('Error al cargar notificaciones:', error);
            lista.innerHTML = '<p class="text-danger">⚠️ Error al cargar notificaciones.</p>';
        });
    }

    // Cargar al abrir modal
    $('#notificacionesModal').on('show.bs.modal', function () {
        cargarNotificaciones();
    });

    // También puedes refrescar cada X segundos (opcional)
    setInterval(cargarNotificaciones, 5000); // cada 5 segundos
});
</script>

<style>

    #badgeNotificaciones {
    display: block; /* Siempre visible */
    background-color: red;
    font-weight: bold;
    color: white;
}
    .mesa-btn {
        height: 100px;
        border-radius: 12px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        text-decoration: none;
        transition: transform 0.2s ease;
        font-family: 'Segoe UI', sans-serif;
        color: #fff !important;
    }

    .mesa-btn:hover {
        transform: translateY(-3px);
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.25);
    }

    .mesa-estado {
        font-size: 0.85rem;
        padding: 5px 10px;
        border-radius: 50px;
        background-color: rgba(255, 255, 255, 0.8);
        color: #333;
    }
</style>

<?php $__env->stopSection(); ?>

<?php $__env->startSection('styles'); ?>

<?php $__env->appendSection(); ?>

<?php echo $__env->make('app', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>