<?php
include "auth.php";
checkPermission(['admin','manager','staff']); // allow all roles here
?>
<?php

require_once "db.php";

/* -------------------------
   Handle Create Category
------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'create') {
        $name = trim($_POST['category_name']);
        if ($name !== '') {
            $stmt = $conn->prepare("INSERT INTO expense_categories (category_name) VALUES (?)");
            $stmt->bind_param("s", $name);
            $stmt->execute();
            $stmt->close();
        }
        header("Location: expense-category.php");
        exit();
    }
    if ($_POST['action'] === 'edit') {
        $id = intval($_POST['category_id']);
        $name = trim($_POST['category_name']);
        if ($id > 0 && $name !== '') {
            $stmt = $conn->prepare("UPDATE expense_categories SET category_name=? WHERE category_id=?");
            $stmt->bind_param("si", $name, $id);
            $stmt->execute();
            $stmt->close();
        }
        header("Location: expense-category.php");
        exit();
    }
}

/* -------------------------
   Handle Delete
------------------------- */
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    if ($id > 0) {
        $stmt = $conn->prepare("DELETE FROM expense_categories WHERE category_id=?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->close();
    }
    header("Location:expense-category.php");
    exit();
}

/* -------------------------
   Fetch Categories
------------------------- */
$sql = "SELECT * FROM expense_categories ORDER BY category_name ASC";
$categories = $conn->query($sql);
?>
<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Expense Categories</title>
        <link rel="stylesheet" href="css/style.css">
    </head>

    <body class="expense-category-page">
        <!-- Global header start -->
        <?php
            include("global/header.php");
         ?>
            <!-- Global header end -->

            <!-- Main -->
            <main class="main">
                <header class="topbar">
                    <button class="hamburger" id="hamburger" aria-label="Toggle menu">☰</button>

                    <div style="margin-left:8px;font-weight:600">Dashboard <span class="topbar-menu-space"> > </span> Expense Category</div>
                    <!-- Global Notification start -->
            <?php include("global/notify.php"); ?>
            <!-- Global Notification end -->
                    <div class="profile">
                        <button class="profile-btn" id="profileBtn" aria-expanded="false">
                        <span>Welcome <?php echo $_SESSION['username']; ?></span>
                        <img class="avatar" src="https://i.pravatar.cc/80" alt="Profile" />
                    </button>
                        <nav class="dropdown" id="profileDropdown">
                            <a href="profile.php">Profile Settings</a>
                        <a href="users.php">Users Settings</a>
                            <a href="logout.php">Logout</a>
                        </nav>
                    </div>
                </header>

                <section class="content">
                    <div class="container">
                        <div class="filter-box">
                            <div class="form-group">
                                <button class="btn" onclick="openCreateModal()">✚ Create Category</button>
                            </div>
                        </div>

                        <table>
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Category Name</th>
                                    <th style="width: 25%; text-align: center;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($categories && $categories->num_rows > 0): ?>
                                <?php while ($c = $categories->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <?php echo $c['category_id']; ?>
                                    </td>
                                    <td>
                                        <?php echo htmlspecialchars($c['category_name']); ?>
                                    </td>
                                    <td class="excat-action-btn">
                                        <button class="btn" onclick='openEditModal(<?php echo json_encode($c); ?>)'>Edit</button>
                                        <a href="?delete=<?php echo $c['category_id']; ?>" class="btn btn-danger" onclick="return confirm('Delete this category?')">Delete</a>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                                <?php else: ?>
                                <tr>
                                    <td colspan="3" style="text-align:center;color:#6b7280;">No categories found</td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </section>

                <!-- Create Modal -->
                <div class="modal" id="createModal">
                    <div class="modal-content">
                        <span class="close" onclick="closeModal('createModal')">&times;</span>
                        <h3>Create Expense Category</h3>
                        <form method="post">
                            <input type="hidden" name="action" value="create">
                            <div class="form-group">
                                <label>Category Name</label>
                                <input type="text" name="category_name" required>
                            </div>
                            <button type="submit" class="btn submit-btn">Save</button>
                        </form>
                    </div>
                </div>

                <!-- Edit Modal -->
                <div class="modal" id="editModal">
                    <div class="modal-content">
                        <span class="close" onclick="closeModal('editModal')">&times;</span>
                        <h3>Edit Expense Category</h3>
                        <form method="post" id="editForm">
                            <input type="hidden" name="action" value="edit">
                            <input type="hidden" name="category_id" id="editId">
                            <label>Category Name</label><br>
                            <input type="text" name="category_name" id="editName" required><br><br>
                            <button type="submit" class="btn">Update</button>
                        </form>
                    </div>
                </div>

                <script>
                    // Sidebar accordion: click ONLY the top-level buttons, not the whole LI.
                    const submenuButtons = document.querySelectorAll(".has-submenu > .menu-link");
                    submenuButtons.forEach((btn) => {
                        btn.addEventListener("click", (e) => {
                            e.preventDefault(); // keep as a toggle, no page jump
                            const currentItem = btn.parentElement; // .has-submenu
                            const isOpen = currentItem.classList.contains("open");

                            // Close other open menus (accordion behavior)
                            document.querySelectorAll(".has-submenu.open").forEach((li) => {
                                if (li !== currentItem) {
                                    li.classList.remove("open");
                                    const b = li.querySelector(".menu-link");
                                    if (b) b.setAttribute("aria-expanded", "false");
                                }
                            });

                            // Toggle current
                            currentItem.classList.toggle("open");
                            btn.setAttribute("aria-expanded", String(!isOpen));
                        });
                    });

                    // Ensure clicks inside submenu DO NOT toggle/close the parent unintentionally
                    document.querySelectorAll(".submenu").forEach((ul) => {
                        ul.addEventListener("click", (e) => {
                            e.stopPropagation();
                        });
                    });

                    // Mobile: show/hide sidebar
                    const sidebar = document.getElementById("sidebar");
                    const hamburger = document.getElementById("hamburger");
                    hamburger.addEventListener("click", () => {
                        sidebar.classList.toggle("active");
                    });

                    // Close sidebar when clicking outside on small screens
                    document.addEventListener("click", (e) => {
                        const isClickInside = sidebar.contains(e.target) || hamburger.contains(e.target);
                        if (!isClickInside && sidebar.classList.contains("active")) {
                            sidebar.classList.remove("active");
                        }
                    });

                    // Profile dropdown
                    const profileBtn = document.getElementById("profileBtn");
                    const profileDropdown = document.getElementById("profileDropdown");
                    profileBtn.addEventListener("click", (e) => {
                        e.stopPropagation();
                        const open = profileDropdown.classList.toggle("open");
                        profileBtn.setAttribute("aria-expanded", String(open));
                    });
                    document.addEventListener("click", () => profileDropdown.classList.remove("open"));
                </script>
                <script>
                    function openCreateModal() {
                        document.getElementById('createModal').style.display = 'flex';
                    }

                    function openEditModal(category) {
                        document.getElementById('editId').value = category.category_id;
                        document.getElementById('editName').value = category.category_name;
                        document.getElementById('editModal').style.display = 'flex';
                    }

                    function closeModal(id) {
                        document.getElementById(id).style.display = 'none';
                    }
                    window.onclick = function(event) {
                        if (event.target.classList.contains('modal')) {
                            event.target.style.display = 'none';
                        }
                    }
                </script>

    </body>

</html>