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

<?php


include("db.php");

// Handle Create Expense
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["create_expense"])) {
    $expense_name = $_POST["expense_name"];
    $category_id = intval($_POST["category_id"]);
    $transaction_method = $_POST["transaction_method"];
    $amount = floatval($_POST["amount"]);
    $note = $_POST["note"];

    $stmt = $conn->prepare("INSERT INTO expenses (expense_name, category_id, transaction_method, amount, note) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("sisis", $expense_name, $category_id, $transaction_method, $amount, $note);
    $stmt->execute();
    $stmt->close();
    header("Location: add-expense.php");
    exit();
}

// Handle Edit Expense
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["edit_expense"])) {
    $id = intval($_POST["expense_id"]);
    $expense_name = $_POST["expense_name"];
    $category_id = intval($_POST["category_id"]);
    $transaction_method = $_POST["transaction_method"];
    $amount = floatval($_POST["amount"]);
    $note = $_POST["note"];

    $stmt = $conn->prepare("UPDATE expenses SET expense_name=?, category_id=?, transaction_method=?, amount=?, note=? WHERE expense_id=?");
    $stmt->bind_param("sisssi", $expense_name, $category_id, $transaction_method, $amount, $note, $id);
    $stmt->execute();
    $stmt->close();
    header("Location: add-expense.php");
    exit();
}

// Handle Delete Expense
if (isset($_GET["delete"])) {
    $id = intval($_GET["delete"]);
    $conn->query("DELETE FROM expenses WHERE expense_id=$id");
    header("Location: add-expense.php");
    exit();
}

// Fetch Categories
$categories = $conn->query("SELECT * FROM expense_categories ORDER BY category_name ASC");

// Fetch Expenses
$expenses = $conn->query("
    SELECT e.*, c.category_name 
    FROM expenses e 
    LEFT JOIN expense_categories c ON e.category_id = c.category_id 
    ORDER BY e.expense_id DESC
");
?>

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>Add Expense</title>
        <link rel="stylesheet" href="css/style.css">
        <style>
            
        </style>
    </head>

    <body class="expense-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> Add Expense</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 onclick="document.getElementById('createModal').style.display='block'">✚ Create Expense</button>
                            </div>
                        </div>
                        <!-- Create Modal -->
                        <div id="createModal" class="modal">
                            <div class="modal-content">
                                <h3>Create Expense</h3>
                                <div class="close-btn">
                                    <button type="button" onclick="document.getElementById('createModal').style.display='none'">×</button>
                                </div>
                                <form method="POST">
                                    <input type="hidden" name="create_expense" value="1">
                                    <div class="form-group">
                                        <label>Expense Name</label>
                                        <input type="text" name="expense_name" required>
                                    </div>
                                    <div class="form-group">
                                        <label>Category</label>
                                    <select name="category_id" required>
                    <?php while ($cat = $categories->fetch_assoc()): ?>
                        <option value="<?= $cat['category_id'] ?>"><?= htmlspecialchars($cat['category_name']) ?></option>
                    <?php endwhile; ?>
                </select>
                                    </div>
                                    

                                    <div class="form-group">
                                        <label>Transaction Method</label>
                                    <select name="transaction_method" required>
                    <option value="Cash">Cash</option>
                    <option value="Bank">Bank</option>
                    <option value="Mobile Banking">Mobile Banking</option>
                    <option value="Other">Other</option>
                </select>
                                    </div>

                                    <div class="form-group">
                                        <label>Expense Amount (৳)</label>
                                        <input type="number" name="amount" step="0.01" required>
                                    </div>

                                    <div class="form-group">
                                        <label>Note</label>
                                        <textarea name="note"></textarea>
                                    </div>
                                    <button class="btn submit-btn" type="submit">Save</button>
                                    
                                </form>
                            </div>
                        </div>

                        <!-- Edit Modal -->
                        <div id="editModal" class="modal">
                            <div class="modal-content">
                                <h3>Edit Expense</h3>
                                <div class="edit-close-btn">
                                    <button type="button" onclick="document.getElementById('editModal').style.display='none'">×</button>
                                </div>
                                <form method="POST">
                                    <div class="form-group">
                                        <input type="hidden" name="edit_expense" value="1">
                                        <input type="hidden" name="expense_id" id="editExpenseId">
                                    </div>

                                    <div class="form-group">
                                        <label>Expense Name</label>
                                        <input type="text" name="expense_name" id="editExpenseName" required>
                                    </div>

                                    <div class="form-group">
                                        <label>Category</label>
                                        <select name="category_id" id="editCategoryId" required>
                                    
                                            <?php
                                            $categories2 = $conn->query("SELECT * FROM expense_categories ORDER BY category_name ASC");
                                            while ($cat = $categories2->fetch_assoc()):
                                            ?>
                                                <option value="<?= $cat['category_id'] ?>"><?= htmlspecialchars($cat['category_name']) ?></option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label>Transaction Method</label>
                                        <select name="transaction_method" id="editTransactionMethod" required>
                                            <option value="Cash">Cash</option>
                                            <option value="Bank">Bank</option>
                                            <option value="Mobile Banking">Mobile Banking</option>
                                            <option value="Other">Other</option>
                                        </select>
                                    </div>

                                    <div class="form-group">
                                        <label>Expense Amount (৳)</label>
                                        <input type="number" name="amount" id="editAmount" step="0.01" required>
                                    </div>

                                    <div class="form-group">
                                        <label>Note</label>
                                        <textarea name="note" id="editNote"></textarea>
                                    </div>
                                    <button class="btn submit-btn" type="submit">Save</button>
                                </form>
                            </div>
                        </div>

                        <h3>Expense List</h3>
                        <table>
                            <thead>
                                <tr>
                                    <th>SL</th>
                                    <th>Name</th>
                                    <th>Category</th>
                                    <th>Transaction</th>
                                    <th>Amount (৳)</th>
                                    <th>Date</th>
                                    <th>Note</th>
                                    <th style="width: 18%; text-align: center;">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $sl = 1; while ($e = $expenses->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <?= $sl++ ?>
                                    </td>
                                    <td>
                                        <?= htmlspecialchars($e['expense_name']) ?>
                                    </td>
                                    <td>
                                        <?= htmlspecialchars($e['category_name']) ?>
                                    </td>
                                    <td>
                                        <?= htmlspecialchars($e['transaction_method']) ?>
                                    </td>
                                    <td>
                                        <?= number_format($e['amount'], 2) ?>
                                    </td>
                                    <td>
                                        <?= date('Y-m-d', strtotime($e['created_at'])) ?>
                                    </td>
                                    <td>
                                        <?= htmlspecialchars($e['note']) ?>
                                    </td>
                                    <td class="expense-list-action-btn">
                                        <button class="btn" onclick="openEditModal(this)" data-id="<?= $e['expense_id'] ?>" data-name="<?= htmlspecialchars($e['expense_name'], ENT_QUOTES) ?>" data-category="<?= $e['category_id'] ?>" data-method="<?= $e['transaction_method'] ?>" data-amount="<?= $e['amount'] ?>"
                                            data-note="<?= htmlspecialchars($e['note'], ENT_QUOTES) ?>">Edit</button>
                                        <a class="btn btn-danger" href="?delete=<?= $e['expense_id'] ?>" onclick="return confirm('Delete this expense?')">Delete</a>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </section>
<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 openEditModal(button) {
                        document.getElementById('editExpenseId').value = button.dataset.id;
                        document.getElementById('editExpenseName').value = button.dataset.name;
                        document.getElementById('editCategoryId').value = button.dataset.category;
                        document.getElementById('editTransactionMethod').value = button.dataset.method;
                        document.getElementById('editAmount').value = button.dataset.amount;
                        document.getElementById('editNote').value = button.dataset.note;
                        document.getElementById('editModal').style.display = 'block';
                    }
                </script>

    </body>

    </html>