<?php
session_start();

// Verifica se o usuário está autenticado
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    // Se não estiver, verifica se houve tentativa de login
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username']) && isset($_POST['password'])) {
        // Verifica as credenciais de login
        $username = $_POST['username'];
        $password = $_POST['password'];

        // Credenciais de exemplo (substitua com lógica de autenticação adequada)
        if ($username === 'admin' && $password === 'admin') {
            $_SESSION['logged_in'] = true;
        } else {
            echo '<p class="alert alert-danger">Credenciais inválidas. Tente novamente.</p>';
        }
    }

    // Se não estiver logado, mostra o formulário de login e encerra a execução
    if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
        ?>

        <!DOCTYPE html>
        <html lang="pt-BR">
        <head>
            <meta charset="utf-8">
            <title>Gerenciamento de Conteúdo - Login</title>
            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
            <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css'>
            <style>
                .login-form {
                    max-width: 400px;
                    margin: 0 auto;
                    margin-top: 100px;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="login-form">
                    <h1 class="text-center">Login</h1>
                    <form method="POST">
                        <div class="form-group">
                            <label for="username">Usuário</label>
                            <input type="text" class="form-control" id="username" name="username" required>
                        </div>
                        <div class="form-group">
                            <label for="password">Senha</label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        <button type="submit" class="btn btn-primary btn-block">Entrar</button>
                    </form>
                </div>
            </div>
        </body>
        </html>

        <?php
        exit; // Encerra a execução do script se não estiver logado
    }
}

// Se estiver logado, continua com o gerenciamento de conteúdo
$dataFile = 'data.json';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents($dataFile), true);

    if (isset($_POST['set_background'])) {
        $data['background'] = $_POST['background'];
    } elseif (isset($_POST['add_category'])) {
        $newCategory = $_POST['category'];
        if (!in_array($newCategory, $data['categories'])) {
            $data['categories'][] = $newCategory;
        }
    } elseif (isset($_POST['delete_category'])) {
        $category = $_POST['category'];
        $data['categories'] = array_filter($data['categories'], fn($c) => $c !== $category);
        $data['cards'] = array_filter($data['cards'], fn($card) => $card['category'] !== $category);
    } elseif (isset($_POST['add'])) {
        $newItem = [
            'imge' => $_POST['imge'],
            'name' => $_POST['name'],
            'desc' => $_POST['desc'],
            'url' => $_POST['url'],
            'category' => $_POST['category']
        ];
        $data['cards'][] = $newItem;
    } elseif (isset($_POST['delete_card'])) {
        $index = $_POST['index'];
        array_splice($data['cards'], $index, 1);
    }

    file_put_contents($dataFile, json_encode($data));
    header("Location: manage.php");
    exit;
}

$data = json_decode(file_get_contents($dataFile), true);
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="utf-8">
    <title>Gerenciamento de Conteúdo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css'>
    <style>
        .btn-back-to-index {
            position: fixed;
            bottom: 30px;
            right: 30px;
            z-index: 1000;
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <h1>Gerenciamento de Conteúdo</h1>

        <h2>Plano de Fundo</h2>
        <form method="POST" class="mb-4">
            <div class="form-group">
                <label for="background">URL do Plano de Fundo</label>
                <input type="text" class="form-control" id="background" name="background" value="<?= htmlspecialchars($data['background']) ?>" required>
            </div>
            <button type="submit" name="set_background" class="btn btn-primary">Salvar Plano de Fundo</button>
        </form>

        <h2>Criar Nova Categoria</h2>
        <form method="POST" class="mb-4">
            <div class="form-group">
                <label for="category">Nome da Categoria</label>
                <input type="text" class="form-control" id="category" name="category" required>
            </div>
            <button type="submit" name="add_category" class="btn btn-primary">Adicionar Categoria</button>
        </form>

        <h2>Categorias Existentes</h2>
        <ul class="list-group mb-4">
            <?php foreach ($data['categories'] as $category) { ?>
                <li class="list-group-item d-flex justify-content-between align-items-center">
                    <?= htmlspecialchars($category) ?>
                    <form method="POST" class="m-0">
                        <input type="hidden" name="category" value="<?= $category ?>">
                        <button type="submit" name="delete_category" class="btn btn-danger">Remover</button>
                    </form>
                </li>
            <?php } ?>
        </ul>

        <h2>Adicionar Novo Card</h2>
        <form method="POST" class="mb-4">
            <div class="form-group">
                <label for="imge">Imagem URL</label>
                <input type="text" class="form-control" id="imge" name="imge" required>
            </div>
            <div class="form-group">
                <label for="name">Título</label>
                <input type="text" class="form-control" id="name" name="name" required>
            </div>
            <div class="form-group">
                <label for="desc">Descrição</label>
                <input type="text" class="form-control" id="desc" name="desc" required>
            </div>
            <div class="form-group">
                <label for="url">URL</label>
                <input type="text" class="form-control" id="url" name="url" required>
            </div>
            <div class="form-group">
                <label for="card_category">Categoria</label>
                <select class="form-control" id="card_category" name="category" required>
                    <option value="">Selecione a Categoria</option>
                    <?php foreach ($data['categories'] as $category) { ?>
                        <option value="<?= $category ?>"><?= $category ?></option>
                    <?php } ?>
                </select>
            </div>
            <button type="submit" name="add" class="btn btn-primary">Adicionar Card</button>
        </form>

        <h2>Cards Existentes</h2>
        <?php foreach ($data['categories'] as $category) { ?>
            <h3><?= $category ?></h3>
            <ul class="list-group mb-4">
                <?php foreach ($data['cards'] as $index => $item) {
                    if ($item['category'] === $category) { ?>
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <?= htmlspecialchars($item['name']) ?>
                            <form method="POST" class="m-0">
                                <input type="hidden" name="index" value="<?= $index ?>">
                                <button type="submit" name="delete_card" class="btn btn-danger">Remover</button>
                            </form>
                        </li>
                <?php } } ?>
            </ul>
        <?php } ?>

        <a href="index.php" class="btn btn-secondary btn-back-to-index">Voltar para a Página Inicial</a>