<?php
$authUser = session('auth_user');
$company = company_profile();
$brandLogoUrl = company_brand_asset_url('logo');
$brandingUnlocked = session('branding_settings_unlocked') === true;
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= esc($title ?? $company['name']) ?></title>
    <meta name="csrf-token-name" content="<?= esc(csrf_token()) ?>">
    <meta name="csrf-token" content="<?= esc(csrf_hash()) ?>">
    <link rel="stylesheet" href="<?= base_url('assets/app.css') ?>">
</head>
<body>
    <!-- Barra superior móvil (oculta en escritorio) -->
    <nav class="mobile-topbar">
        <div class="mobile-topbar-brand">
            <?php if ($brandLogoUrl): ?>
                <img src="<?= esc($brandLogoUrl) ?>" alt="<?= esc($company['name']) ?>" class="mobile-brand-logo">
            <?php endif; ?>
            <span class="mobile-topbar-name"><?= esc($company['name']) ?></span>
        </div>
        <button class="hamburger" id="nav-toggle" aria-label="Abrir menú" aria-expanded="false">
            <span></span><span></span><span></span>
        </button>
    </nav>
    <div class="nav-overlay" id="nav-overlay"></div>

    <div class="app-shell">
        <aside class="sidebar">
            <div class="nav-close-btn">
                <button type="button" id="nav-close" aria-label="Cerrar menú">&times;</button>
            </div>
            <div>
                <?php if ($brandLogoUrl): ?>
                    <img src="<?= esc($brandLogoUrl) ?>" alt="<?= esc($company['name']) ?>" class="brand-logo">
                <?php endif; ?>
                <h1><?= esc($company['name']) ?></h1>
                <p><?= esc($company['tagline']) ?></p>
            </div>

            <nav class="sidebar-nav">
                <div class="nav-group">
                    <span class="nav-group-title">General</span>
                    <a class="<?= url_is('dashboard') ? 'is-active' : '' ?>" href="<?= site_url('dashboard') ?>">Panel</a>
                    <a class="<?= url_is('clients*') ? 'is-active' : '' ?>" href="<?= site_url('clients') ?>">Clientes</a>
                    <a class="<?= url_is('inspections*') ? 'is-active' : '' ?>" href="<?= site_url('inspections') ?>">Inspecciones</a>
                    <a class="<?= url_is('delivery-notes*') ? 'is-active' : '' ?>" href="<?= site_url('delivery-notes') ?>">Actas</a>
                </div>
                <div class="nav-group">
                    <span class="nav-group-title">Personalización</span>
                    <a class="<?= url_is('inspection-templates*') ? 'is-active' : '' ?>" href="<?= site_url('inspection-templates') ?>">Plantillas de inspección</a>
                    <a class="<?= url_is('delivery-note-templates*') ? 'is-active' : '' ?>" href="<?= site_url('delivery-note-templates') ?>">Plantillas de acta</a>
                </div>
                <div class="nav-group">
                    <span class="nav-group-title">Configuración</span>
                    <?php if ($brandingUnlocked): ?>
                        <a class="<?= url_is('settings/branding*') ? 'is-active' : '' ?>" href="<?= site_url('settings/branding') ?>">Marca</a>
                    <?php else: ?>
                        <button type="button" class="sidebar-nav-button" id="branding-trigger-nav">Marca</button>
                    <?php endif; ?>
                </div>
            </nav>

            <div class="sidebar-user">
                <strong><?= esc(is_array($authUser) ? ($authUser['name'] ?? 'Administrador') : 'Administrador') ?></strong>
                <span><?= esc(is_array($authUser) ? ($authUser['email'] ?? '') : '') ?></span>
                <a href="<?= site_url('logout') ?>">Cerrar sesión</a>
            </div>

            <div class="sidebar-footer-note">
                <button type="button" class="developer-trigger" id="branding-trigger"><?= esc($company['developer_footer']) ?></button>

                <?php if ($brandingUnlocked): ?>
                    <div class="sidebar-footer-actions">
                        <a href="<?= site_url('settings/branding') ?>">Panel desbloqueado</a>
                        <form method="post" action="<?= site_url('settings/branding/lock') ?>">
                            <?= csrf_field() ?>
                            <button type="submit" class="link-button">Bloquear</button>
                        </form>
                    </div>
                <?php endif; ?>
            </div>
        </aside>

        <main class="content-area">
            <header class="page-header">
                <div>
                    <h2><?= esc($title ?? 'Panel') ?></h2>
                    <p>Captura inspecciones en campo, compón reportes y entrega documentos firmados.</p>
                </div>
            </header>

            <?= $this->include('partials/flash') ?>

            <?= $this->renderSection('content') ?>
        </main>
    </div>

    <div class="pin-modal" id="branding-pin-modal" hidden>
        <div class="pin-modal-backdrop" data-close-pin-modal></div>
        <div class="pin-modal-card">
            <div class="section-head">
                <div>
                    <h3>Panel oculto</h3>
                    <p>Ingresa el PIN para editar el branding del sistema.</p>
                </div>
                <button type="button" class="link-button" data-close-pin-modal>Cerrar</button>
            </div>

            <form id="branding-pin-form" class="stack-md">
                <input type="hidden" name="<?= esc(csrf_token()) ?>" value="<?= esc(csrf_hash()) ?>">
                <div>
                    <label for="branding-pin-input">PIN</label>
                    <input id="branding-pin-input" name="pin" type="password" inputmode="numeric" autocomplete="one-time-code" required>
                </div>
                <p class="muted" id="branding-pin-status"></p>
                <button type="submit" class="btn btn-primary">Abrir panel</button>
            </form>
        </div>
    </div>

    <script>
    (() => {
        document.addEventListener('submit', (event) => {
            const form = event.target;
            if (!(form instanceof HTMLFormElement) || (form.method || '').toLowerCase() !== 'post') {
                return;
            }

            const csrfName = document.querySelector('meta[name="csrf-token-name"]')?.content;
            const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
            if (!csrfName || !csrfToken) {
                return;
            }

            let input = form.querySelector('input[name="' + CSS.escape(csrfName) + '"]');
            if (!input) {
                input = document.createElement('input');
                input.type = 'hidden';
                input.name = csrfName;
                form.appendChild(input);
            }
            input.value = csrfToken;
        }, true);
    })();

    // Menú móvil
    (() => {
        const toggle  = document.getElementById('nav-toggle');
        const close   = document.getElementById('nav-close');
        const overlay = document.getElementById('nav-overlay');
        const openNav  = () => { document.body.classList.add('nav-open');    toggle?.setAttribute('aria-expanded', 'true'); };
        const closeNav = () => { document.body.classList.remove('nav-open'); toggle?.setAttribute('aria-expanded', 'false'); };
        toggle?.addEventListener('click', openNav);
        close?.addEventListener('click', closeNav);
        overlay?.addEventListener('click', closeNav);
        document.querySelectorAll('.sidebar-nav a').forEach((a) => a.addEventListener('click', closeNav));
        document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeNav(); });
    })();

    (() => {
        const trigger = document.getElementById('branding-trigger');
        const modal = document.getElementById('branding-pin-modal');
        const form = document.getElementById('branding-pin-form');
        const input = document.getElementById('branding-pin-input');
        const status = document.getElementById('branding-pin-status');

        if (!trigger || !modal || !form || !input || !status) {
            return;
        }

        const csrfName = <?= json_encode(csrf_token()) ?>;
        let csrfToken = <?= json_encode(csrf_hash()) ?>;

        const openModal = () => {
            modal.hidden = false;
            status.textContent = '';
            input.value = '';
            window.setTimeout(() => input.focus(), 40);
        };

        const closeModal = () => {
            modal.hidden = true;
        };

        trigger.addEventListener('click', openModal);
        document.getElementById('branding-trigger-nav')?.addEventListener('click', openModal);
        modal.querySelectorAll('[data-close-pin-modal]').forEach((node) => {
            node.addEventListener('click', closeModal);
        });

        form.addEventListener('submit', async (event) => {
            event.preventDefault();
            status.textContent = 'Validando PIN...';

            const body = new URLSearchParams();
            body.set(csrfName, csrfToken);
            body.set('pin', input.value.trim());

            try {
                const response = await fetch(<?= json_encode(site_url('settings/access')) ?>, {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                    },
                    body: body.toString()
                });

                const payload = await response.json();
                csrfToken = payload.csrf_token || csrfToken;

                if (!response.ok || !payload.ok) {
                    status.textContent = payload.message || 'No fue posible validar el PIN.';
                    return;
                }

                window.location.href = payload.redirect;
            } catch (error) {
                status.textContent = 'No fue posible validar el PIN.';
            }
        });

        document.addEventListener('keydown', (event) => {
            if (event.key === 'Escape' && !modal.hidden) {
                closeModal();
            }
        });
    })();
    </script>
</body>
</html>
