<?php
// supervisores.php — Gerenciamento de Supervisores (Múltiplos)
$pageActive = 'supervisores';
$pageTitle  = 'Supervisores';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/auth.php';
requirePerfil(['ADMIN']);

$msg  = '';
$erro = '';

// Garante tabela
pdo()->exec("CREATE TABLE IF NOT EXISTS `supervisores` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(150) NOT NULL,
  `whatsapp` varchar(20) NOT NULL,
  `email` varchar(150) DEFAULT NULL,
  `cargo` varchar(100) DEFAULT 'Supervisor',
  `ativo` tinyint(1) DEFAULT 1,
  `criado_em` timestamp DEFAULT current_timestamp(),
  `atualizado_em` timestamp DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

// Ações
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCsrf($_POST['csrf_token'] ?? '')) die('CSRF inválido');
    
    $action = $_POST['action'] ?? '';
    
    if ($action === 'adicionar') {
        $nome     = trim($_POST['nome'] ?? '');
        $whatsapp = preg_replace('/\D/', '', $_POST['whatsapp'] ?? '');
        $email    = trim($_POST['email'] ?? '');
        $cargo    = trim($_POST['cargo'] ?? 'Supervisor');
        
        if (empty($nome) || empty($whatsapp)) {
            $erro = 'Nome e WhatsApp são obrigatórios.';
        } else {
            pdo()->prepare("INSERT INTO supervisores (nome, whatsapp, email, cargo) VALUES (?, ?, ?, ?)")
                ->execute([$nome, $whatsapp, $email, $cargo]);
            $msg = '✓ Supervisor adicionado com sucesso!';
        }
    }
    
    if ($action === 'editar') {
        $id       = (int)($_POST['id'] ?? 0);
        $nome     = trim($_POST['nome'] ?? '');
        $whatsapp = preg_replace('/\D/', '', $_POST['whatsapp'] ?? '');
        $email    = trim($_POST['email'] ?? '');
        $cargo    = trim($_POST['cargo'] ?? 'Supervisor');
        $ativo    = isset($_POST['ativo']) ? 1 : 0;
        
        if ($id > 0 && !empty($nome) && !empty($whatsapp)) {
            pdo()->prepare("UPDATE supervisores SET nome=?, whatsapp=?, email=?, cargo=?, ativo=? WHERE id=?")
                ->execute([$nome, $whatsapp, $email, $cargo, $ativo, $id]);
            $msg = '✓ Supervisor atualizado!';
        }
    }
    
    if ($action === 'excluir') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            pdo()->prepare("DELETE FROM supervisores WHERE id=?")->execute([$id]);
            $msg = '✓ Supervisor removido.';
        }
    }
    
    if ($action === 'alternar_status') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            pdo()->prepare("UPDATE supervisores SET ativo = NOT ativo WHERE id=?")->execute([$id]);
            $msg = '✓ Status alterado.';
        }
    }
}

// Lista supervisores
$supervisores = pdo()->query("SELECT * FROM supervisores ORDER BY ativo DESC, nome ASC")->fetchAll();
$totalAtivos  = count(array_filter($supervisores, fn($s) => $s['ativo']));

require_once __DIR__ . '/includes/header.php';
?>

<style>
.sup-card {
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 16px;
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    gap: 14px;
    transition: .2s;
}
.sup-card:hover { border-color: var(--cyan); }
.sup-card.inativo { opacity: 0.5; }
.sup-avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background: linear-gradient(135deg, var(--cyan), var(--green));
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    font-weight: 800;
    color: #050e1a;
    flex-shrink: 0;
}
.sup-info { flex: 1; min-width: 0; }
.sup-nome { font-size: 14px; font-weight: 700; color: var(--text); }
.sup-cargo { font-size: 11px; color: var(--muted); }
.sup-whatsapp { font-size: 11px; font-family: var(--mono); color: var(--green); margin-top: 3px; }
.sup-actions { display: flex; gap: 6px; flex-shrink: 0; }
.badge-status {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 10px;
    font-weight: 700;
    font-family: var(--mono);
}
.badge-ativo { background: var(--green)1a; color: var(--green); }
.badge-inativo { background: var(--muted)1a; color: var(--muted); }
</style>

<div class="topbar">
    <button class="btn-hamburger" onclick="abrirDrawer()">☰</button>
    <div>
        <div class="page-title">👥 Supervisores</div>
        <div class="page-sub"><?= $totalAtivos ?> ativo(s) · <?= count($supervisores) ?> cadastrado(s)</div>
    </div>
    <div class="topbar-actions">
        <button class="btn btn-primary btn-sm" onclick="abrirModal('modal-supervisor')">+ Novo Supervisor</button>
    </div>
</div>

<div class="content" style="max-width: 800px">

<?php if ($msg):  ?><div class="alert alert-success"><?= e($msg) ?></div><?php endif; ?>
<?php if ($erro): ?><div class="alert alert-danger"><?= e($erro) ?></div><?php endif; ?>

<?php if (empty($supervisores)): ?>
    <div style="text-align:center;padding:40px;color:var(--muted)">
        <div style="font-size:48px;margin-bottom:12px">👥</div>
        <div style="font-size:14px">Nenhum supervisor cadastrado</div>
        <button class="btn btn-primary btn-sm" style="margin-top:12px" onclick="abrirModal('modal-supervisor')">+ Adicionar</button>
    </div>
<?php else: ?>
    <?php foreach ($supervisores as $sup): ?>
    <div class="sup-card <?= $sup['ativo'] ? '' : 'inativo' ?>">
        <div class="sup-avatar"><?= strtoupper(substr($sup['nome'], 0, 2)) ?></div>
        <div class="sup-info">
            <div class="sup-nome">
                <?= e($sup['nome']) ?>
                <span class="badge-status <?= $sup['ativo'] ? 'badge-ativo' : 'badge-inativo' ?>">
                    <?= $sup['ativo'] ? 'ATIVO' : 'INATIVO' ?>
                </span>
            </div>
            <div class="sup-cargo"><?= e($sup['cargo']) ?></div>
            <div class="sup-whatsapp">📱 <?= e($sup['whatsapp']) ?></div>
            <?php if ($sup['email']): ?>
            <div style="font-size:10px;color:var(--muted)">✉ <?= e($sup['email']) ?></div>
            <?php endif; ?>
        </div>
        <div class="sup-actions">
            <button class="btn btn-ghost btn-xs" onclick="editarSupervisor(<?= $sup['id'] ?>, '<?= addslashes($sup['nome']) ?>', '<?= $sup['whatsapp'] ?>', '<?= addslashes($sup['email'] ?? '') ?>', '<?= addslashes($sup['cargo']) ?>', <?= $sup['ativo'] ?>)">✎</button>
            <form method="post" style="display:inline">
                <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
                <input type="hidden" name="action" value="alternar_status">
                <input type="hidden" name="id" value="<?= $sup['id'] ?>">
                <button type="submit" class="btn btn-ghost btn-xs" title="<?= $sup['ativo'] ? 'Desativar' : 'Ativar' ?>">
                    <?= $sup['ativo'] ? '⏸' : '▶' ?>
                </button>
            </form>
            <form method="post" style="display:inline" onsubmit="return confirm('Excluir permanentemente?')">
                <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
                <input type="hidden" name="action" value="excluir">
                <input type="hidden" name="id" value="<?= $sup['id'] ?>">
                <button type="submit" class="btn btn-danger btn-xs">✕</button>
            </form>
        </div>
    </div>
    <?php endforeach; ?>
<?php endif; ?>

</div>

<!-- Modal Adicionar/Editar Supervisor -->
<div class="modal-overlay" id="modal-supervisor">
    <div class="modal" style="max-width: 480px">
        <div class="modal-header">
            <div class="modal-title" id="modal-sup-title">Novo Supervisor</div>
            <button class="modal-close" onclick="fecharModal('modal-supervisor')">✕</button>
        </div>
        <form method="post" style="padding: 20px">
            <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
            <input type="hidden" name="action" id="sup-action" value="adicionar">
            <input type="hidden" name="id" id="sup-id" value="">
            
            <div class="form-group">
                <label class="form-label">NOME *</label>
                <input class="form-input" type="text" name="nome" id="sup-nome" required placeholder="Nome completo">
            </div>
            <div class="form-group">
                <label class="form-label">WHATSAPP * (somente números)</label>
                <input class="form-input" type="tel" name="whatsapp" id="sup-whatsapp" required placeholder="17999999999">
            </div>
            <div class="form-group">
                <label class="form-label">CARGO</label>
                <input class="form-input" type="text" name="cargo" id="sup-cargo" placeholder="Supervisor">
            </div>
            <div class="form-group">
                <label class="form-label">E-MAIL</label>
                <input class="form-input" type="email" name="email" id="sup-email" placeholder="email@exemplo.com">
            </div>
            <div class="form-group" id="sup-ativo-group" style="display:none">
                <label style="display:flex;align-items:center;gap:8px;cursor:pointer">
                    <input type="checkbox" name="ativo" id="sup-ativo" checked>
                    <span style="font-size:12px">Supervisor ativo</span>
                </label>
            </div>
            <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:16px">
                <button type="button" class="btn btn-ghost btn-sm" onclick="fecharModal('modal-supervisor')">Cancelar</button>
                <button type="submit" class="btn btn-primary btn-sm" id="sup-submit">✓ Salvar</button>
            </div>
        </form>
    </div>
</div>

<script>
function editarSupervisor(id, nome, whatsapp, email, cargo, ativo) {
    document.getElementById('sup-action').value = 'editar';
    document.getElementById('sup-id').value = id;
    document.getElementById('sup-nome').value = nome;
    document.getElementById('sup-whatsapp').value = whatsapp;
    document.getElementById('sup-cargo').value = cargo;
    document.getElementById('sup-email').value = email;
    document.getElementById('sup-ativo').checked = ativo == 1;
    document.getElementById('sup-ativo-group').style.display = '';
    document.getElementById('modal-sup-title').textContent = 'Editar Supervisor';
    document.getElementById('sup-submit').textContent = '✓ Atualizar';
    abrirModal('modal-supervisor');
}

// Limpar formulário ao abrir para novo
document.querySelector('[onclick="abrirModal(\'modal-supervisor\')"]')?.addEventListener('click', () => {
    document.getElementById('sup-action').value = 'adicionar';
    document.getElementById('sup-id').value = '';
    document.getElementById('sup-nome').value = '';
    document.getElementById('sup-whatsapp').value = '';
    document.getElementById('sup-cargo').value = 'Supervisor';
    document.getElementById('sup-email').value = '';
    document.getElementById('sup-ativo-group').style.display = 'none';
    document.getElementById('modal-sup-title').textContent = 'Novo Supervisor';
    document.getElementById('sup-submit').textContent = '✓ Salvar';
});
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>