index.html

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NEGOCIO LEGAL</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #f8f8f8;
            color: #333;
        }
        header {
            width: 100%;
            background-color: #fff;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            text-align: center;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        footer {
            background-color: #333;
            color: #fff;
            text-align: center;
            padding: 20px;
            width: 100%;
        }
        footer p {
            margin: 0;
        }
        header #store-name {
            font-size: 2em;
            color: #333;
        }
        header #store-name::after {
            content: '';
            display: block;
            width: 100%;
            height: 2px;
            background-color: #333;
            margin-top: 5px;
        }
        header #banner-preview {
            max-width: 100%;
            height: auto;
            display: none;
            margin-top: 10px;
        }
        #product-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
            padding: 20px;
            width: 100%;
            max-width: 1200px;
        }
        .product {
            background-color: #fff;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
        .product img {
            max-width: 100%;
            height: auto;
        }
        .product h3 {
            margin: 10px 0;
        }
        .product button {
            background-color: #add8e6;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .product button:hover {
            background-color: #87ceeb;
        }
        #pagination {
            margin: 20px;
        }
        #pagination button {
            background-color: #add8e6;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            transition: background-color 0.3s ease;
            margin: 0 5px;
        }
        #pagination button:hover {
            background-color: #87ceeb;
        }
        #category-list {
            list-style-type: none;
            padding: 0;
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
        }
        #category-list li {
            margin: 0 10px;
        }
        #category-list a {
            text-decoration: none;
            color: #333;
            font-weight: bold;
            padding: 5px 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            transition: background-color 0.3s ease;
        }
        #category-list a:hover {
            background-color: #f0f0f0;
        }
        #cookieConsent {
            background: #333;
            color: #fff;
            padding: 10px;
            position: fixed;
            bottom: 0;
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        #cookieConsent p {
            margin: 0 10px 0 0;
        }
        #cookieButtons {
            display: flex;
        }
        #cookieButtons button {
            background: #007bff;
            color: #fff;
            border: none;
            padding: 10px;
            cursor: pointer;
            margin-left: 10px;
            transition: background-color 0.3s ease;
        }
        #cookieButtons button:first-of-type {
            margin-left: 0;
        }
        #cookieButtons button:hover {
            background: #0056b3;
        }
    </style>
</head>
<body>
    <header>
        <h1 id="store-name">NEGOCIO LEGAL</h1>
        <img id="banner-preview" src="" alt="Banner Preview">
    </header>
    <ul id="category-list"></ul>
    <div id="product-grid"></div>
    <div id="pagination"></div>
    <footer>
        <p>&copy; 2024 NEGOCIO LEGAL. Todos os direitos reservados.</p>
    </footer>

    <div id="cookieConsent">
        <p>Este site usa cookies para melhorar sua experiência. Ao continuar navegando, você concorda com o uso de cookies.</p>
        <div id="cookieButtons">
            <button id="acceptCookies">Aceitar</button>
            <button id="declineCookies">Recusar</button>
        </div>
    </div>

    <script>
        const productsPerPage = 20;
        let currentPage = 1;
        let products = [];
        let categories = [];

        function loadBanner() {
            fetch('admin.php?action=getBanner')
                .then(response => response.json())
                .then(data => {
                    if (data.text) {
                        document.getElementById('banner-preview').style.display = 'none';
                        document.getElementById('store-name').textContent = data.text;
                    } else {
                        document.getElementById('store-name').textContent = 'NEGOCIO LEGAL';
                        if (data.image) {
                            document.getElementById('banner-preview').src = data.image;
                            document.getElementById('banner-preview').style.display = 'block';
                        }
                    }
                })
                .catch(error => console.error('Erro ao carregar banner:', error));
        }

        function loadProducts(page) {
            fetch('admin.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ action: 'getProducts' })
            })
            .then(response => response.json())
            .then(data => {
                products = data;
                displayProducts(page);
            })
            .catch(error => console.error('Erro ao carregar produtos:', error));
        }

        function displayProducts(page) {
            const start = (page - 1) * productsPerPage;
            const end = start + productsPerPage;
            const productsToShow = products.slice(start, end);

            const productGrid = document.getElementById("product-grid");
            productGrid.innerHTML = "";

            productsToShow.forEach(product => {
                const productElement = document.createElement("div");
                productElement.className = "product";
                productElement.innerHTML = `
                    <img src="${product.image}" alt="${product.name}">
                    <h3>${product.name}</h3>
                    <button onclick="openProductPage('${product.link}')">Ver Produto</button>
                `;
                productGrid.appendChild(productElement);
            });

            displayPagination(page);
        }

        function displayPagination(page) {
            const totalPages = Math.ceil(products.length / productsPerPage);
            const pagination = document.getElementById("pagination");
            pagination.innerHTML = "";

            for (let i = 1; i <= totalPages; i++) {
                const button = document.createElement("button");
                button.textContent = i;
                if (i === page) {
                    button.style.backgroundColor = "#87ceeb";
                }
                button.addEventListener("click", () => {
                    currentPage = i;
                    displayProducts(currentPage);
                });
                pagination.appendChild(button);
            }
        }

        function loadCategories() {
            fetch('admin.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ action: 'getCategories' })
            })
            .then(response => response.json())
            .then(data => {
                categories = data;
                displayCategories();
            })
            .catch(error => console.error('Erro ao carregar categorias:', error));
        }

        function displayCategories() {
            const categoryList = document.getElementById("category-list");
            categoryList.innerHTML = "";

            categories.forEach(category => {
                const li = document.createElement("li");
                const a = document.createElement("a");
                a.href = "#";
                a.textContent = category.name;
                a.onclick = (e) => {
                    e.preventDefault();
                    loadProductsByCategory(category.id);
                };
                li.appendChild(a);
                categoryList.appendChild(li);
            });
        }

        function loadProductsByCategory(categoryId) {
            const filteredProducts = products.filter(product => product.categoryId === categoryId);
            displayFilteredProducts(filteredProducts);
        }

        function displayFilteredProducts(filteredProducts) {
            const productGrid = document.getElementById("product-grid");
            productGrid.innerHTML = "";

            filteredProducts.forEach(product => {
                const productElement = document.createElement("div");
                productElement.className = "product";
                productElement.innerHTML = `
                    <img src="${product.image}" alt="${product.name}">
                    <h3>${product.name}</h3>
                    <button onclick="openProductPage('${product.link}')">Ver Produto</button>
                `;
                productGrid.appendChild(productElement);
            });
        }

        function openProductPage(link) {
            window.location.href = link;
        }

        // Carregar banner, produtos e categorias ao carregar a página
        document.addEventListener("DOMContentLoaded", () => {
            loadBanner();
            loadProducts(currentPage);
            loadCategories();

            // Verificar se o usuário já aceitou os cookies
            const cookiesAccepted = localStorage.getItem('cookiesAccepted');
            if (cookiesAccepted) {
                document.getElementById("cookieConsent").style.display = "none";
            }
        });

        // Manipulação dos botões de cookies
        document.getElementById("acceptCookies").addEventListener("click", () => {
            localStorage.setItem('cookiesAccepted', true);
            document.getElementById("cookieConsent").style.display = "none";
        });

        document.getElementById("declineCookies").addEventListener("click", () => {
            document.getElementById("cookieConsent").style.display = "none";
        });
    </script>
</body>
</html>

admin.php

<?php
$servername = "127.0.0.1:3306";
$username = "u228248172_negociolegal_u";
$password = "Polara13#";
$dbname = "u228248172_negociolegal_b";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Function to create tables if they do not exist
function createTables($conn) {
    $createCategoriesTable = "CREATE TABLE IF NOT EXISTS categories (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL
    )";

    $createProductsTable = "CREATE TABLE IF NOT EXISTS products (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        image TEXT NOT NULL,
        link VARCHAR(255) NOT NULL,
        category VARCHAR(255) NOT NULL
    )";

    if ($conn->query($createCategoriesTable) !== TRUE) {
        echo "Error creating categories table: " . $conn->error;
    }

    if ($conn->query($createProductsTable) !== TRUE) {
        echo "Error creating products table: " . $conn->error;
    }
}

// Call the function to create tables
createTables($conn);

// Process API requests
$input = json_decode(file_get_contents('php://input'), true);

if (isset($input['action'])) {
    $action = $input['action'];

    switch ($action) {
        case 'updateBannerText':
            $text = $input['text'];

            $updateStatement = $conn->prepare("UPDATE banner SET text = ?");
            $updateStatement->bind_param("s", $text);

            if ($updateStatement->execute()) {
                echo json_encode(["message" => "Texto do banner atualizado no banco de dados com sucesso!"]);
            } else {
                echo json_encode(["message" => "Erro ao atualizar o texto do banner no banco de dados: " . $updateStatement->error]);
            }

            $updateStatement->close();
            break;

        case 'addProduct':
            $name = $input['name'];
            $link = $input['link'];
            $category = $input['category'];

            $image_path = ''; // Caminho padrão para a imagem

            if (isset($_FILES['product-image'])) {
                $image_name = $_FILES['product-image']['name'];
                $image_path = 'caminho/do/seu/diretorio/' . $image_name;

                if (move_uploaded_file($_FILES['product-image']['tmp_name'], $image_path)) {
                    // Imagem movida com sucesso
                    // Inserir no Banco de Dados
                    $stmt = $conn->prepare("INSERT INTO products (name, image, link, category) VALUES (?, ?, ?, ?)");
                    $stmt->bind_param("ssss", $name, $image_path, $link, $category);

                    if ($stmt->execute()) {
                        echo json_encode(["message" => "Produto adicionado com sucesso!", "success" => true]);
                    } else {
                        echo json_encode(["message" => "Erro ao adicionar produto: " . $stmt->error, "success" => false]);
                    }

                    $stmt->close();
                } else {
                    echo json_encode(["message" => "Erro ao mover a imagem.", "success" => false]);
                    exit;
                }
            }
            break;

        case 'addCategory':
            $name = $input['name'];

            $stmt = $conn->prepare("INSERT INTO categories (name) VALUES (?)");
            $stmt->bind_param("s", $name);

            if ($stmt->execute()) {
                echo json_encode(["message" => "Categoria adicionada com sucesso!", "success" => true]);
            } else {
                echo json_encode(["message" => "Erro ao adicionar categoria: " . $stmt->error, "success" => false]);
            }

            $stmt->close();
            break;

        case 'getProducts':
            $result = $conn->query("SELECT * FROM products");

            $products = [];
            while ($row = $result->fetch_assoc()) {
                $products[] = $row;
            }

            echo json_encode($products);
            break;

        case 'getCategories':
            $result = $conn->query("SELECT * FROM categories");

            $categories = [];
            while ($row = $result->fetch_assoc()) {
                $categories[] = $row;
            }

            echo json_encode($categories);
            break;

        case 'updateProduct':
            $id = $input['id'];
            $name = $input['name'];
            $image = $input['image'];
            $link = $input['link'];
            $category = $input['category'];

            $stmt = $conn->prepare("UPDATE products SET name=?, image=?, link=?, category=? WHERE id=?");
            $stmt->bind_param("ssssi", $name, $image, $link, $category, $id);

            if ($stmt->execute()) {
                echo json_encode(["message" => "Produto atualizado com sucesso!", "success" => true]);
            } else {
                echo json_encode(["message" => "Erro ao atualizar produto: " . $stmt->error, "success" => false]);
            }

            $stmt->close();
            break;

        case 'deleteProduct':
            $id = $input['id'];

            $stmt = $conn->prepare("DELETE FROM products WHERE id=?");
            $stmt->bind_param("i", $id);

            if ($stmt->execute()) {
                echo json_encode(["message" => "Produto excluído com sucesso!", "success" => true]);
            } else {
                echo json_encode(["message" => "Erro ao excluir produto: " . $stmt->error, "success" => false]);
            }

            $stmt->close();
            break;

        case 'saveBanner':
            $response = array();

            if (isset($input['text'])) {
                $text = $input['text'];
                $updateQuery = "UPDATE banner_table SET text = '{$text}' WHERE id = 1";

                if ($conn->query($updateQuery) === TRUE) {
                    $response['success'] = true;
                    $response['message'] = "Texto do banner atualizado com sucesso!";
                } else {
                    $response['success'] = false;
                    $response['message'] = "Erro ao atualizar o texto do banner: " . $conn->error;
                }
            } else {
                $response['success'] = false;
                $response['message'] = "Texto do banner não foi recebido.";
            }

            header('Content-Type: application/json');
            echo json_encode($response);
            exit;
            break;

        case 'getBanner':
            $banner_data = array(
                'text' => 'Texto do banner',
                'image' => 'uploads/banner.jpg' // URL da imagem do banner
            );

            header('Content-Type: application/json');
            echo json_encode($banner_data);
            exit;
            break;

        default:
            echo json_encode(["message" => "Ação inválida."]);
            break;
    }
} else {
    echo json_encode(["message" => "Nenhuma ação fornecida."]);
}

$conn->close();
?>
admin.js

let categories = [];
let products = [];

function loadBanner() {
    fetch('admin.php?action=getBanner')
        .then(response => response.json())
        .then(data => {
            if (data.image) {
                document.getElementById('banner-preview').src = data.image;
                document.getElementById('banner-preview').style.display = 'block';
            } else {
                document.getElementById('banner-preview').style.display = 'none';
            }
            document.getElementById('banner-text').value = data.text || '';
            
            // Atualize o título da loja com o texto do banner
            document.title = "Minha Loja - " + data.text;
        })
        .catch(error => console.error('Erro ao carregar banner:', error));
}

function saveBanner() {
    const bannerImage = document.getElementById('banner-image').files[0];
    const bannerText = document.getElementById('banner-text').value;
    
    const formData = new FormData();
    formData.append('action', 'saveBanner');
    if (bannerImage) {
        formData.append('image', bannerImage);
    }
    formData.append('text', bannerText);

    fetch('admin.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.message) {
            alert(data.message);
            // Atualize a interface se necessário
            loadBanner(); // Recarrega o banner após salvar
            updateTitleInDatabase(bannerText); // Salva o texto do banner no banco de dados
        }
    })
    .catch(error => console.error('Erro ao salvar banner:', error));
}

function updateTitleInDatabase(bannerText) {
    fetch('admin.php?action=updateBannerText', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ text: bannerText })
    })
    .then(response => response.json())
    .then(data => {
        if (data.message) {
            console.log(data.message);
        }
    })
    .catch(error => console.error('Erro ao atualizar título no banco de dados:', error));
}






function addCategory() {
    const categoryName = prompt('Digite o nome da nova categoria:');
    if (categoryName) {
        fetch('admin.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                action: 'addCategory',
                name: categoryName
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.message) {
                alert(data.message);
                if (data.success) {
                    loadCategories();
                }
            }
        })
        .catch(error => console.error('Erro:', error));
    }
}

function addProduct() {
    const productName = document.getElementById('product-name').value;
    const productImage = document.getElementById('product-image').files[0];
    const productLink = document.getElementById('product-link').value;
    const productCategory = document.getElementById('product-category').value;

    if (productName && productLink && productCategory) {
        const formData = new FormData();
        formData.append('action', 'addProduct'); // Adicione a ação 'addProduct'
        formData.append('name', productName);
        formData.append('link', productLink);
        formData.append('category', productCategory);
        formData.append('product-image', productImage);

        fetch('admin.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.message) {
                alert(data.message);
                if (data.success) {
                    clearForm();
                    loadProducts(); // Recarregar os produtos após adicionar um novo
                }
            }
        })
        .catch(error => console.error('Erro:', error));
    } else {
        alert('Por favor, preencha todos os campos obrigatórios.');
    }
}

function clearForm() {
    document.getElementById('product-name').value = '';
    document.getElementById('product-image').value = '';
    document.getElementById('product-image-preview').src = '';
    document.getElementById('product-link').value = '';
    document.getElementById('product-category').selectedIndex = 0;
}

function loadCategories() {
    fetch('admin.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ action: 'getCategories' })
    })
    .then(response => response.json())
    .then(data => {
        categories = data;
        updateCategoryOptions();
    })
    .catch(error => console.error('Erro:', error));
}

function updateCategoryOptions() {
    const categorySelect = document.getElementById('product-category');
    categorySelect.innerHTML = '';
    categories.forEach(category => {
        const option = document.createElement('option');
        option.value = category.name;
        option.textContent = category.name;
        categorySelect.appendChild(option);
    });
}

function loadProducts() {
    fetch('admin.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ action: 'getProducts' })
    })
    .then(response => response.json())
    .then(data => {
        products = data;
        displayProducts();
    })
    .catch(error => console.error('Erro:', error));
}

function displayProducts() {
    const productTableBody = document.getElementById('product-table-body');
    productTableBody.innerHTML = '';
    
    products.forEach(product => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${product.name}</td>
            <td><img src="${product.image}" alt="${product.name}" class="product-image"></td>
            <td><a href="${product.link}" target="_blank">${product.link}</a></td>
            <td>${product.category}</td>
            <td>
                <button class="edit-button" onclick="editProduct(${product.id})">Editar</button>
                <button class="delete-button" onclick="deleteProduct(${product.id})">Excluir</button>
            </td>
        `;
        productTableBody.appendChild(row);
    });
}

function editProduct(id) {
    const product = products.find(p => p.id === id);
    if (product) {
        document.getElementById('product-name').value = product.name;
        document.getElementById('product-link').value = product.link;
        document.getElementById('product-category').value = product.category;
        document.getElementById('add-button').style.display = 'none';
        document.getElementById('update-button').style.display = 'inline-block';
    }
}

function updateProduct() {
    const productName = document.getElementById('product-name').value;
    const productImage = document.getElementById('product-image').files[0];
    const productLink = document.getElementById('product-link').value;
    const productCategory = document.getElementById('product-category').value;

    if (productName && productLink && productCategory) {
        const formData = new FormData();
        formData.append('action', 'updateProduct');
        formData.append('name', productName);
        if (productImage) {
            formData.append('image', productImage);
        }
        formData.append('link', productLink);
        formData.append('category', productCategory);

        fetch('admin.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.message) {
                alert(data.message);
                if (data.success) {
                    clearForm();
                    document.getElementById('add-button').style.display = 'inline-block';
                    document.getElementById('update-button').style.display = 'none';
                    loadProducts();
                }
            }
        })
        .catch(error => console.error('Erro:', error));
    } else {
        alert('Por favor, preencha todos os campos obrigatórios.');
    }
}

function deleteProduct(id) {
    if (confirm('Tem certeza que deseja excluir este produto?')) {
        fetch('admin.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                action: 'deleteProduct',
                id: id
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.message) {
                alert(data.message);
                if (data.success) {
                    loadProducts();
                }
            }
        })
        .catch(error => console.error('Erro:', error));
    }
}

window.onload = function() {
    loadBanner(); // Load banner functionality
    loadCategories();
    loadProducts();
    const productImageInput = document.getElementById('product-image');
    const productImagePreview = document.getElementById('product-image-preview');
    
    productImageInput.addEventListener('change', function() {
        const file = this.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function() {
                productImagePreview.src = reader.result;
                productImagePreview.style.display = 'block';
            }
            reader.readAsDataURL(file);
        } else {
            productImagePreview.src = '';
            productImagePreview.style.display = 'none';
        }
    });
};
admin.html

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

     <!-- Adicione a biblioteca Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Administração de Produtos</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            margin: 0;
            padding: 0;
        }
        header {
            width: 100%;
            background-color: #f8f8f8;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
        header h1 {
            margin: 0;
            font-size: 24px;
        }
        .form-container, .products-container, .categories-container {
            width: 100%;
            max-width: 800px;
            margin: 20px;
            padding: 20px;
            border: 1px solid #ddd;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            background-color: #fff;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        .form-group input, .form-group select {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }
        .form-group button {
            background-color: #add8e6;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .form-group button:hover {
            background-color: #87ceeb;
        }
        .product-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #ddd;
        }
        .product-item button {
            background-color: #ff6961;
            border: none;
            padding: 5px 10px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .product-item button:hover {
            background-color: #ff5c5c;
        }
        .product-item .edit-button {
            background-color: #f0ad4e;
        }
        .product-item .edit-button:hover {
            background-color: #ec971f;
        }
        .product-item img {
            max-width: 50px;
            max-height: 50px;
        }
        .banner-container {
            width: 100%;
            max-width: 800px;
            margin: 20px;
            padding: 20px;
            border: 1px solid #ddd;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            background-color: #fff;
        }
        .banner-container h2 {
            margin-top: 0;
        }
        .banner-container .form-group {
            margin-bottom: 15px;
        }
        .banner-container .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        .banner-container .form-group input {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }
        .banner-container .form-group button {
            background-color: #add8e6;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .banner-container .form-group button:hover {
            background-color: #87ceeb;
        }
    </style>
</head>
<body>
    <header>
        <h1>Administração de Produtos</h1>
    </header>
    <div class="form-container">
        <div class="form-group">
            <label for="product-name">Nome do Produto</label>
            <input type="text" id="product-name" required>
        </div>
        <div class="form-group">
            <label for="product-image">Imagem do Produto</label>
            <input type="file" id="product-image" accept="image/*">
            <img id="product-image-preview" style="max-width: 20%; display: none; margin-top: 10px;">
        </div>
        <div class="form-group">
            <label for="product-link">Link do Produto</label>
            <input type="url" id="product-link" required>
        </div>
        <div class="form-group">
            <label for="product-category">Categoria do Produto</label>
            <select id="product-category" required>
                <!-- Options will be dynamically added -->
            </select>
        </div>
        <div class="form-group">
            <button id="add-button" onclick="addProduct()">Adicionar Produto</button>
            <button id="update-button" onclick="updateProduct()" style="display: none;">Atualizar Produto</button>
        </div>
    </div>
    <div class="categories-container">
        <h2>Categorias</h2>
        <button onclick="addCategory()">Adicionar Categoria</button>
        <ul id="category-list"></ul>
    </div>
    <div class="products-container">
        <h2>Produtos</h2>
        <table id="product-table">
            <thead>
                <tr>
                    <th>Nome</th>
                    <th>Imagem</th>
                    <th>Link</th>
                    <th>Categoria</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody id="product-table-body">
                <!-- Product rows will be dynamically added -->
                <tr class="product-item">
                    <td>Produto Exemplo</td>
                    <td><img src="imagem_exemplo.jpg" alt="Produto Exemplo"></td>
                    <td><a href="https://linkdoproduto.com">Link</a></td>
                    <td>Categoria Exemplo</td>
                    <td>
                        <button class="edit-button" onclick="editProduct(1)">Editar</button>
                        <button class="delete-button" onclick="deleteProduct(1)">Excluir</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <div class="banner-container">
        <h2>Alterar Banner do Site</h2>
        <div class="form-group">
            <label for="banner-image">Imagem do Banner</label>
            <input type="file" id="banner-image" accept="image/*">
            <img id="banner-preview" style="max-width: 100%; display: none; margin-top: 10px;">
        </div>
        <div class="form-group">
            <label for="banner-text">Texto do Banner</label>
            <input type="text" id="banner-text">
        </div>
        <div class="form-group">
            <button onclick="saveBanner()">Salvar Banner</button>
        </div>
    </div>
    <script src="admin.js"></script>
</body>
</html>
script.js

const productsPerPage = 20;
let currentPage = 1;
let products = [];
let categories = [];

function loadProductsFromStorage() {
    const storedProducts = localStorage.getItem('products');
    if (storedProducts) {
        products = JSON.parse(storedProducts);
    }
}

function loadCategoriesFromStorage() {
    const storedCategories = localStorage.getItem('categories');
    if (storedCategories) {
        categories = JSON.parse(storedCategories);
    }
}

function loadProducts(page) {
    loadProductsFromStorage();
    const start = (page - 1) * productsPerPage;
    const end = start + productsPerPage;
    const productsToShow = products.slice(start, end);

    const productGrid = document.getElementById("product-grid");
    productGrid.innerHTML = "";

    productsToShow.forEach(product => {
        const productElement = document.createElement("div");
        productElement.className = "product";
        productElement.innerHTML = `
            <img src="${product.image}" alt="${product.name}">
            <h3>${product.name}</h3>
            <button onclick="window.location.href='${product.link}'">Ver Produto</button>
            <button onclick="editProduct(${product.id})">Editar</button>
            <button onclick="deleteProduct(${product.id})">Excluir</button>
        `;
        productGrid.appendChild(productElement);
    });

    loadPagination(page);
}

function loadProductsByCategory(category) {
    const filteredProducts = products.filter(product => product.category === category);
    const productGrid = document.getElementById("product-grid");
    productGrid.innerHTML = "";

    filteredProducts.forEach(product => {
        const productElement = document.createElement("div");
        productElement.className = "product";
        productElement.innerHTML = `
            <img src="${product.image}" alt="${product.name}">
            <h3>${product.name}</h3>
            <button onclick="window.location.href='${product.link}'">Ver Produto</button>
            <button onclick="editProduct(${product.id})">Editar</button>
            <button onclick="deleteProduct(${product.id})">Excluir</button>
        `;
        productGrid.appendChild(productElement);
    });

    // Atualiza a paginação, se necessário
    loadPagination(1); // Reseta a paginação para 1 ao filtrar por categoria
}

function loadPagination(page) {
    const pagination = document.getElementById("pagination");
    pagination.innerHTML = "";

    const totalPages = Math.ceil(products.length / productsPerPage);

    if (page > 1) {
        const prevButton = document.createElement("button");
        prevButton.textContent = "Anterior";
        prevButton.onclick = () => loadProducts(page - 1);
        pagination.appendChild(prevButton);
    }

    if (page < totalPages) {
        const nextButton = document.createElement("button");
        nextButton.textContent = "Próxima";
        nextButton.onclick = () => loadProducts(page + 1);
        pagination.appendChild(nextButton);
    }
}

function loadCategoryList() {
    const categoryList = document.getElementById("category-list");
    categoryList.innerHTML = '';

    categories.forEach(category => {
        const categoryItem = document.createElement('li');
        categoryItem.innerHTML = `
            <a href="#" onclick="loadProductsByCategory('${category}')">${category}</a>
        `;
        categoryList.appendChild(categoryItem);
    });
}

// Funções para editar, atualizar e excluir produtos
function editProduct(id) {
    const product = products.find(p => p.id === id);
    if (product) {
        document.getElementById('product-name').value = product.name;
        document.getElementById('product-link').value = product.link;
        document.getElementById('product-category').value = product.category;
        document.getElementById('add-button').style.display = 'none';
        document.getElementById('update-button').style.display = 'inline-block';
    }
}

function updateProduct() {
    const productName = document.getElementById('product-name').value;
    const productImage = document.getElementById('product-image').files[0];
    const productLink = document.getElementById('product-link').value;
    const productCategory = document.getElementById('product-category').value;

    if (productName && productLink && productCategory) {
        const formData = new FormData();
        formData.append('action', 'updateProduct');
        formData.append('name', productName);
        if (productImage) {
            formData.append('image', productImage);
        }
        formData.append('link', productLink);
        formData.append('category', productCategory);

        fetch('admin.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.message) {
                alert(data.message);
                if (data.success) {
                    clearForm();
                    document.getElementById('add-button').style.display = 'inline-block';
                    document.getElementById('update-button').style.display = 'none';
                    loadProducts(currentPage);
                }
            }
        })
        .catch(error => console.error('Erro:', error));
    } else {
        alert('Por favor, preencha todos os campos obrigatórios.');
    }
}

function deleteProduct(id) {
    if (confirm('Tem certeza que deseja excluir este produto?')) {
        fetch('admin.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                action: 'deleteProduct',
                id: id
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.message) {
                alert(data.message);
                if (data.success) {
                    loadProducts(currentPage);
                }
            }
        })
        .catch(error => console.error('Erro:', error));
    }
}

// Inicializa a página com os produtos e categorias
loadProducts(currentPage);
loadCategoriesFromStorage();
loadCategoryList();