<?php
/**
 * Pessoal / Funcionários — shell instantâneo.
 */
// Termo conforme o segmento: "Garçons" (mesas) ou "Vendedores" (varejo/serviços)
$__seg = '';
$__dbp = dirname(__DIR__, 3) . '/config/database.php';
if (is_file($__dbp)) { $__c = require $__dbp; $__seg = $__c['segmento'] ?? ''; }
$ehMesas = in_array($__seg, ['restaurante','bar','lanchonete','sushi','pizzaria','churrascaria'], true);
$TERMO  = $ehMesas ? 'Garçons'  : 'Vendedores';
$TERMOS = $ehMesas ? 'garçom'   : 'vendedor';
?>
<div class="pbi-page-header">
    <h1 class="pbi-page-title"><i class="bi bi-person-badge-fill me-2 text-accent"></i>Pessoal</h1>
</div>
<?php include __DIR__ . '/_submenu.php' ?>

<!-- ── KPIs skeleton ─────────────────────────────────────────────────────── -->
<div class="pbi-kpi-grid mb-4" id="kpi-grid">
    <?php for ($i = 0; $i < 2; $i++): ?>
    <div class="pbi-kpi-card">
        <div class="pbi-kpi-label pbi-skeleton" style="width:60%;height:.8rem;border-radius:4px">&nbsp;</div>
        <div class="pbi-kpi-value pbi-skeleton mt-2" style="width:80%;height:1.6rem;border-radius:4px">&nbsp;</div>
    </div>
    <?php endfor; ?>
</div>

<!-- ── Tabela (async) ────────────────────────────────────────────────────── -->
<div class="pbi-card" id="card-funcionarios">
    <div class="pbi-card-header d-flex justify-content-between">
        <span><i class="bi bi-people me-2"></i>Equipe de <?= $TERMO ?></span>
        <small class="text-muted" id="func-badge">
            <span class="pbi-skeleton d-inline-block" style="width:80px;height:.75rem;border-radius:3px">&nbsp;</span>
        </small>
        <div class="pbi-hint mb-2" style="margin-top:0">% de comissão de cada <?= $TERMOS ?>: <strong>Geral</strong> = padrão; <strong>Vista</strong> = em vendas à vista; <strong>Cartão</strong> = em vendas no cartão.</div>
    </div>
    <div id="func-body">
        <div class="table-responsive">
            <table class="pbi-table">
                <thead><tr>
                    <th>#</th><th>Nome</th><th>CPF</th><th>Telefone</th>
                    <th>Turno</th>
                    <th class="text-end">Com. Geral</th>
                    <th class="text-end">Com. Vista</th>
                    <th class="text-end">Com. Cartão</th>
                    <th>Status</th>
                </tr></thead>
                <tbody>
                <?php for ($i = 0; $i < 6; $i++): ?>
                <tr>
                    <?php foreach ([30,130,90,80,60,60,60,60,50] as $w): ?>
                    <td><span class="pbi-skeleton d-inline-block" style="width:<?= $w ?>px;height:.75rem;border-radius:3px">&nbsp;</span></td>
                    <?php endforeach; ?>
                </tr>
                <?php endfor; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>
@keyframes pbi-pulse{0%,100%{opacity:1}50%{opacity:.4}}
.pbi-skeleton{background:var(--pbi-border,#e2e8f0);animation:pbi-pulse 1.4s ease-in-out infinite;pointer-events:none;color:transparent!important}
</style>

<script>
(function(){
'use strict';

function fmtP(v){return parseFloat(v||0).toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2})+'%';}
function esc(s){var d=document.createElement('div');d.textContent=s||'';return d.innerHTML;}
function apiFetch(url){
    return fetch(url,{credentials:'same-origin'}).then(function(r){
        if(!r.ok)return r.json().then(function(e){throw new Error(e.erro||'HTTP '+r.status);});
        return r.json();
    });
}

window.addEventListener('DOMContentLoaded', function(){
    // KPIs
    apiFetch('/api/pessoal/kpis')
        .then(function(d){
            var kpis = d.kpis||{};
            document.getElementById('kpi-grid').innerHTML =
                '<div class="pbi-kpi-card"><div class="pbi-kpi-label">Total <?= $TERMO ?></div>'
                + '<div class="pbi-kpi-value">'+parseInt(kpis.TOTAL_GARCONS||0)+'</div></div>'
                + '<div class="pbi-kpi-card"><div class="pbi-kpi-label">Ativos</div>'
                + '<div class="pbi-kpi-value text-success">'+parseInt(kpis.ATIVOS||0)+'</div></div>';
        })
        .catch(function(e){
            document.getElementById('kpi-grid').innerHTML=
                '<div class="alert alert-warning small py-2">Erro KPIs: '+esc(e.message)+'</div>';
        });

    // Funcionários
    apiFetch('/api/pessoal/funcionarios')
        .then(function(d){
            var linhas = d.linhas||[];
            document.getElementById('func-badge').textContent = linhas.length+' registros';
            if(!linhas.length){
                document.getElementById('func-body').innerHTML=
                    '<p class="text-center text-muted py-4">Nenhum funcionário encontrado.</p>';
                return;
            }
            var rows = linhas.map(function(r,i){
                var ativo = (r.ATIVO||'').trim()==='S'
                    ? '<span class="pbi-badge pbi-badge-success">Ativo</span>'
                    : '<span class="pbi-badge">Inativo</span>';
                return '<tr>'
                    + '<td class="text-muted">'+(i+1)+'</td>'
                    + '<td>'+esc(r.NOME||'')+'</td>'
                    + '<td class="text-muted small">'+esc((r.CPF||'').trim())+'</td>'
                    + '<td class="text-muted small">'+esc((r.CEL_PRINC||r.FONE_PRINC||'').trim())+'</td>'
                    + '<td>'+esc((r.TURNO||'').trim())+'</td>'
                    + '<td class="text-end">'+fmtP(r.COM_GERAL||0)+'</td>'
                    + '<td class="text-end">'+fmtP(r.COM_VISTA||0)+'</td>'
                    + '<td class="text-end">'+fmtP(r.COM_CARTAO||0)+'</td>'
                    + '<td>'+ativo+'</td>'
                    + '</tr>';
            }).join('');
            document.getElementById('func-body').innerHTML =
                '<div class="table-responsive"><table class="pbi-table">'
                + '<thead><tr><th>#</th><th>Nome</th><th>CPF</th><th>Telefone</th>'
                + '<th>Turno</th><th class="text-end">Com. Geral</th>'
                + '<th class="text-end">Com. Vista</th><th class="text-end">Com. Cartão</th><th>Status</th>'
                + '</tr></thead><tbody>'+rows+'</tbody></table></div>';
        })
        .catch(function(e){
            document.getElementById('func-body').innerHTML=
                '<div class="px-3 py-3 alert alert-warning small">Erro: '+esc(e.message)+'</div>';
        });
});

})();
</script>
