<?php
session_start();

// Opcional: Adicione a sua verificação de login aqui
// if (!isset($_SESSION['logado']) || $_SESSION['nivel'] !== 'admin') { header("Location: index.php"); exit; }

// Chama o seu arquivo que liga aos bancos de dados
require_once 'conexao.php';

$isAdmin = true;
$usuarioLogado = $_SESSION['usuario'] ?? 'Admin';
$msg = "";
$msg_tipo = "";
$total_msg_nao_lidas = 0; // Variável para o ícone de mensagens

// --- 1. CONFIGURAÇÕES VISUAIS DO PAINEL ---
$nomePainel = "IPTV PANEL"; 
$corPrimaria = "#7367f0"; 
try {
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($conf) {
        if (!empty($conf['NomePainel'])) $nomePainel = $conf['NomePainel'];
        if (!empty($conf['TemaPainel'])) $corPrimaria = $conf['TemaPainel'];
    }
} catch (Exception $e) { }

// ================================================================
// CRIAÇÃO AUTOMÁTICA DA TABELA DE LICENÇAS (Banco GERAL)
// ================================================================
try {
    $sql_tabela = "
    CREATE TABLE IF NOT EXISTS `licencas` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `cliente_nome` varchar(100) NOT NULL,
      `chave_licenca` varchar(50) NOT NULL,
      `dominio_permitido` varchar(150) NOT NULL,
      `data_vencimento` date NOT NULL,
      `status` enum('ativo','bloqueado') DEFAULT 'ativo',
      `data_criacao` timestamp DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      UNIQUE KEY `chave_licenca` (`chave_licenca`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
    
    $connGeral->exec($sql_tabela);

} catch (PDOException $e) {
    die("Erro ao criar tabela de licenças.");
}

// Função para gerar uma Chave de Licença única
function gerarChave($tamanho = 16) {
    return strtoupper(substr(md5(uniqid(rand(), true)), 0, $tamanho));
}

// ================================================================
// PROCESSAR AÇÕES (POST)
// ================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao'])) {
    $acao = $_POST['acao'];

    // 1. ADICIONAR
    if ($acao === 'adicionar') {
        $cliente = trim($_POST['cliente']);
        $dominio = trim($_POST['dominio']);
        $dias = (int)$_POST['dias'];
        $chave = gerarChave();
        $vencimento = date('Y-m-d', strtotime("+$dias days"));

        $stmt = $connGeral->prepare("INSERT INTO licencas (cliente_nome, chave_licenca, dominio_permitido, data_vencimento, status) VALUES (?, ?, ?, ?, 'ativo')");
        if($stmt->execute([$cliente, $chave, $dominio, $vencimento])) {
            $msg = "Licença criada! Chave: <strong class='text-warning'>$chave</strong>";
            $msg_tipo = "success";
        }
    }
    
    // 2. BLOQUEAR / DESBLOQUEAR
    if ($acao === 'bloquear') {
        $id = $_POST['id'];
        $novo_status = $_POST['status_atual'] === 'ativo' ? 'bloqueado' : 'ativo';
        $stmt = $connGeral->prepare("UPDATE licencas SET status = ? WHERE id = ?");
        $stmt->execute([$novo_status, $id]);
        $msg = "Status atualizado!";
        $msg_tipo = "info";
    }

    // 3. RENOVAR (+30 DIAS)
    if ($acao === 'renovar') {
        $id = $_POST['id'];
        $stmt = $connGeral->prepare("UPDATE licencas SET data_vencimento = DATE_ADD(data_vencimento, INTERVAL 30 DAY), status = 'ativo' WHERE id = ?");
        $stmt->execute([$id]);
        $msg = "Renovado por +30 dias!";
        $msg_tipo = "success";
    }

    // 4. EDITAR (NOME, DOMÍNIO E DATA)
    if ($acao === 'editar') {
        $id = $_POST['id'];
        $nome = trim($_POST['cliente_nome']);
        $dominio = trim($_POST['dominio_permitido']);
        $venc = $_POST['data_vencimento'];
        
        $stmt = $connGeral->prepare("UPDATE licencas SET cliente_nome = ?, dominio_permitido = ?, data_vencimento = ? WHERE id = ?");
        $stmt->execute([$nome, $dominio, $venc, $id]);
        $msg = "Dados atualizados!";
        $msg_tipo = "success";
    }

    // 5. EXCLUIR
    if ($acao === 'excluir') {
        $id = $_POST['id'];
        $stmt = $connGeral->prepare("DELETE FROM licencas WHERE id = ?");
        $stmt->execute([$id]);
        $msg = "Licença removida!";
        $msg_tipo = "danger";
    }
}

// Buscar todas as licenças
$licencas = $connGeral->query("SELECT * FROM licencas ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);

?>

<!DOCTYPE html>
<html lang="pt-br">
<head>

<?php include 'tema_global.php'; ?>



    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SaaS Master | <?= htmlspecialchars($nomePainel) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root { --primary: <?= $corPrimaria ?>; --bg-body: #151521; --bg-card: #1e1e2d; --text-color: #d0d2d6; --border-color: #2b2b40; }
        body { background: var(--bg-body); color: #fff; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; }
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid #333; z-index: 1050; padding: 20px; overflow-y: auto; transition: 0.3s; }
        .nav-link { color: #a6a6b7; padding: 12px 15px; border-radius: 8px; display: flex; align-items: center; gap: 12px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }
        .main-content { margin-left: 260px; transition: 0.3s; min-height: 100vh; }
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--primary) 100%); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; }
        .card-custom { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 12px; overflow: hidden; margin-bottom: 20px; }
        .form-control, .form-select { background: #151521 !important; border: 1px solid #444 !important; color: #fff !important; }
        .table-dark { --bs-table-bg: transparent; margin-bottom: 0; }
        .table-dark th { border-bottom-color: #333; color: #a6a6b7; font-size: 0.8rem; text-transform: uppercase; }
        .table-dark td { border-bottom-color: #2b2b40; vertical-align: middle; }
        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; } .mobile-toggle { display: block !important; } 
        }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; margin-right: 15px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; }
        .overlay.show { display: block; }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>


<main class="main-content">
    <div class="top-header">
        <div class="d-flex align-items-center w-100">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title"><i class="fas fa-crown text-warning me-2"></i> Gestão Mestre de Aluguer</div>
        </div>
    </div>

    <div class="container-fluid p-3 p-md-4">
        <?php if($msg): ?>
            <div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show border-0 shadow-sm">
                <?= $msg ?> <button class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-md-4 mb-4">
                <div class="card card-custom p-4 shadow">
                    <h5 class="fw-bold text-white mb-4"><i class="fas fa-plus-circle me-2 text-primary"></i> Nova Licença</h5>
                    <form method="POST">
                        <input type="hidden" name="acao" value="adicionar">
                        <div class="mb-3"><label class="form-label text-white-50">Nome do Cliente</label>
                            <input type="text" name="cliente" class="form-control" placeholder="Ex: Painel do João" required>
                        </div>
                        <div class="mb-3"><label class="form-label text-white-50">Domínio/IP</label>
                            <input type="text" name="dominio" value="*" class="form-control">
                        </div>
                        <div class="mb-4"><label class="form-label text-white-50">Validade (Dias)</label>
                            <input type="number" name="dias" class="form-control" value="30" required>
                        </div>
                        <button type="submit" class="btn text-white w-100 fw-bold" style="background-color: var(--primary);">GERAR AGORA</button>
                    </form>
                </div>
            </div>

            <div class="col-md-8">
                <div class="card card-custom p-3 shadow">
                    <h5 class="fw-bold text-white mb-3 ms-2 mt-2">Licenças Ativas</h5>
                    <div class="table-responsive">
                        <table class="table table-dark table-hover align-middle">
                            <thead>
                                <tr>
                                    <th>Cliente</th>
                                    <th>Domínio / IP</th>
                                    <th>Chave / Vencimento</th>
                                    <th>Status</th>
                                    <th class="text-end">Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($licencas as $lic): 
                                    $vencido = strtotime($lic['data_vencimento'] . ' 23:59:59') < time();
                                ?>
                                <tr>
                                    <td class="fw-bold text-white"><?= htmlspecialchars($lic['cliente_nome']) ?></td>
                                    <td>
                                        <span class="badge bg-dark text-info border border-secondary" style="font-size: 0.8rem;">
                                            <?= htmlspecialchars($lic['dominio_permitido']) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <small class="text-warning d-block font-monospace"><?= htmlspecialchars($lic['chave_licenca']) ?></small>
                                        <small class="<?= $vencido ? 'text-danger' : 'text-white-50' ?>">Vence: <?= date('d/m/Y', strtotime($lic['data_vencimento'])) ?></small>
                                    </td>
                                    <td>
                                        <?php if($lic['status'] === 'bloqueado'): ?><span class="badge bg-danger">Bloqueado</span>
                                        <?php elseif($vencido): ?><span class="badge bg-warning text-dark">Expirado</span>
                                        <?php else: ?><span class="badge bg-success">Ativo</span><?php endif; ?>
                                    </td>
                                    <td class="text-end">
                                        <div class="btn-group">
                                            <button class="btn btn-sm btn-outline-info" onclick='abrirModalEditar(<?= json_encode($lic) ?>)' title="Editar"><i class="fas fa-edit"></i></button>
                                            <form method="POST" class="d-inline">
                                                <input type="hidden" name="acao" value="renovar"><input type="hidden" name="id" value="<?= $lic['id'] ?>">
                                                <button class="btn btn-sm btn-outline-success" title="Renovar +30 dias"><i class="fas fa-sync-alt"></i></button>
                                            </form>
                                            <form method="POST" class="d-inline">
                                                <input type="hidden" name="acao" value="bloquear"><input type="hidden" name="id" value="<?= $lic['id'] ?>"><input type="hidden" name="status_atual" value="<?= $lic['status'] ?>">
                                                <button class="btn btn-sm <?= $lic['status'] === 'ativo' ? 'btn-outline-warning' : 'btn-outline-primary' ?>" title="Bloquear / Desbloquear"><i class="fas fa-ban"></i></button>
                                            </form>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('Apagar permanentemente?')">
                                                <input type="hidden" name="acao" value="excluir"><input type="hidden" name="id" value="<?= $lic['id'] ?>">
                                                <button class="btn btn-sm btn-outline-danger" title="Apagar Licença"><i class="fas fa-trash-alt"></i></button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<div class="modal fade" id="modalEditar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary text-white">
            <form method="POST">
                <input type="hidden" name="acao" value="editar"><input type="hidden" name="id" id="edit_id">
                <div class="modal-header border-secondary"><h5 class="modal-title">Editar Licença</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <div class="mb-3"><label class="form-label text-white-50">Nome do Cliente</label><input type="text" name="cliente_nome" id="edit_nome" class="form-control" required></div>
                    <div class="mb-3"><label class="form-label text-white-50">Domínio / IP</label><input type="text" name="dominio_permitido" id="edit_dominio" class="form-control" required></div>
                    <div class="mb-3"><label class="form-label text-white-50">Data de Vencimento</label><input type="date" name="data_vencimento" id="edit_venc" class="form-control" required></div>
                </div>
                <div class="modal-footer border-secondary"><button type="submit" class="btn btn-primary w-100 fw-bold">SALVAR ALTERAÇÕES</button></div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu() { document.getElementById('sidebar').classList.toggle('show'); document.getElementById('overlay').classList.toggle('show'); }
    
    // Função atualizada para preencher também o campo do Domínio no Modal
    function abrirModalEditar(dados) {
        document.getElementById('edit_id').value = dados.id;
        document.getElementById('edit_nome').value = dados.cliente_nome;
        document.getElementById('edit_dominio').value = dados.dominio_permitido;
        document.getElementById('edit_venc').value = dados.data_vencimento;
        new bootstrap.Modal(document.getElementById('modalEditar')).show();
    }
</script>
</body>
</html>