<?php
// admin/wiki_config.php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
require '../includes/conexao.php';

// SEGURANÇA
if (!isset($_SESSION['account_id'])) { header("Location: ../login.php"); exit; }

$stmt = $pdo->prepare("SELECT page_access, name FROM accounts WHERE id = ?");
$stmt->execute([$_SESSION['account_id']]);
$acc = $stmt->fetch();

if (!$acc || $acc['page_access'] < 3) {
    die("<div class='container p-5 text-center text-white bg-dark'><h1>⛔ Acesso Negado</h1><a href='../index.php' class='btn btn-warning'>Voltar</a></div>");
}

$page_title = "Gestão da Wiki";

// Header
if(file_exists('../includes/admin_header.php')) include '../includes/admin_header.php';
else include '../includes/header.php';

$msg = '';
$action = $_GET['action'] ?? 'view_articles';
$editId = (int)($_GET['edit'] ?? 0);

// Helper Slug
function slugify($text) {
    $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    $text = preg_replace('~[^-\w]+~', '', $text);
    $text = trim($text, '-');
    $text = preg_replace('~-+~', '-', $text);
    $text = strtolower($text);
    return empty($text) ? 'n-a' : $text;
}

// --- PROCESSAMENTOS ---

// A. Categorias
if (isset($_POST['save_category'])) {
    $name = trim($_POST['name']);
    $desc = trim($_POST['description']);
    $sort = (int)($_POST['sort_order'] ?? 0);
    $slug = slugify($name);
    $catId = (int)$_POST['cat_id'];

    if ($catId > 0) {
        $pdo->prepare("UPDATE wiki_categories SET name=?, slug=?, description=?, sort_order=? WHERE id=?")->execute([$name, $slug, $desc, $sort, $catId]);
        $msg = '<div class="alert alert-info shadow-sm"><i class="fas fa-check-circle"></i> Categoria atualizada!</div>';
    } else {
        $pdo->prepare("INSERT INTO wiki_categories (name, slug, description, sort_order) VALUES (?, ?, ?, ?)")->execute([$name, $slug, $desc, $sort]);
        $msg = '<div class="alert alert-success shadow-sm"><i class="fas fa-plus-circle"></i> Categoria criada!</div>';
    }
    $action = 'view_categories';
}

// B. Artigos
if (isset($_POST['save_article'])) {
    $title = trim($_POST['title']);
    $content = $_POST['content']; // HTML do Editor
    $catId = (int)$_POST['category_id'];
    $tags = trim($_POST['tags']);
    $slug = slugify($title);
    $artId = (int)$_POST['article_id'];
    $time = time();

    if ($artId > 0) {
        $pdo->prepare("UPDATE wiki_articles SET title=?, slug=?, content=?, category_id=?, tags=?, updated_at=? WHERE id=?")->execute([$title, $slug, $content, $catId, $tags, $time, $artId]);
        $msg = '<div class="alert alert-info shadow-sm"><i class="fas fa-check-circle"></i> Artigo atualizado!</div>';
    } else {
        $pdo->prepare("INSERT INTO wiki_articles (title, slug, content, category_id, tags, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)")->execute([$title, $slug, $content, $catId, $tags, $time, $time]);
        $msg = '<div class="alert alert-success shadow-sm"><i class="fas fa-plus-circle"></i> Artigo publicado!</div>';
    }
    $action = 'view_articles';
}

// C. Exclusões
if (isset($_GET['delete_cat'])) {
    $pdo->prepare("DELETE FROM wiki_categories WHERE id=?")->execute([(int)$_GET['delete_cat']]);
    $msg = '<div class="alert alert-danger shadow-sm">Categoria removida.</div>';
    $action = 'view_categories';
}
if (isset($_GET['delete_article'])) {
    $pdo->prepare("DELETE FROM wiki_articles WHERE id=?")->execute([(int)$_GET['delete_article']]);
    $msg = '<div class="alert alert-danger shadow-sm">Artigo removido.</div>';
    $action = 'view_articles';
}

// --- DADOS ---
$categoriesList = $pdo->query("SELECT * FROM wiki_categories ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);
$articlesData = $pdo->query("SELECT a.*, c.name as cat_name FROM wiki_articles a JOIN wiki_categories c ON a.category_id = c.id ORDER BY a.updated_at DESC")->fetchAll(PDO::FETCH_ASSOC);

// Preenchimento Edição
$editCategory = ($action == 'edit_category' && $editId) ? $pdo->query("SELECT * FROM wiki_categories WHERE id=$editId")->fetch() : null;
$editArticle = ($action == 'edit_article' && $editId) ? $pdo->query("SELECT * FROM wiki_articles WHERE id=$editId")->fetch() : null;
?>

<style>
    /* Admin Dark Theme */
    body { background-color: #0f172a; color: #f8fafc; font-family: 'Poppins', sans-serif; }
    .card { background-color: #1e293b; border: 1px solid rgba(255,255,255,0.1); color: #fff; border-radius: 12px; }
    .table { color: #cbd5e1; }
    .table-hover tbody tr:hover { background-color: rgba(255,255,255,0.02); color: #fff; }
    .table thead th { background-color: #0f172a; border-bottom: 2px solid #334155; color: #94a3b8; font-size: 0.8rem; text-transform: uppercase; }
    .form-control, .form-select { background-color: #0f172a; border: 1px solid rgba(255,255,255,0.2); color: #fff; }
    .form-control:focus, .form-select:focus { background-color: #0f172a; color: #fff; border-color: #3b82f6; box-shadow: 0 0 0 0.25rem rgba(59, 130, 246, 0.25); }
    .form-label { color: #cbd5e1; font-weight: 600; text-transform: uppercase; font-size: 0.8rem; }
    .tox-tinymce { border: 1px solid rgba(255,255,255,0.2) !important; border-radius: 8px !important; }
</style>

<div class="container my-5">

    <div class="d-flex justify-content-between align-items-center mb-4 border-bottom border-secondary pb-3">
        <div>
            <h2 class="fw-bold text-white mb-0"><i class="fas fa-book-open text-primary me-2"></i>Gestão Wiki</h2>
            <p class="text-white-50 m-0">Organize o conhecimento do servidor.</p>
        </div>
        <div class="btn-group">
            <a href="?action=view_articles" class="btn btn-sm <?php echo $action == 'view_articles' ? 'btn-primary' : 'btn-outline-secondary'; ?>">Artigos</a>
            <a href="?action=view_categories" class="btn btn-sm <?php echo $action == 'view_categories' ? 'btn-primary' : 'btn-outline-secondary'; ?>">Categorias</a>
        </div>
    </div>

    <?php echo $msg; ?>

    <?php if ($action === 'view_categories'): ?>
        <div class="card shadow">
            <div class="card-header bg-primary text-white fw-bold d-flex justify-content-between align-items-center">
                <span>Categorias Ativas</span>
                <a href="?action=edit_category" class="btn btn-sm btn-light text-primary fw-bold"><i class="fas fa-plus"></i> Nova</a>
            </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Nome</th>
                            <th>Descrição</th>
                            <th>Ordem</th>
                            <th class="text-end">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($categoriesList as $cat): ?>
                        <tr>
                            <td><?php echo $cat['id']; ?></td>
                            <td class="fw-bold text-info"><?php echo htmlspecialchars($cat['name']); ?></td>
                            <td class="text-muted small"><?php echo htmlspecialchars($cat['description']); ?></td>
                            <td><span class="badge bg-secondary"><?php echo $cat['sort_order']; ?></span></td>
                            <td class="text-end">
                                <a href="?action=edit_category&edit=<?php echo $cat['id']; ?>" class="btn btn-sm btn-info"><i class="fas fa-edit"></i></a>
                                <a href="?delete_cat=<?php echo $cat['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Excluir esta categoria?');"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

    <?php elseif ($action === 'edit_category'): ?>
        <div class="col-md-6 mx-auto">
            <div class="card shadow border-warning">
                <div class="card-header bg-warning text-dark fw-bold">
                    <i class="fas fa-folder"></i> <?php echo $editCategory ? 'Editar Categoria' : 'Nova Categoria'; ?>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="save_category" value="1">
                        <input type="hidden" name="cat_id" value="<?php echo $editCategory['id'] ?? 0; ?>">
                        
                        <div class="mb-3">
                            <label class="form-label">Nome</label>
                            <input type="text" name="name" class="form-control" required value="<?php echo $editCategory['name'] ?? ''; ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Descrição</label>
                            <input type="text" name="description" class="form-control" value="<?php echo $editCategory['description'] ?? ''; ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Ordem (Sort)</label>
                            <input type="number" name="sort_order" class="form-control" value="<?php echo $editCategory['sort_order'] ?? 0; ?>">
                        </div>
                        <div class="d-grid gap-2">
                            <button class="btn btn-warning fw-bold text-dark">Salvar</button>
                            <a href="?action=view_categories" class="btn btn-outline-secondary">Cancelar</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

    <?php elseif ($action === 'view_articles'): ?>
        <div class="card shadow">
            <div class="card-header bg-success text-white fw-bold d-flex justify-content-between align-items-center">
                <span>Biblioteca de Artigos</span>
                <a href="?action=edit_article" class="btn btn-sm btn-light text-success fw-bold"><i class="fas fa-plus"></i> Novo Artigo</a>
            </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Título</th>
                            <th>Categoria</th>
                            <th>Views</th>
                            <th>Atualizado</th>
                            <th class="text-end">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($articlesData as $art): ?>
                        <tr>
                            <td class="fw-bold text-white"><?php echo htmlspecialchars($art['title']); ?></td>
                            <td><span class="badge bg-dark border border-secondary"><?php echo htmlspecialchars($art['cat_name']); ?></span></td>
                            <td><?php echo $art['views']; ?></td>
                            <td class="text-muted small"><?php echo date('d/m/Y', $art['updated_at']); ?></td>
                            <td class="text-end">
                                <a href="?action=edit_article&edit=<?php echo $art['id']; ?>" class="btn btn-sm btn-info"><i class="fas fa-edit"></i></a>
                                <a href="?delete_article=<?php echo $art['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Excluir artigo?');"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

    <?php elseif ($action === 'edit_article'): ?>
        <div class="card shadow border-top border-4 border-success">
            <div class="card-header bg-transparent text-white fw-bold py-3">
                <i class="fas fa-pen-nib text-success me-2"></i> <?php echo $editArticle ? 'Editando Artigo' : 'Escrever Novo Artigo'; ?>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="save_article" value="1">
                    <input type="hidden" name="article_id" value="<?php echo $editArticle['id'] ?? 0; ?>">

                    <div class="row g-3 mb-3">
                        <div class="col-md-8">
                            <label class="form-label">Título do Artigo</label>
                            <input type="text" name="title" class="form-control form-control-lg" placeholder="Ex: Sistema de Pesca" required value="<?php echo $editArticle['title'] ?? ''; ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Categoria</label>
                            <select name="category_id" class="form-select form-select-lg" required>
                                <option value="">Selecione...</option>
                                <?php foreach($categoriesList as $c): ?>
                                    <option value="<?php echo $c['id']; ?>" <?php echo (isset($editArticle['category_id']) && $editArticle['category_id'] == $c['id']) ? 'selected' : ''; ?>>
                                        <?php echo $c['name']; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Tags (Busca)</label>
                        <input type="text" name="tags" class="form-control" placeholder="Separadas por vírgula" value="<?php echo $editArticle['tags'] ?? ''; ?>">
                    </div>

                    <div class="mb-4">
                        <label class="form-label">Conteúdo</label>
                        <textarea id="editor" name="content" rows="20"><?php echo $editArticle['content'] ?? ''; ?></textarea>
                    </div>

                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-success btn-lg fw-bold px-5"><i class="fas fa-save me-2"></i> Publicar</button>
                        <a href="?action=view_articles" class="btn btn-outline-secondary btn-lg">Cancelar</a>
                    </div>
                </form>
            </div>
        </div>
    <?php endif; ?>

</div>

<?php include '../includes/footer.php'; ?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.8.2/tinymce.min.js"></script>
<script>
    tinymce.init({
        selector: '#editor',
        height: 600,
        skin: "oxide-dark",
        content_css: "dark",
        menubar: true,
        plugins: 'advlist autolink lists link image charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime media table help wordcount',
        toolbar: 'undo redo | blocks | bold italic underline forecolor backcolor | alignleft aligncenter alignright | bullist numlist outdent indent | removeformat | help',
        content_style: 'body { font-family: Poppins, sans-serif; font-size: 16px; color: #e2e8f0; background-color: #1e293b; }'
    });
</script>
</body>
</html>