<?php
include 'verifica_login.php';
requer_admin();
include 'conexao.php';
include 'config/base_utils.php';

$conn = conectar_banco();
garantir_estrutura_bases($conn);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $acao = $_POST['acao'] ?? '';

    if ($acao === 'salvar') {
        $idbase = (int)($_POST['idbase'] ?? 0);
        $nome_base = trim($_POST['nome_base'] ?? '');
        $ativa = (($_POST['ativa'] ?? 'S') === 'N') ? 'N' : 'S';

        if ($nome_base === '') {
            header('Location: bases.php?msg=erro&detalhe=' . urlencode('Informe o nome da base.'));
            exit;
        }

        // Validar duplicidade de nome (considerando edição)
        if ($idbase > 0) {
            $stmt_dup = $conn->prepare("SELECT idbase FROM bases WHERE nome_base = ? AND idbase <> ? LIMIT 1");
            if ($stmt_dup) {
                $stmt_dup->bind_param('si', $nome_base, $idbase);
                $stmt_dup->execute();
                $existe_dup = $stmt_dup->get_result()->fetch_assoc();
                $stmt_dup->close();
                if ($existe_dup) {
                    header('Location: bases.php?id=' . $idbase . '&msg=erro&detalhe=' . urlencode('Já existe uma base com esse nome.'));
                    exit;
                }
            }
        } else {
            $stmt_dup = $conn->prepare("SELECT idbase FROM bases WHERE nome_base = ? LIMIT 1");
            if ($stmt_dup) {
                $stmt_dup->bind_param('s', $nome_base);
                $stmt_dup->execute();
                $existe_dup = $stmt_dup->get_result()->fetch_assoc();
                $stmt_dup->close();
                if ($existe_dup) {
                    header('Location: bases.php?msg=erro&detalhe=' . urlencode('Já existe uma base com esse nome.'));
                    exit;
                }
            }
        }

        if ($idbase > 0) {
            $stmt = $conn->prepare("UPDATE bases SET nome_base = ?, ativa = ? WHERE idbase = ?");
            if (!$stmt) {
                header('Location: bases.php?id=' . $idbase . '&msg=erro&detalhe=' . urlencode('Erro ao preparar atualização da base.'));
                exit;
            }
            $stmt->bind_param('ssi', $nome_base, $ativa, $idbase);
            if (!$stmt->execute()) {
                $detalhe = $stmt->error ?: 'Erro ao atualizar base.';
                $stmt->close();
                header('Location: bases.php?id=' . $idbase . '&msg=erro&detalhe=' . urlencode($detalhe));
                exit;
            }
            $stmt->close();
        } else {
            $stmt = $conn->prepare("INSERT INTO bases (nome_base, ativa) VALUES (?, ?)");
            if (!$stmt) {
                header('Location: bases.php?msg=erro&detalhe=' . urlencode('Erro ao preparar cadastro da base.'));
                exit;
            }
            $stmt->bind_param('ss', $nome_base, $ativa);
            if (!$stmt->execute()) {
                $detalhe = $stmt->error ?: 'Erro ao cadastrar base.';
                $stmt->close();
                header('Location: bases.php?msg=erro&detalhe=' . urlencode($detalhe));
                exit;
            }
            $stmt->close();
        }

        header('Location: bases.php?msg=sucesso');
        exit;
    }

    if ($acao === 'alterar_status') {
        $idbase = (int)($_POST['idbase'] ?? 0);
        $novo_status = (($_POST['novo_status'] ?? 'S') === 'N') ? 'N' : 'S';

        if ($idbase > 0) {
            $stmt = $conn->prepare("UPDATE bases SET ativa = ? WHERE idbase = ?");
            if ($stmt) {
                $stmt->bind_param('si', $novo_status, $idbase);
                $stmt->execute();
                $stmt->close();
            }
        }

        header('Location: bases.php?msg=sucesso');
        exit;
    }
}

$bases = [];
$res = $conn->query("SELECT b.idbase, b.nome_base, b.ativa, COUNT(e.ID_EMPRESA) AS total_empresas FROM bases b LEFT JOIN empresas e ON e.idbase = b.idbase GROUP BY b.idbase, b.nome_base, b.ativa ORDER BY b.nome_base ASC");
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $bases[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Cadastro de Bases</title>
<style>
    body{ font-family: Arial, sans-serif; background:#f4f4f4; padding:20px; }
    .container{ max-width:1000px; margin:0 auto; background:#fff; padding:20px; border-radius:6px; box-shadow:0 2px 6px rgba(0,0,0,0.08); }
    table{ width:100%; border-collapse: collapse; margin-top:12px; }
    th, td{ padding:8px 10px; border-bottom:1px solid #eee; text-align:left; }
    th{ background:#004d99; color:#fff; }
    .msg{ padding:8px; background:#e8f5e9; color:#1b5e20; border-radius:4px; margin:10px 0; }
    .erro{ padding:8px; background:#f8d7da; color:#721c24; border-radius:4px; margin:10px 0; }
    label{ display:block; font-weight:bold; margin-bottom:5px; }
    input[type=text], select{ width:100%; padding:8px; border:1px solid #ccc; border-radius:4px; }
    .row{ display:grid; grid-template-columns: 1fr 180px 170px; gap:10px; align-items:end; }
    .btn{ background:#004d99; color:#fff; border:none; border-radius:4px; padding:8px 12px; cursor:pointer; text-decoration:none; display:inline-block; }
    .btn-secondary{ background:#6c757d; }
    .btn-warn{ background:#f57c00; }
    .modal-overlay{ display:none; position:fixed; inset:0; background:rgba(0,0,0,.55); z-index:999; align-items:center; justify-content:center; padding:20px; }
    .modal{ width:100%; max-width:560px; background:#fff; border-radius:10px; box-shadow:0 10px 35px rgba(0,0,0,.25); overflow:hidden; }
    .modal-header{ background:#004d99; color:#fff; padding:14px 18px; display:flex; justify-content:space-between; align-items:center; }
    .modal-close{ background:transparent; border:0; color:#fff; font-size:1.2em; cursor:pointer; }
    .modal-body{ padding:16px 18px; }
    .modal-footer{ padding:14px 18px; border-top:1px solid #eee; display:flex; justify-content:flex-end; gap:8px; background:#fafafa; }
</style>
</head>
<body>
<div class="container">
    <h1>Cadastro de Bases</h1>
    <div style="margin-bottom:10px; display:flex; gap:10px; flex-wrap:wrap;">
        <a href="principal_administrador.php" class="btn btn-secondary">← Voltar para Principal</a>
        <a href="empresas.php" class="btn btn-secondary">🏢 Empresas</a>
    </div>

    <?php if (isset($_GET['msg']) && $_GET['msg'] === 'sucesso'): ?>
        <div class="msg">✓ Operação concluída com sucesso.</div>
    <?php endif; ?>
    <?php if (isset($_GET['msg']) && $_GET['msg'] === 'erro'): ?>
        <div class="erro">✗ <?= htmlspecialchars($_GET['detalhe'] ?? 'Erro ao processar') ?></div>
    <?php endif; ?>

    <form method="post" action="bases.php" style="background:#f8f9fa; border:1px solid #e0e0e0; border-radius:6px; padding:14px;">
        <input type="hidden" name="acao" value="salvar">
        <input type="hidden" name="idbase" value="0">

        <div class="row">
            <div>
                <label>Nome da base</label>
                <input type="text" name="nome_base" maxlength="100" required value="" placeholder="Ex.: Base Março 2026">
            </div>
            <div>
                <label>Status</label>
                <select name="ativa">
                    <option value="S" selected>Ativa</option>
                    <option value="N">Inativa</option>
                </select>
            </div>
            <div>
                <button type="submit" class="btn" style="width:100%;">Cadastrar base</button>
            </div>
        </div>
    </form>

    <table>
        <thead>
            <tr>
                <th>ID Base</th>
                <th>Nome</th>
                <th>Status</th>
                <th>Empresas</th>
                <th>Ações</th>
            </tr>
        </thead>
        <tbody>
            <?php if (count($bases) > 0): ?>
                <?php foreach ($bases as $base): ?>
                    <tr>
                        <td><?= (int)$base['idbase'] ?></td>
                        <td><?= htmlspecialchars($base['nome_base']) ?></td>
                        <td><?= ($base['ativa'] === 'S') ? 'Ativa' : 'Inativa' ?></td>
                        <td><?= (int)$base['total_empresas'] ?></td>
                        <td style="display:flex; gap:6px; flex-wrap:wrap;">
                            <button
                                type="button"
                                class="btn btn-warn"
                                onclick="abrirModalEditarBase(<?= (int)$base['idbase'] ?>, <?= htmlspecialchars(json_encode((string)$base['nome_base']), ENT_QUOTES, 'UTF-8') ?>, <?= htmlspecialchars(json_encode((string)$base['ativa']), ENT_QUOTES, 'UTF-8') ?>)"
                            >Editar</button>
                            <form method="post" action="bases.php" style="margin:0;">
                                <input type="hidden" name="acao" value="alterar_status">
                                <input type="hidden" name="idbase" value="<?= (int)$base['idbase'] ?>">
                                <input type="hidden" name="novo_status" value="<?= ($base['ativa'] === 'S') ? 'N' : 'S' ?>">
                                <button type="submit" class="btn btn-secondary"><?= ($base['ativa'] === 'S') ? 'Inativar' : 'Ativar' ?></button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr><td colspan="5">Nenhuma base cadastrada.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<div class="modal-overlay" id="modal-editar-base">
    <div class="modal">
        <div class="modal-header">
            <h3 style="margin:0; font-size:1.05em;">✏️ Editar Base</h3>
            <button type="button" class="modal-close" onclick="fecharModalEditarBase()">✖</button>
        </div>
        <form method="post" action="bases.php">
            <input type="hidden" name="acao" value="salvar">
            <input type="hidden" name="idbase" id="modal-idbase" value="0">
            <div class="modal-body">
                <label for="modal-nome-base">Nome da base</label>
                <input type="text" id="modal-nome-base" name="nome_base" maxlength="100" required>

                <label for="modal-ativa-base" style="margin-top:10px;">Status</label>
                <select id="modal-ativa-base" name="ativa">
                    <option value="S">Ativa</option>
                    <option value="N">Inativa</option>
                </select>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="fecharModalEditarBase()">Cancelar</button>
                <button type="submit" class="btn">Salvar</button>
            </div>
        </form>
    </div>
</div>

<script>
function abrirModalEditarBase(idbase, nomeBase, ativa) {
    document.getElementById('modal-idbase').value = idbase || 0;
    document.getElementById('modal-nome-base').value = nomeBase || '';
    document.getElementById('modal-ativa-base').value = (ativa === 'N') ? 'N' : 'S';
    document.getElementById('modal-editar-base').style.display = 'flex';
}

function fecharModalEditarBase() {
    document.getElementById('modal-editar-base').style.display = 'none';
}

window.addEventListener('click', function(event) {
    const modal = document.getElementById('modal-editar-base');
    if (event.target === modal) {
        fecharModalEditarBase();
    }
});
</script>
</body>
</html>
