<?php
session_start();
if (!isset($_SESSION['logado']) || $_SESSION['nivel'] !== 'admin') { 
    header("Location: index.php"); 
    exit; 
}
require_once 'conexao.php'; // Usa $connGeral

$msg = "";
$msg_tipo = "";

// --- 1. PROCESSAMENTO ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $acao = $_POST['acao'];
        $id   = $_POST['id'] ?? 0;

        // UPLOAD DE IMAGEM
        if ($acao === 'criar') {
            $nome = $_POST['nome'];
            
            if (isset($_FILES['arquivo']) && $_FILES['arquivo']['error'] === 0) {
                // Pasta de destino
                $diretorio = "assets/img/icones/";
                if(!is_dir($diretorio)) mkdir($diretorio, 0777, true);

                // Gera nome único para não sobrepor
                $ext = pathinfo($_FILES['arquivo']['name'], PATHINFO_EXTENSION);
                $novo_nome_arquivo = uniqid() . "." . $ext;
                
                if (move_uploaded_file($_FILES['arquivo']['tmp_name'], $diretorio . $novo_nome_arquivo)) {
                    // Salva no Banco
                    $sql = "INSERT INTO perfil_icone (nome, img) VALUES (?, ?)";
                    $stmt = $connGeral->prepare($sql);
                    $stmt->execute([$nome, $novo_nome_arquivo]);
                    
                    $msg = "Ícone enviado com sucesso!"; 
                    $msg_tipo = "success";
                } else {
                    $msg = "Erro ao mover o arquivo para a pasta.";
                    $msg_tipo = "danger";
                }
            } else {
                $msg = "Selecione uma imagem válida.";
                $msg_tipo = "warning";
            }
        }

        // EXCLUIR
        if ($acao === 'excluir') {
            // 1. Busca o nome do arquivo para deletar da pasta
            $stmt = $connGeral->prepare("SELECT img FROM perfil_icone WHERE id = ?");
            $stmt->execute([$id]);
            $arquivo = $stmt->fetchColumn();

            // 2. Deleta do banco
            $connGeral->prepare("DELETE FROM perfil_icone WHERE id = ?")->execute([$id]);

            // 3. Deleta o arquivo físico se existir
            if ($arquivo && file_exists("assets/img/icones/" . $arquivo)) {
                unlink("assets/img/icones/" . $arquivo);
            }

            $msg = "Ícone removido!";
            $msg_tipo = "danger";
        }

    } catch (PDOException $e) {
        $msg = "Erro: " . $e->getMessage();
        $msg_tipo = "danger";
    }
}

// --- 2. BUSCAR ÍCONES ---
$icones = $connGeral->query("SELECT * FROM perfil_icone ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerenciar Ícones | Painel</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 { --bg-body: #151521; --bg-card: #1e1e2d; --primary: #7367f0; }
        body { background: var(--bg-body); color: #fff; font-family: 'Segoe UI', sans-serif; }
        .sidebar { width: 260px; height: 100vh; position: fixed; background: #1e1e2d; padding: 20px; border-right: 1px solid #333; z-index: 1000; transition: 0.3s; }
        .main-content { margin-left: 260px; padding: 30px; transition: 0.3s; }
        .form-label { color: #ffffff !important; font-weight: 700; display: block; }
        .card-custom { background: var(--bg-card); border: 1px solid rgba(255,255,255,0.05); border-radius: 12px; }
        .form-control { background: #2b2b40 !important; border: 1px solid #444 !important; color: #fff !important; }
        
        /* Preview da Imagem na Tabela */
        .img-preview { width: 40px; height: 40px; object-fit: contain; background: rgba(255,255,255,0.1); border-radius: 5px; padding: 2px; }

        .table-dark { background-color: var(--bg-card) !important; color: #fff !important; }
        .table-dark th, .table-dark td { border-color: #333 !important; vertical-align: middle; }

        @media (max-width: 768px) { .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; padding: 15px; } .mobile-toggle { display: block !important; } }
        .mobile-toggle { display: none; font-size: 1.5rem; color: #fff; background: none; border: none; margin-bottom: 20px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 999; } .overlay.show { display: block; }
        .nav-link { color: #a6a6b7; text-decoration: none; display: flex; align-items: center; gap: 10px; padding: 10px; border-radius: 8px; } .nav-link.active { background: var(--primary); color: #fff; }
        .submenu-link { padding-left: 20px; font-size: 0.9rem; color: #b0b0c0; }
        .submenu-link:hover { color: #fff; background: rgba(255,255,255,0.05); }
    </style>
</head>
<body>

<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<nav class="sidebar" id="sidebar">
    <h4 class="mb-4 fw-bold text-white"><i class="fas fa-tv text-primary"></i> Painel v3.0</h4>
    <div class="nav flex-column gap-2">
        <a href="index.php" class="nav-link text-white"><i class="fas fa-home"></i> Dashboard</a>
        
        <?php if ($_SESSION['nivel'] === 'admin'): ?>
            <div class="mt-2 mb-1 px-3 text-uppercase fw-bold text-light" style="font-size: 0.75rem; opacity: 0.7;">Administração</div>
            
            <a class="nav-link text-white d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#submenuPainel" role="button" aria-expanded="true">
                <span><i class="fas fa-sliders-h text-info me-2"></i> Painel</span>
                <i class="fas fa-chevron-down small"></i>
            </a>
            <div class="collapse show" id="submenuPainel">
                <div class="bg-dark rounded border border-secondary p-2 ms-2 mb-2">
                    <a href="personalizar_painel.php" class="nav-link submenu-link"><i class="fas fa-paint-brush me-2 text-danger"></i> Personalizar</a>
                    <a href="config_geral.php" class="nav-link submenu-link"><i class="fas fa-cogs me-2 text-warning"></i> Config. Geral</a>
                    <a href="gerenciar_dns.php" class="nav-link submenu-link"><i class="fas fa-network-wired me-2 text-success"></i> Servidores DNS</a>
                    <a href="gerenciar_perfis.php" class="nav-link submenu-link"><i class="fas fa-layer-group me-2 text-primary"></i> Perfis</a>
                    <a href="gerenciar_mascara.php" class="nav-link submenu-link"><i class="fas fa-mask me-2 text-info"></i> Máscaras URL</a>
                    <a href="gerenciar_icones.php" class="nav-link submenu-link text-white" style="background: rgba(255,255,255,0.1);"><i class="fas fa-icons me-2 text-white"></i> Ícones</a>
                </div>
            </div>

            <a href="permissoes_server.php" class="nav-link text-white"><i class="fas fa-server text-white"></i> Permissões CSP</a>
            <a href="revendedores.php" class="nav-link text-white"><i class="fas fa-store"></i> Revendedores</a>
            <a href="configuracoes.php" class="nav-link text-white"><i class="fas fa-wallet"></i> Pagamentos (Global)</a>
            <div class="mb-2 border-bottom border-secondary opacity-50"></div>
        <?php else: ?>
            <a href="configuracoes.php" class="nav-link text-white"><i class="fas fa-wallet"></i> Meus Pagamentos</a>
        <?php endif; ?>

        <a href="clientes.php" class="nav-link text-white"><i class="fas fa-users"></i> Clientes</a>
        <a href="sair.php" class="nav-link text-danger mt-4"><i class="fas fa-sign-out-alt"></i> Sair</a>
    </div>
</nav>

<main class="main-content">
    <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold text-white">Gerenciar Ícones</h3>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalCriar">
            <i class="fas fa-cloud-upload-alt me-2"></i> Enviar Ícone
        </button>
    </div>

    <?php if($msg): ?>
        <div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show">
            <?= $msg ?> <button class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card card-custom">
        <div class="table-responsive">
            <table class="table table-dark table-hover mb-0 align-middle">
                <thead>
                    <tr class="text-white small text-uppercase">
                        <th class="ps-4">Preview</th>
                        <th>Nome do Ícone</th>
                        <th>Arquivo</th>
                        <th class="text-end pe-4">Ação</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($icones)): ?>
                        <tr><td colspan="4" class="text-center text-white py-3">Nenhum ícone cadastrado.</td></tr>
                    <?php else: ?>
                        <?php foreach($icones as $ic): ?>
                        <tr>
                            <td class="ps-4">
                                <img src="assets/img/icones/<?= $ic['img'] ?>" class="img-preview" alt="Icone">
                            </td>
                            <td class="fw-bold text-white"><?= $ic['nome'] ?></td>
                            <td class="text-white-50 small"><?= $ic['img'] ?></td>
                            <td class="text-end pe-4">
                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="acao" value="excluir">
                                    <input type="hidden" name="id" value="<?= $ic['id'] ?>">
                                    <button class="btn btn-sm btn-danger rounded-circle" onclick="return confirm('Excluir este ícone?')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<div class="modal fade" id="modalCriar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary">
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="acao" value="criar">
                <div class="modal-header border-secondary text-white">
                    <h5 class="modal-title">Novo Ícone</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">Nome de Identificação</label>
                        <input type="text" name="nome" class="form-control" placeholder="Ex: Logo Claro TV" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Arquivo de Imagem (PNG, JPG)</label>
                        <input type="file" name="arquivo" class="form-control" accept="image/*" required>
                    </div>
                </div>
                <div class="modal-footer border-secondary">
                    <button type="submit" class="btn btn-primary w-100 fw-bold">Enviar</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'); }
</script>
</body>
</html>
