<?php 
    include('menu_admin.php');
    include_once 'model/posts_model.php';

    // Instantiate posts model and fetch all categories
    $posts_model = new posts_model();
    $categories = $posts_model->get_categories();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Admin Panel - Categories</title>
    <link rel="apple-touch-icon" sizes="76x76" href="images/logo.png">
    <link rel="icon" type="image/png" href="images/logo.png">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">
    <link rel="stylesheet" href="dist/css/adminlte.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        .category-table th, .category-table td {
            vertical-align: middle;
        }
    </style>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <section class="content">
            <div class="container-fluid">
                <h1 class="mb-4">Manage Categories</h1>

                <button type="button" class="btn btn-success mb-3" data-toggle="modal" data-target="#addCategoryModal">
    <i class="fas fa-plus"></i> Add New Category
</button>


                <!-- Categories Table -->
                <table class="table table-bordered category-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Category Name</th>
                            <th>Date Created</th>
                            <th>Created By</th>
                            <th>Usage</th> 
                            <th>Action</th> 
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                            if ($categories) {
                                $i = 1;
                                foreach ($categories as $category) {
                                    echo "<tr data-id='{$category['category_id']}'>";
                                    echo "<td>{$i}</td>";
                                    echo "<td>{$category['category_name']}</td>";
                                    echo "<td>" . date("F j, Y", strtotime($category['date_created'])) . "</td>";
                                    echo "<td>{$category['operator']}</td>";
                                    echo "<td>{$category['total']}</td>";
                                    echo "<td>";
                                    echo "<a href='#' class='btn btn-info btn-sm edit-category' data-id='{$category['category_id']}'>Edit</a> ";
                    
                                    echo "</td>";
                                    echo "</tr>";
                                    $i++;
                                }
                            } else {
                                echo "<tr><td colspan='6' class='text-center'>No categories found.</td></tr>";
                            }
                        ?>
                    </tbody>
                </table>


            </div>
        </section>
    </div>

    <!-- Add Category Modal -->
<!-- Add Category Modal -->
<div class="modal fade" id="addCategoryModal" tabindex="-1" role="dialog" aria-labelledby="addCategoryModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addCategoryModalLabel">Add New Category</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="addCategoryForm" method="post">
                <div class="modal-body">
                    <!-- Category Name -->
                    <div class="form-group">
                        <label for="categoryName">Category Name</label>
                        <input type="text" class="form-control" id="categoryName" name="categoryName" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Add Category</button>
                </div>
            </form>
        </div>
    </div>
</div>


    <!-- Edit Category Modal (Popup) -->
        <!-- Here we are just going to reuse the Add Modal structure to edit categories. -->
        <div class="modal fade" id="editCategoryModal" tabindex="-1" aria-labelledby="editCategoryModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editCategoryModalLabel">Edit Category</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <form id="editCategoryForm" method="post" action="edit_category_backend.php">
                        <div class="modal-body">
                            <!-- Category Name -->
                            <div class="form-group">
                                <label for="editCategoryName">Category Name</label>
                                <input type="text" class="form-control" id="editCategoryName" name="categoryName" required>
                                <input type="hidden" id="editCategoryId" name="categoryId">
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save Changes</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

    <!-- JS for Category Management -->
    <script src="plugins/jquery/jquery.min.js"></script>
    <script src="plugins/jquery-ui/jquery-ui.min.js"></script>
    <script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="dist/js/adminlte.js"></script>
    <script src="js/script.js"></script>
    
    <script>
    // Edit Category
    document.querySelectorAll('.edit-category').forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const categoryId = this.getAttribute('data-id');
            
            // Fetch category details using AJAX
            fetch(`get_category_details.php?category_id=${categoryId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Fill the modal with category data
                        document.getElementById('editCategoryId').value = categoryId;
                        document.getElementById('editCategoryName').value = data.category.category_name;

                        // Show the edit modal
                        var editModal = new bootstrap.Modal(document.getElementById('editCategoryModal'));
                        editModal.show();
                    } else {
                        Swal.fire('Error!', 'Failed to fetch category details.', 'error');
                    }
                })
                .catch(error => console.error('Error fetching category details:', error));
        });
    });



    
</script><script>
    // Handle the form submission for adding a category
    document.getElementById('addCategoryForm').addEventListener('submit', function(e) {
        e.preventDefault(); // Prevent default form submission

        // Get the category name from the form
        const categoryName = document.getElementById('categoryName').value;

        // Validate category name
        if (!categoryName) {
            Swal.fire('Error', 'Category name is required.', 'error');
            return;
        }

        // Create a FormData object to send the data
        const formData = new FormData();
        formData.append('categoryName', categoryName);

        // Send the form data to the backend script
        fetch('add_category_backend.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Close the modal if the category was successfully added
                var addModal = new bootstrap.Modal(document.getElementById('addCategoryModal'));
                addModal.hide(); // Close the modal

                // Show a success message
                Swal.fire('Success', data.message, 'success');

                // Optionally, you can update the category list dynamically without reloading the page
                // Example: Add the new category to the table or refresh the category list
                // This can be done by dynamically inserting a new row in the table
                const newCategoryRow = `
                    <tr>
                        <td>#</td>
                        <td>${categoryName}</td>
                        <td>Just Now</td>
                        <td>Admin</td>
                        <td>0</td>
                        <td>
                            <a href="#" class="btn btn-info btn-sm edit-category" data-id="newId">Edit</a>
                        </td>
                    </tr>`;
                document.querySelector('.category-table tbody').insertAdjacentHTML('afterbegin', newCategoryRow);
            } else {
                // Show an error message if something goes wrong
                Swal.fire('Error', data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire('Error', 'An error occurred while adding the category.', 'error');
        });
    });
</script>


</body>
</html>
