<?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;
            --overlay-desk: rgba(0, 0, 0, 0.65); 
            --overlay-mob: rgba(0, 0, 0, 0.85); 
        }
        body.light-mode { 
            --bg-body: #f4f5f8; 
            --bg-card: #ffffff; 
            --text-color: #5e5873; 
            --border-color: #ebe9f1; 
            --overlay-desk: rgba(255, 255, 255, 0.1); 
            --overlay-mob: rgba(255, 255, 255, 0); 
        }
        
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; padding: 0; }
        
        /* Sidebar Restourada Premium */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid var(--border-color); z-index: 1050; padding: 20px; overflow-y: auto; transition: transform 0.3s ease, box-shadow 0.3s ease; }
        .sidebar .nav-link { white-space: nowrap !important; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; color: #a6a6b7; padding: 12px 15px; border-radius: 8px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .sidebar .nav-link:hover, .sidebar .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .sidebar .nav-link i.fa-fw { margin-right: 8px; text-align: center; }
        .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 Flexbox (Para Rodapé Fixo) */
        .main-content { margin-left: 260px; transition: 0.3s; display: flex; flex-direction: column; min-height: 100vh; }
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--overlay-desk) 100%), var(--primary); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.3);}
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; margin: 0; }

        /* Elementos Premium */
        .card-custom { background-color: var(--bg-card) !important; border: 1px solid var(--border-color) !important; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        
        /* Tabela Dinâmica que respeita Tema Claro/Escuro DE VERDADE */
        .table-custom { width: 100%; margin-bottom: 0; border-collapse: separate; border-spacing: 0; background: transparent !important; }
        .table-custom th { background-color: var(--bg-card) !important; border-bottom: 1px solid var(--border-color) !important; color: #a6a6b7 !important; font-size: 0.8rem; text-transform: uppercase; font-weight: 700; padding: 15px; white-space: nowrap; }
        .table-custom td { background-color: var(--bg-card) !important; border-bottom: 1px solid var(--border-color) !important; color: var(--text-color) !important; vertical-align: middle; padding: 15px; font-size: 0.95rem; }
        .table-custom tbody tr:hover td { background-color: rgba(115, 103, 240, 0.08) !important; }

        /* Inputs Customizados Dinâmicos */
        .form-control, .form-select { background-color: rgba(0,0,0,0.1) !important; border: 1px solid var(--border-color) !important; color: var(--text-color) !important; border-radius: 8px; padding: 10px 15px; transition: 0.2s; }
        body.light-mode .form-control, body.light-mode .form-select { background-color: rgba(0,0,0,0.03) !important; }
        .form-control:focus, .form-select:focus { border-color: var(--primary) !important; box-shadow: 0 0 0 0.25rem rgba(115, 103, 240, 0.25) !important; background-color: transparent !important;}

        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); box-shadow: none; z-index: 1050; } 
            .sidebar.show { transform: translateX(0); box-shadow: 5px 0 30px rgba(0,0,0,0.9); } 
            .main-content { margin-left: 0; width: 100%;}
            .mobile-toggle { display: block !important; margin-right: 15px; } 
            .top-header { flex-direction: row; padding: 15px 20px; background: linear-gradient(var(--overlay-mob), var(--overlay-mob)), var(--primary); border-bottom: none; }
        }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; cursor: pointer; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7); z-index: 1040; backdrop-filter: blur(3px); }
        .overlay.show { display: block; }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>
<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<!-- O d-flex flex-column min-vh-100 garante que a página tenha a altura máxima e o rodapé fique embaixo -->
<main class="main-content d-flex flex-column min-vh-100">
    <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 bg-white rounded-circle p-1"></i> Gestão Mestre de Aluguer</div>
        </div>
    </div>

    <!-- Container flex-grow-1 estica o meio, empurrando o Rodapé para baixo -->
    <div class="container-fluid p-3 p-md-4 flex-grow-1">
        <?php if($msg): ?>
            <div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show border-0 shadow-sm fw-bold">
                <?= $msg ?> <button class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- COLUNA CRIAR NOVA LICENÇA (AGORA OCUPA 100% DA LARGURA) -->
            <div class="col-12 mb-4">
                <div class="card card-custom p-4 shadow-sm border-0">
                    <h5 class="fw-bold mb-4" style="color: var(--text-color);"><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="row g-3">
                            <div class="col-md-4 mb-3">
                                <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">NOME DO CLIENTE</label>
                                <input type="text" name="cliente" class="form-control" placeholder="Ex: Painel do João" required>
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">DOMÍNIO/IP</label>
                                <input type="text" name="dominio" value="*" class="form-control fw-bold text-info">
                                <small class="text-white-50 mt-1 d-block" style="font-size: 0.70rem;"><i class="fas fa-info-circle me-1"></i> Deixe * (asterisco) para liberar geral.</small>
                            </div>
                            
                            <div class="col-md-4 mb-4">
                                <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">VALIDADE (DIAS)</label>
                                <input type="number" name="dias" class="form-control text-center fw-bold" value="30" required>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn text-white w-100 fw-bold shadow-sm rounded-pill py-2" style="background-color: var(--primary);">GERAR AGORA</button>
                    </form>
                </div>
            </div>

            <!-- COLUNA LISTAR LICENÇAS (AGORA OCUPA 100% DA LARGURA) -->
            <div class="col-12 mb-4">
                <div class="card card-custom p-0 shadow-sm border-0">
                    <div class="p-4 border-bottom border-secondary bg-transparent">
                        <h5 class="mb-0 fw-bold" style="color: var(--text-color);"><i class="fas fa-list text-info me-2"></i> Licenças Ativas</h5>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-custom table-hover align-middle m-0">
                            <thead>
                                <tr>
                                    <th class="ps-4">Cliente</th>
                                    <th>Domínio / IP</th>
                                    <th>Chave / Vencimento</th>
                                    <th>Status</th>
                                    <th class="text-end pe-4">Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(empty($licencas)): ?>
                                    <tr><td colspan="5" class="text-center py-5" style="color: var(--text-color); opacity: 0.5;"><i class="fas fa-key fs-2 mb-2"></i><br>Nenhuma licença gerada ainda.</td></tr>
                                <?php else: foreach($licencas as $lic): 
                                    $vencido = strtotime($lic['data_vencimento'] . ' 23:59:59') < time();
                                ?>
                                <tr>
                                    <td class="ps-4 fw-bold" style="color: var(--text-color);"><?= htmlspecialchars($lic['cliente_nome']) ?></td>
                                    <td>
                                        <span class="badge bg-dark text-info border border-secondary shadow-sm px-2 py-1 fs-6">
                                            <?= htmlspecialchars($lic['dominio_permitido']) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <small class="text-warning fw-bold d-block font-monospace mb-1" style="background: rgba(255, 159, 67, 0.1); padding: 2px 6px; border-radius: 4px; display: inline-block !important;"><?= htmlspecialchars($lic['chave_licenca']) ?></small>
                                        <small class="fw-bold <?= $vencido ? 'text-danger' : 'text-success' ?>" style="opacity: 0.8;">Vence: <?= date('d/m/Y', strtotime($lic['data_vencimento'])) ?></small>
                                    </td>
                                    <td>
                                        <?php if($lic['status'] === 'bloqueado'): ?><span class="badge bg-danger bg-opacity-10 text-danger border border-danger px-2 py-1 shadow-sm">Bloqueado</span>
                                        <?php elseif($vencido): ?><span class="badge bg-warning bg-opacity-10 text-warning border border-warning px-2 py-1 shadow-sm">Expirado</span>
                                        <?php else: ?><span class="badge bg-success bg-opacity-10 text-success border border-success px-2 py-1 shadow-sm">Ativo</span><?php endif; ?>
                                    </td>
                                    <td class="text-end pe-4">
                                        <div class="d-flex gap-2 justify-content-end">
                                            <button class="btn btn-sm btn-outline-info shadow-sm rounded-3" onclick='abrirModalEditar(<?= json_encode($lic) ?>)' title="Editar">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <form method="POST" class="m-0" onsubmit="return confirm('Deseja renovar esta licença por mais 30 dias?')">
                                                <input type="hidden" name="acao" value="renovar"><input type="hidden" name="id" value="<?= $lic['id'] ?>">
                                                <button class="btn btn-sm btn-outline-success shadow-sm rounded-3" title="Renovar +30 dias"><i class="fas fa-sync-alt"></i></button>
                                            </form>
                                            <form method="POST" class="m-0">
                                                <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' ?> shadow-sm rounded-3" title="Bloquear / Desbloquear"><i class="fas fa-ban"></i></button>
                                            </form>
                                            <form method="POST" class="m-0" onsubmit="return confirm('Apagar permanentemente a licença de <?= htmlspecialchars($lic['cliente_nome']) ?>?')">
                                                <input type="hidden" name="acao" value="excluir"><input type="hidden" name="id" value="<?= $lic['id'] ?>">
                                                <button class="btn btn-sm btn-outline-danger shadow-sm rounded-3" title="Apagar Licença"><i class="fas fa-trash-alt"></i></button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Rodapé fixado no final do Main Content -->
    <div class="mt-auto w-100">
        <?php include 'rodape.php'; ?>
    </div>
</main>

<div class="modal fade" id="modalEditar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-secondary" style="background-color: var(--bg-card);">
            <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 fw-bold" style="color: var(--text-color);"><i class="fas fa-pen text-warning me-2"></i> Editar Licença</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1) grayscale(100%) brightness(200%);"></button>
                </div>
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">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 small fw-bold" style="color: var(--text-color); opacity: 0.7;">DOMÍNIO / IP</label>
                        <input type="text" name="dominio_permitido" id="edit_dominio" class="form-control text-info fw-bold" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">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 shadow-sm rounded-pill py-2">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>