<?= $this->extend('layouts/admin') ?>

<?= $this->section('title') ?>Ocupación de Función<?= $this->endSection() ?>

<?= $this->section('content') ?>
<div style="display: flex; flex-direction: column; gap: 24px;">

    <!-- Volver y Cabecera -->
    <div style="display: flex; justify-content: space-between; align-items: center; gap: 16px;">
        <div>
            <a href="<?= base_url('admin/funciones') ?>" style="text-decoration: none; color: var(--admin-accent); font-weight: 700; font-size: 0.9rem; display: inline-flex; align-items: center; gap: 6px; margin-bottom: 8px;">
                ⬅️ Volver a Funciones
            </a>
            <h2 style="margin: 0; font-size: 1.8rem; color: var(--admin-text);">Mapa de Ocupación en Tiempo Real</h2>
            <p style="margin: 4px 0 0; color: var(--admin-muted);">Monitorea la venta de boletos y disponibilidad de butacas para esta función.</p>
        </div>
        <button id="btnRefrescar" class="btn btn-secondary" style="display: inline-flex; align-items: center; gap: 8px;">
            🔄 Refrescar Estado
        </button>
    </div>

    <!-- Contenido Principal -->
    <div style="display: flex; gap: 24px; flex-wrap: wrap;">

        <!-- Datos de la Función y Métricas -->
        <div style="flex: 1; min-width: 300px; display: flex; flex-direction: column; gap: 20px;">
            
            <!-- Ficha de la Función -->
            <div style="background: var(--admin-surface); border: 1px solid var(--admin-border); border-radius: 24px; padding: 24px; box-shadow: 0 8px 30px rgba(15,23,42,0.04);">
                <h3 style="margin-top: 0; margin-bottom: 16px; font-size: 1.2rem; color: var(--admin-text); border-bottom: 1px solid var(--admin-border); padding-bottom: 12px;">Detalles de Programación</h3>
                
                <div style="display: flex; gap: 16px; margin-bottom: 16px;">
                    <?php if ($funcion->pelicula_poster): ?>
                        <img src="<?= base_url('uploads/posters/' . $funcion->pelicula_poster) ?>" 
                             onerror="this.src='https://placehold.co/80x120?text=Poster'" 
                             alt="Poster" style="width: 70px; height: 100px; border-radius: 12px; object-fit: cover; box-shadow: 0 4px 12px rgba(0,0,0,0.15);">
                    <?php else: ?>
                        <div style="width: 70px; height: 100px; background: var(--admin-surface-alt); border: 1px solid var(--admin-border); border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 0.75rem; color: var(--admin-muted); text-align: center;">Sin Poster</div>
                    <?php endif; ?>
                    
                    <div>
                        <h4 style="margin: 0 0 6px; font-size: 1.1rem; color: var(--admin-text);"><?= esc($funcion->pelicula_titulo) ?></h4>
                        <p style="margin: 0 0 4px; font-size: 0.85rem; color: var(--admin-muted);"><strong>Duración:</strong> <?= esc($funcion->pelicula_duracion) ?> minutos</p>
                        <p style="margin: 0; font-size: 0.85rem; color: var(--admin-muted);"><strong>Precio Base:</strong> S/. <?= number_format($funcion->precio_base, 2) ?></p>
                    </div>
                </div>

                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 14px; font-size: 0.9rem;">
                    <div>
                        <span style="color: var(--admin-muted); font-size: 0.8rem; display: block; font-weight: 700; text-transform: uppercase;">Cine</span>
                        <strong style="color: var(--admin-text);"><?= esc($funcion->local_nombre) ?></strong>
                    </div>
                    <div>
                        <span style="color: var(--admin-muted); font-size: 0.8rem; display: block; font-weight: 700; text-transform: uppercase;">Sala</span>
                        <strong style="color: var(--admin-text);"><?= esc($funcion->sala_nombre) ?> (<?= esc($funcion->sala_tipo) ?>)</strong>
                    </div>
                    <div>
                        <span style="color: var(--admin-muted); font-size: 0.8rem; display: block; font-weight: 700; text-transform: uppercase;">Fecha</span>
                        <strong style="color: var(--admin-text);"><?= date('d/m/Y', strtotime($funcion->fecha)) ?></strong>
                    </div>
                    <div>
                        <span style="color: var(--admin-muted); font-size: 0.8rem; display: block; font-weight: 700; text-transform: uppercase;">Horario</span>
                        <strong style="color: var(--admin-text);"><?= esc($funcion->getHoraInicio12h()) ?> - <?= esc($funcion->getHoraFin12h()) ?></strong>
                    </div>
                </div>
            </div>

            <!-- Panel de Estadísticas en Vivo -->
            <div style="background: var(--admin-surface); border: 1px solid var(--admin-border); border-radius: 24px; padding: 24px; box-shadow: 0 8px 30px rgba(15,23,42,0.04);">
                <h3 style="margin-top: 0; margin-bottom: 16px; font-size: 1.2rem; color: var(--admin-text); border-bottom: 1px solid var(--admin-border); padding-bottom: 12px;">Resumen de Ocupación</h3>
                
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; margin-bottom: 16px;">
                    <div style="background: var(--admin-surface-alt); padding: 14px; border-radius: 16px; text-align: center;">
                        <span style="font-size: 0.8rem; color: var(--admin-muted); font-weight: 600; display: block;">Vendido / Ocupado</span>
                        <span id="statOccupied" style="font-size: 1.8rem; font-weight: 800; color: #dc3545; display: block; margin-top: 4px;">0</span>
                    </div>
                    <div style="background: var(--admin-surface-alt); padding: 14px; border-radius: 16px; text-align: center;">
                        <span style="font-size: 0.8rem; color: var(--admin-muted); font-weight: 600; display: block;">Disponibles</span>
                        <span id="statAvailable" style="font-size: 1.8rem; font-weight: 800; color: #28a745; display: block; margin-top: 4px;">0</span>
                    </div>
                </div>

                <div style="display: flex; flex-direction: column; gap: 10px; font-size: 0.9rem;">
                    <div style="display: flex; justify-content: space-between;">
                        <span style="color: var(--admin-muted);">Porcentaje Ocupación:</span>
                        <strong id="statPercent" style="color: var(--admin-text);">0%</strong>
                    </div>
                    <div style="height: 8px; width: 100%; background: var(--admin-border); border-radius: 99px; overflow: hidden;">
                        <div id="statProgressBar" style="height: 100%; width: 0%; background: linear-gradient(90deg, #28a745, #dc3545); transition: width 0.4s ease;"></div>
                    </div>
                    <div style="display: flex; justify-content: space-between; border-top: 1px solid var(--admin-border); padding-top: 10px; margin-top: 6px;">
                        <span style="color: var(--admin-muted);">Recaudación Estimada:</span>
                        <strong id="statRevenue" style="color: var(--admin-text); font-size: 1.05rem;">S/. 0.00</strong>
                    </div>
                </div>
            </div>

            <!-- Ficha Detallada de Asiento Seleccionado -->
            <div id="seatDetailsCard" style="background: var(--admin-surface); border: 1px solid var(--admin-border); border-radius: 24px; padding: 24px; box-shadow: 0 8px 30px rgba(15,23,42,0.04); display: none;">
                <h3 style="margin-top: 0; margin-bottom: 12px; font-size: 1.2rem; color: var(--admin-text);">Información de la Butaca</h3>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; font-size: 0.9rem;">
                    <div>
                        <span style="color: var(--admin-muted); display: block;">Asiento:</span>
                        <strong id="detailSeatCode" style="font-size: 1.1rem; color: var(--admin-text);">-</strong>
                    </div>
                    <div>
                        <span style="color: var(--admin-muted); display: block;">Estado:</span>
                        <span id="detailSeatStatus" class="status-pill" style="display: inline-block; margin-top: 2px;">-</span>
                    </div>
                    <div>
                        <span style="color: var(--admin-muted); display: block;">Categoría:</span>
                        <strong id="detailSeatType" style="color: var(--admin-text);">-</strong>
                    </div>
                    <div>
                        <span style="color: var(--admin-muted); display: block;">Precio unitario:</span>
                        <strong id="detailSeatPrice" style="color: var(--admin-text);">-</strong>
                    </div>
                </div>
            </div>

        </div>

        <!-- Renderizador del Mapa de Asientos -->
        <div style="flex: 1.6; min-width: 320px; background: var(--admin-surface); border: 1px solid var(--admin-border); border-radius: 24px; padding: 28px; box-shadow: 0 8px 30px rgba(15,23,42,0.04); display: flex; flex-direction: column;">
            
            <!-- Alertas e Instructivo -->
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px;">
                <h3 style="margin: 0; color: var(--admin-text); font-size: 1.2rem;">Distribución Física</h3>
                <span id="liveBadge" style="background: rgba(220,53,69,0.1); color: #dc3545; border: 1px solid rgba(220,53,69,0.3); padding: 4px 10px; border-radius: 20px; font-size: 0.75rem; font-weight: 700; display: inline-flex; align-items: center; gap: 6px;">
                    <span style="width: 6px; height: 6px; background: #dc3545; border-radius: 50%; display: inline-block; animation: blink 1.5s infinite;"></span> EN VIVO
                </span>
            </div>

            <!-- Mapa Container -->
            <div id="seatMapContainer" style="flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 350px; background: var(--admin-surface-alt); border-radius: 16px; border: 1px solid var(--admin-border); padding: 24px; position: relative;">
                
                <div id="mapLoader" style="display: none; text-align: center; color: var(--admin-muted);">
                    <div class="loader" style="width: 40px; height: 40px; border: 4px solid var(--admin-border); border-top-color: var(--primary); border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto 16px;"></div>
                    <p>Obteniendo ocupación en tiempo real...</p>
                </div>

                <?php if (!$tieneAsientos): ?>
                    <!-- Advertencia de falta de asientos -->
                    <div id="noSeatsWarning" style="text-align: center; max-width: 340px; padding: 20px;">
                        <span style="font-size: 3rem; display: block; margin-bottom: 12px;">⚠️</span>
                        <h4 style="margin: 0 0 8px; color: var(--admin-text);">Sala sin Asientos</h4>
                        <p style="font-size: 0.85rem; color: var(--admin-muted); margin-bottom: 16px;">Esta sala no tiene asientos configurados en la base de datos. Se requiere inicializarlos antes de poder monitorear la ocupación.</p>
                        <button type="button" id="btnGenerarAsientos" class="btn btn-secondary" style="width: 100%;">Autogenerar Asientos Ahora</button>
                    </div>
                <?php endif; ?>

                <!-- Mapa SVG de Asientos -->
                <svg id="svgSeatMap" style="width: 100%; height: 100%; display: none; min-height: 320px;" viewBox="0 0 500 350"></svg>
            </div>

            <!-- Leyenda -->
            <div id="mapLegend" style="display: none; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 12px; margin-top: 20px; font-size: 0.8rem; border-top: 1px solid var(--admin-border); padding-top: 16px;">
                <div style="display: flex; align-items: center; gap: 8px;">
                    <span style="width: 16px; height: 16px; background: #334155; border: 1px solid #475569; border-radius: 4px; display: inline-block;"></span>
                    <span style="color: var(--admin-text); font-weight: 500;">Ocupado (Vendido)</span>
                </div>
                <div style="display: flex; align-items: center; gap: 8px;">
                    <span style="width: 16px; height: 16px; background: #1a73e8; border-radius: 4px; display: inline-block;"></span>
                    <span style="color: var(--admin-text); font-weight: 500;">Disponible Estándar</span>
                </div>
                <div style="display: flex; align-items: center; gap: 8px;">
                    <span style="width: 16px; height: 16px; background: #f4b400; border-radius: 4px; display: inline-block;"></span>
                    <span style="color: var(--admin-text); font-weight: 500;">Disponible Preferencial</span>
                </div>
                <div style="display: flex; align-items: center; gap: 8px;">
                    <span style="width: 16px; height: 16px; background: #9c27b0; border-radius: 4px; display: inline-block;"></span>
                    <span style="color: var(--admin-text); font-weight: 500;">Disponible Accesible</span>
                </div>
            </div>

        </div>

    </div>
</div>

<style>
    @keyframes spin {
        to { transform: rotate(360deg); }
    }
    @keyframes blink {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.4; }
    }
    .asiento-svg {
        transition: transform 0.15s ease, filter 0.15s ease;
    }
    .asiento-svg:hover {
        transform: scale(1.1);
        transform-origin: center;
        filter: brightness(1.15) drop-shadow(0 2px 5px rgba(0,0,0,0.2));
    }
</style>

<!-- Importar Axios -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const id_funcion = <?= esc($funcion->id_funcion) ?>;
    const precioBase = <?= esc($funcion->precio_base) ?>;
    const tieneAsientos = <?= $tieneAsientos ? 'true' : 'false' ?>;

    const statOccupied = document.getElementById('statOccupied');
    const statAvailable = document.getElementById('statAvailable');
    const statPercent = document.getElementById('statPercent');
    const statProgressBar = document.getElementById('statProgressBar');
    const statRevenue = document.getElementById('statRevenue');

    const seatDetailsCard = document.getElementById('seatDetailsCard');
    const detailSeatCode = document.getElementById('detailSeatCode');
    const detailSeatStatus = document.getElementById('detailSeatStatus');
    const detailSeatType = document.getElementById('detailSeatType');
    const detailSeatPrice = document.getElementById('detailSeatPrice');

    const mapLoader = document.getElementById('mapLoader');
    const svgSeatMap = document.getElementById('svgSeatMap');
    const mapLegend = document.getElementById('mapLegend');
    const btnRefrescar = document.getElementById('btnRefrescar');
    
    // Asignación de autogeneración si no tiene asientos
    const btnGenerarAsientos = document.getElementById('btnGenerarAsientos');
    if (btnGenerarAsientos) {
        btnGenerarAsientos.addEventListener('click', async function() {
            btnGenerarAsientos.disabled = true;
            btnGenerarAsientos.textContent = 'Generando asientos...';

            try {
                const response = await axios.post(`<?= base_url('admin/funciones/generar-asientos') ?>/<?= $funcion->id_sala ?>`);
                alert(response.data.message);
                window.location.reload();
            } catch (error) {
                console.error('Error al generar asientos:', error);
                alert(error.response?.data?.message || 'Error al generar asientos.');
                btnGenerarAsientos.disabled = false;
                btnGenerarAsientos.textContent = 'Autogenerar Asientos Ahora';
            }
        });
    }

    btnRefrescar.addEventListener('click', function() {
        cargarOcupacion();
    });

    // Carga inicial
    if (tieneAsientos) {
        cargarOcupacion();
    }

    async function cargarOcupacion() {
        svgSeatMap.style.display = 'none';
        mapLegend.style.display = 'none';
        mapLoader.style.display = 'block';

        try {
            const response = await axios.get(`<?= base_url('admin/funciones/ocupacion') ?>/${id_funcion}`);
            const data = response.data;
            
            mapLoader.style.display = 'none';

            if (data.status === 'success') {
                renderSVGMap(data.asientos);
                actualizarMetricas(data.asientos);
            }
        } catch (error) {
            console.error('Error al cargar la ocupación:', error);
            mapLoader.style.display = 'none';
            alert('No se pudo cargar la ocupación en vivo de la función.');
        }
    }

    function actualizarMetricas(asientos) {
        const total = asientos.length;
        const ocupados = asientos.filter(a => a.estado_ocupacion === 'ocupado').length;
        const disponibles = total - ocupados;
        
        const porcentaje = total > 0 ? Math.round((ocupados / total) * 100) : 0;
        
        // Calcular recaudación: cada asiento ocupado suma su precio unitario
        let totalRecaudado = 0;
        asientos.forEach(a => {
            if (a.estado_ocupacion === 'ocupado') {
                let precio = precioBase;
                if (a.tipo === 'preferencial' || a.tipo === 'discapacitado') {
                    precio = precioBase * 0.75; // 25% de descuento
                }
                totalRecaudado += precio;
            }
        });

        statOccupied.textContent = ocupados;
        statAvailable.textContent = disponibles;
        statPercent.textContent = `${porcentaje}%`;
        statProgressBar.style.width = `${porcentaje}%`;
        statRevenue.textContent = `S/. ${totalRecaudado.toFixed(2)}`;
    }

    function renderSVGMap(asientos) {
        svgSeatMap.innerHTML = '';
        
        const rows = [...new Set(asientos.map(a => a.fila))].sort();
        const cols = [...new Set(asientos.map(a => parseInt(a.numero)))].sort((a, b) => a - b);

        const numRows = rows.length;
        const numCols = cols.length;

        const seatWidth = 24;
        const seatHeight = 24;
        const spacingX = 8;
        const spacingY = 10;
        
        const rowLabelWidth = 20;
        const screenMarginTop = 50;

        const totalWidth = rowLabelWidth + numCols * (seatWidth + spacingX) + 10;
        const totalHeight = screenMarginTop + numRows * (seatHeight + spacingY) + 20;

        svgSeatMap.setAttribute('viewBox', `0 0 ${totalWidth} ${totalHeight}`);
        svgSeatMap.style.display = 'block';
        mapLegend.style.display = 'grid';

        // 1. Dibujar Pantalla
        const screenWidth = totalWidth - 80;
        const screenX = 40;
        const screenY = 20;
        const screenCurve = 10;

        const pathScreen = document.createElementNS("http://www.w3.org/2000/svg", "path");
        pathScreen.setAttribute('d', `M ${screenX} ${screenY + screenCurve} Q ${screenX + screenWidth/2} ${screenY} ${screenX + screenWidth} ${screenY + screenCurve}`);
        pathScreen.setAttribute('stroke', 'var(--admin-accent)');
        pathScreen.setAttribute('stroke-width', '5');
        pathScreen.setAttribute('fill', 'none');
        pathScreen.setAttribute('style', 'filter: drop-shadow(0px 2px 10px rgba(244,180,0,0.5));');
        svgSeatMap.appendChild(pathScreen);

        const textScreen = document.createElementNS("http://www.w3.org/2000/svg", "text");
        textScreen.setAttribute('x', (totalWidth / 2).toString());
        textScreen.setAttribute('y', (screenY + 28).toString());
        textScreen.setAttribute('text-anchor', 'middle');
        textScreen.setAttribute('fill', 'var(--admin-muted)');
        textScreen.setAttribute('font-size', '9');
        textScreen.setAttribute('font-weight', 'bold');
        textScreen.textContent = "PANTALLA";
        svgSeatMap.appendChild(textScreen);

        // 2. Renderizar Filas y Asientos
        rows.forEach((row, rIdx) => {
            const y = screenMarginTop + rIdx * (seatHeight + spacingY);

            const labelLeft = document.createElementNS("http://www.w3.org/2000/svg", "text");
            labelLeft.setAttribute('x', '5');
            labelLeft.setAttribute('y', (y + seatHeight/2 + 4).toString());
            labelLeft.setAttribute('fill', 'var(--admin-muted)');
            labelLeft.setAttribute('font-size', '11');
            labelLeft.setAttribute('font-weight', 'bold');
            labelLeft.textContent = row;
            svgSeatMap.appendChild(labelLeft);

            cols.forEach((col, cIdx) => {
                const asiento = asientos.find(a => a.fila === row && parseInt(a.numero) === col);
                if (!asiento) return;

                const x = rowLabelWidth + cIdx * (seatWidth + spacingX);

                const group = document.createElementNS("http://www.w3.org/2000/svg", "g");
                group.setAttribute('class', 'asiento-svg');
                group.style.cursor = 'pointer';

                // Transform-origin al centro para la escala al hacer hover
                const centerX = x + seatWidth / 2;
                const centerY = y + seatHeight / 2;
                group.setAttribute('style', `transform-origin: ${centerX}px ${centerY}px;`);

                const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
                rect.setAttribute('x', x.toString());
                rect.setAttribute('y', y.toString());
                rect.setAttribute('width', seatWidth.toString());
                rect.setAttribute('height', seatHeight.toString());
                rect.setAttribute('rx', '6');

                // Color según ocupación y tipo
                let fill = '#1a73e8'; // estándar
                let stroke = '#155cb4';
                
                if (asiento.estado_ocupacion === 'ocupado') {
                    fill = '#334155'; // gris/pizarra oscuro
                    stroke = '#1e293b';
                } else {
                    if (asiento.tipo === 'preferencial') {
                        fill = '#f4b400';
                        stroke = '#c69200';
                    } else if (asiento.tipo === 'discapacitado') {
                        fill = '#9c27b0';
                        stroke = '#7b1fa2';
                    }
                }

                rect.setAttribute('fill', fill);
                rect.setAttribute('stroke', stroke);
                rect.setAttribute('stroke-width', '1.5');
                group.appendChild(rect);

                const numText = document.createElementNS("http://www.w3.org/2000/svg", "text");
                numText.setAttribute('x', (x + seatWidth/2).toString());
                numText.setAttribute('y', (y + seatHeight/2 + 4).toString());
                numText.setAttribute('text-anchor', 'middle');
                numText.setAttribute('fill', '#ffffff');
                numText.setAttribute('font-size', '8');
                numText.setAttribute('font-weight', 'bold');
                numText.textContent = col.toString();
                group.appendChild(numText);

                // Eventos de Clic y Hover
                group.addEventListener('click', () => {
                    mostrarDetallesAsiento(asiento);
                });

                svgSeatMap.appendChild(group);
            });
        });
    }

    function mostrarDetallesAsiento(asiento) {
        detailSeatCode.textContent = `${asiento.fila}-${asiento.numero}`;
        
        // Estado Badge
        detailSeatStatus.textContent = asiento.estado_ocupacion.toUpperCase();
        detailSeatStatus.className = 'status-pill ' + (asiento.estado_ocupacion === 'ocupado' ? 'inactive' : 'active');
        
        detailSeatType.textContent = asiento.tipo.toUpperCase();
        
        let precio = precioBase;
        if (asiento.tipo === 'preferencial' || asiento.tipo === 'discapacitado') {
            precio = precioBase * 0.75; // 25% de descuento
        }
        detailSeatPrice.textContent = `S/. ${precio.toFixed(2)}`;

        seatDetailsCard.style.display = 'block';
        
        // Animación suave de aparición del panel de detalle
        seatDetailsCard.style.animation = 'none';
        setTimeout(() => {
            seatDetailsCard.style.animation = 'blink 0.3s ease-out 1';
        }, 10);
    }
});
</script>
<?= $this->endSection() ?>
