<?php
/**
 * ================================================================================
 * Depto de Engenharia e Automação - Master Automação - Autor: Derlivon Silva
 * ================================================================================
 * Mesas / Exceções no Caixa — anti-fraude bar (Tumbleweed pattern).
 *
 * Detecta padrões clássicos via SOMENTE LEITURA do banco do ERP:
 *  - mesa cancelada (STATUS='C') por garçom
 *  - desconto manual alto (% sobre o total)
 *  - comanda longa (> 4h sem fechar)
 *  - score ponderado + semáforo + alertas dos vermelhos
 *  - drill-down: clica garçom → lista mesas suspeitas com flag
 * ================================================================================
 */
?>
<div class="pbi-page-header">
    <h1 class="pbi-page-title"><i class="bi bi-shield-exclamation me-2" style="color:#dc2626"></i>Exceções no Caixa</h1>
</div>
<?php include __DIR__ . '/_submenu.php' ?>

<form method="get" action="/mesas/excecoes-caixa" class="pbi-filtro-barra mb-3" id="ecFiltro">
    <div class="pbi-filtro-row">
        <div class="pbi-filtro-field"><label class="pbi-filtro-label">De</label>
            <input type="date" name="data_ini" value="<?= \App\Core\View::e($filtros['dataIni'] ?? '') ?>" class="pbi-filtro-input form-control"></div>
        <div class="pbi-filtro-field"><label class="pbi-filtro-label">Até</label>
            <input type="date" name="data_fim" value="<?= \App\Core\View::e($filtros['dataFim'] ?? '') ?>" class="pbi-filtro-input form-control"></div>
        <div class="pbi-filtro-field" style="max-width:120px"><label class="pbi-filtro-label">% Canc</label>
            <input type="number" step="0.5" name="t_canc" value="5.0" class="pbi-filtro-input form-control" title="Acima desse % de mesas canceladas vira alerta"></div>
        <div class="pbi-filtro-field" style="max-width:120px"><label class="pbi-filtro-label">% Desc</label>
            <input type="number" step="0.5" name="t_desc" value="10.0" class="pbi-filtro-input form-control" title="Acima desse % de desconto sobre faturamento vira alerta"></div>
        <div class="pbi-filtro-field" style="max-width:100px"><label class="pbi-filtro-label">Horas Longa</label>
            <input type="number" step="1" name="h_longa" value="4" class="pbi-filtro-input form-control" title="Comanda aberta mais que isso vira alerta"></div>
        <button type="submit" class="pbi-btn-filtrar btn"><i class="bi bi-funnel me-1"></i>Analisar</button>
    </div>
</form>

<!-- ── Box explicativo pro gestor ────────────────────────────────────────── -->
<div class="pbi-card mb-3" style="border-left:4px solid #6366f1;background:#f5f3ff">
    <div class="pbi-card-header" style="background:transparent;border:none;cursor:pointer" onclick="document.getElementById('ecExplica').classList.toggle('d-none')">
        <i class="bi bi-info-circle-fill me-2" style="color:#6366f1"></i>
        <strong>Como interpretar essa tela</strong>
        <span class="text-muted small ms-2">(clique pra abrir/fechar)</span>
    </div>
    <div id="ecExplica" style="padding:0 1.25rem 1.25rem">
        <p class="mb-2"><strong>O que essa tela detecta HOJE:</strong></p>
        <ul class="mb-3">
            <li><strong>Mesa cancelada inteira</strong> — quando a mesa foi aberta e fechada sem efetivar a venda (cliente desistiu, erro de abertura, etc.).</li>
            <li><strong>Desconto manual no total da comanda</strong> — quanto o garçom concedeu de desconto sobre o valor cheio.</li>
            <li><strong>Comanda longa</strong> — mesa que ficou aberta mais de 4h (configurável). Possível sinal de "comanda fantasma" ou esquecimento.</li>
        </ul>

        <p class="mb-2"><strong>O que essa tela NÃO detecta (ainda):</strong></p>
        <ul class="mb-3">
            <li>🚨 <strong>Item cancelado dentro de comanda fechada</strong> — fraude mais comum em bar: garçom lança item, recebe do cliente, e cancela só o item antes de fechar.</li>
            <li>🚨 <strong>Preço unitário alterado pra menor</strong> — garçom muda o preço do item na hora de lançar, recebe o cheio e fica com a diferença.</li>
            <li>🚨 <strong>Lançamento tardio</strong> — item lançado horas depois do fechamento (típico de furto depois do expediente).</li>
        </ul>

        <p class="mb-2"><strong>Como ler o ranking:</strong></p>
        <ul class="mb-3">
            <li><span class="badge" style="background:#16a34a;color:#fff">Verde &lt;30</span> = comportamento normal pro bar.</li>
            <li><span class="badge" style="background:#f59e0b;color:#fff">Amarelo 30-59</span> = atenção, vale conversar com o garçom.</li>
            <li><span class="badge" style="background:#dc2626;color:#fff">Vermelho ≥60</span> = investigar urgente.</li>
        </ul>

        <p class="mb-2"><strong>Regra de ouro:</strong> o que importa é a <strong>diferença entre garçons</strong>. Se a média do bar é 5% de cancelamento e um garçom tá em 15%, ele é o suspeito — não o número absoluto.</p>

        <p class="mb-0 text-muted small"><i class="bi bi-shield-check me-1"></i> Padrão Tumbleweed Tex-Mex — recuperou ~US$ 100 mil/ano só com este tipo de relatório.</p>
    </div>
</div>

<div class="pbi-hint mb-3" style="margin-top:0">
    Ranking de garçons com indicadores de exceção. <strong>Clique numa linha</strong> e abre as mesas problemáticas dele.
</div>

<!-- ── KPIs agregados ──────────────────────────────────────────────────── -->
<div class="pbi-kpi-grid mb-4" id="ecKpis">
    <div class="pbi-kpi-card"><div class="pbi-kpi-label">Mesas no período</div><div class="pbi-kpi-value" id="ecK_mesas">—</div></div>
    <div class="pbi-kpi-card" style="border-left:4px solid #dc2626"><div class="pbi-kpi-label">Canceladas</div><div class="pbi-kpi-value" id="ecK_canc" style="color:#dc2626">—</div></div>
    <div class="pbi-kpi-card" style="border-left:4px solid #dc2626"><div class="pbi-kpi-label">Valor cancelado</div><div class="pbi-kpi-value" id="ecK_valc" style="color:#dc2626">—</div></div>
    <div class="pbi-kpi-card" style="border-left:4px solid #f59e0b"><div class="pbi-kpi-label">Desconto total</div><div class="pbi-kpi-value" id="ecK_desc" style="color:#f59e0b">—</div></div>
    <div class="pbi-kpi-card" style="border-left:4px solid #6366f1"><div class="pbi-kpi-label">Comandas longas (&gt;4h)</div><div class="pbi-kpi-value" id="ecK_long" style="color:#6366f1">—</div></div>
</div>

<!-- ── Alertas (vermelhos) ──────────────────────────────────────────────── -->
<div class="alert alert-danger mb-3" id="ecAlertas" style="display:none">
    <h6 class="mb-2"><i class="bi bi-exclamation-octagon-fill me-2"></i>Alertas — garçons com score crítico</h6>
    <ul class="mb-0" id="ecAlertasList"></ul>
</div>

<!-- ── Tabela principal ─────────────────────────────────────────────────── -->
<div class="pbi-card">
    <div class="pbi-card-header">
        <i class="bi bi-table me-2"></i> Ranking de exceções por garçom
        <span class="text-muted small ms-2" id="ecPeriodo"></span>
    </div>
    <div class="table-responsive">
        <table class="table pbi-table mb-0">
            <thead>
                <tr>
                    <th style="width:32px"></th>
                    <th>Garçom</th>
                    <th class="text-end">Mesas</th>
                    <th class="text-end">Faturamento</th>
                    <th class="text-end" style="color:#dc2626">Canc</th>
                    <th class="text-end" style="color:#dc2626">% Canc</th>
                    <th class="text-end" style="color:#f59e0b">Desconto</th>
                    <th class="text-end" style="color:#f59e0b">% Desc</th>
                    <th class="text-end" style="color:#6366f1">Longas</th>
                    <th class="text-end">Score</th>
                </tr>
            </thead>
            <tbody id="ecTbody">
                <tr><td colspan="10" class="text-center py-4 text-muted"><i class="bi bi-hourglass-split"></i> Carregando…</td></tr>
            </tbody>
        </table>
    </div>
</div>

<div id="ecErro" class="alert alert-danger mt-3" style="display:none"></div>

<script>
(function () {
    const fmtBR  = (n) => 'R$ ' + Number(n || 0).toLocaleString('pt-BR', {minimumFractionDigits: 2, maximumFractionDigits: 2});
    const fmtInt = (n) => Number(n || 0).toLocaleString('pt-BR');
    const fmtPct = (n) => Number(n || 0).toFixed(1) + '%';
    const fmtData = (d) => {
        if (!d) return '—';
        const s = String(d).substring(0, 10).split('-');
        return s.length === 3 ? `${s[2]}/${s[1]}/${s[0]}` : d;
    };
    const fmtHora = (h) => h ? String(h).substring(0, 5) : '—';
    const $ = (id) => document.getElementById(id);

    function apiFetch(url) {
        return fetch(url, {credentials:'same-origin'})
            .then(r => r.ok ? r.json() : r.json().then(j => Promise.reject(j.erro || r.statusText)));
    }

    function corSemaforo(s) {
        return s === 'vermelho' ? '#dc2626' : (s === 'amarelo' ? '#f59e0b' : '#16a34a');
    }
    function badgeFlag(f) {
        const map = {
            'cancelada':     {cor:'#dc2626', txt:'Cancelada'},
            'desconto-alto': {cor:'#f59e0b', txt:'Desconto alto'},
            'comanda-longa': {cor:'#6366f1', txt:'Comanda longa'},
        };
        const m = map[f] || {cor:'#64748b', txt:f};
        return `<span class="badge me-1" style="background:${m.cor};color:#fff">${m.txt}</span>`;
    }

    // ── 1) Carrega ranking ────────────────────────────────────────────────
    function carregar() {
        const di = document.querySelector('[name=data_ini]').value;
        const df = document.querySelector('[name=data_fim]').value;
        const tc = document.querySelector('[name=t_canc]').value;
        const td = document.querySelector('[name=t_desc]').value;
        const hl = document.querySelector('[name=h_longa]').value;
        const qs = new URLSearchParams({data_ini:di, data_fim:df, t_canc:tc, t_desc:td, h_longa:hl});

        $('ecErro').style.display = 'none';
        $('ecTbody').innerHTML = '<tr><td colspan="10" class="text-center py-4 text-muted"><i class="bi bi-hourglass-split"></i> Analisando…</td></tr>';

        apiFetch('/api/mesas/excecoes-caixa?' + qs.toString()).then(data => {
            const k = data.kpis || {};
            $('ecK_mesas').textContent = fmtInt(k.mesas_total);
            $('ecK_canc').textContent  = fmtInt(k.canceladas);
            $('ecK_valc').textContent  = fmtBR(k.valor_cancelado);
            $('ecK_desc').textContent  = fmtBR(k.desconto_total);
            $('ecK_long').textContent  = fmtInt(k.comandas_longas);
            $('ecPeriodo').textContent = `${fmtData(data.dataIni)} a ${fmtData(data.dataFim)}`;

            // Alertas
            if ((data.alertas || []).length) {
                $('ecAlertas').style.display = '';
                $('ecAlertasList').innerHTML = data.alertas.map(a =>
                    `<li><strong>${a.garcom}</strong> — score ${a.score} (${a.motivo})</li>`
                ).join('');
            } else {
                $('ecAlertas').style.display = 'none';
            }

            const linhas = data.linhas || [];
            if (!linhas.length) {
                $('ecTbody').innerHTML = '<tr><td colspan="10" class="text-center py-4 text-muted">Nenhum garçom no período. Ajuste o filtro de datas.</td></tr>';
                return;
            }
            $('ecTbody').innerHTML = linhas.map(r => `
                <tr class="ec-row" data-cod="${r.COD_GARCOM}" style="cursor:pointer">
                    <td class="text-center"><i class="bi bi-chevron-right ec-toggle"></i></td>
                    <td><strong>${r.GARCOM}</strong></td>
                    <td class="text-end">${fmtInt(r.MESAS_TOTAL)}</td>
                    <td class="text-end">${fmtBR(r.FATURAMENTO)}</td>
                    <td class="text-end">${fmtInt(r.MESAS_CANCELADAS)}</td>
                    <td class="text-end" style="color:${r.PCT_CANCELADAS>=5?'#dc2626':''}">${fmtPct(r.PCT_CANCELADAS)}</td>
                    <td class="text-end">${fmtBR(r.DESCONTO_TOTAL)}</td>
                    <td class="text-end" style="color:${r.PCT_DESCONTO>=10?'#f59e0b':''}">${fmtPct(r.PCT_DESCONTO)}</td>
                    <td class="text-end">${fmtInt(r.COMANDAS_LONGAS)}</td>
                    <td class="text-end">
                        <span class="badge" style="background:${corSemaforo(r.SEMAFORO)};color:#fff;font-size:.85rem">${r.SCORE}</span>
                    </td>
                </tr>
                <tr class="ec-det" id="ec-det-${r.COD_GARCOM}" style="display:none">
                    <td colspan="10" style="background:#f8f9fb;padding:0">
                        <div class="ec-det-box" style="padding:1rem">
                            <div class="text-muted small mb-2"><i class="bi bi-hourglass-split"></i> Carregando mesas suspeitas…</div>
                        </div>
                    </td>
                </tr>
            `).join('');

            document.querySelectorAll('.ec-row').forEach(tr =>
                tr.addEventListener('click', () => toggleDetalhe(tr.dataset.cod, tr))
            );
        }).catch(e => {
            $('ecTbody').innerHTML = '';
            $('ecErro').textContent = 'Erro: ' + e;
            $('ecErro').style.display = '';
        });
    }

    // ── 2) Drill-down: mesas suspeitas do garçom ──────────────────────────
    const detCache = {};
    function toggleDetalhe(cod, tr) {
        const box = $('ec-det-' + cod);
        const ico = tr.querySelector('.ec-toggle');
        if (box.style.display !== 'none') {
            box.style.display = 'none';
            ico.classList.remove('bi-chevron-down');
            ico.classList.add('bi-chevron-right');
            return;
        }
        box.style.display = '';
        ico.classList.remove('bi-chevron-right');
        ico.classList.add('bi-chevron-down');

        if (detCache[cod]) { renderDetalhe(box, detCache[cod]); return; }
        const di = document.querySelector('[name=data_ini]').value;
        const df = document.querySelector('[name=data_fim]').value;
        const qs = new URLSearchParams({cod_garcom:cod, data_ini:di, data_fim:df});
        apiFetch('/api/mesas/excecoes-detalhe?' + qs.toString()).then(data => {
            detCache[cod] = data.mesas || [];
            renderDetalhe(box, detCache[cod]);
        }).catch(e => {
            box.querySelector('.ec-det-box').innerHTML = '<div class="text-danger small">Erro: ' + e + '</div>';
        });
    }

    function renderDetalhe(box, mesas) {
        if (!mesas.length) {
            box.querySelector('.ec-det-box').innerHTML = '<div class="text-muted small">Nenhuma mesa com exceção para esse garçom no período. 👍</div>';
            return;
        }
        const rows = mesas.map(m => {
            const flags = (m.FLAGS || []).map(badgeFlag).join('');
            return `<tr>
                <td><strong>#${m.COD_MESA ?? '—'}</strong></td>
                <td>${fmtData(m.DATA_ABERTURA)} ${fmtHora(m.HORA_ABERTURA)} → ${fmtData(m.DATA_FECHAMENTO)} ${fmtHora(m.HORA_FECHAMENTO)}</td>
                <td class="text-end">${fmtInt(m.MINUTOS)} min</td>
                <td class="text-end">${fmtBR(m.TOTAL)}</td>
                <td class="text-end" style="color:#f59e0b">${fmtBR(m.DESCONTO)} (${fmtPct(m.PCT_DESCONTO)})</td>
                <td>${flags}</td>
            </tr>`;
        });
        box.querySelector('.ec-det-box').innerHTML = `
            <table class="table table-sm mb-0">
                <thead style="background:#eef1f6">
                    <tr><th>Mesa</th><th>Período</th><th class="text-end">Tempo</th><th class="text-end">Total</th><th class="text-end">Desconto</th><th>Flags</th></tr>
                </thead>
                <tbody>${rows.join('')}</tbody>
            </table>`;
    }

    // ── 3) Submit do filtro ─────────────────────────────────────────────
    $('ecFiltro').addEventListener('submit', (e) => { e.preventDefault(); carregar(); });

    // Carga inicial
    carregar();
})();
</script>
