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


include("db.php");

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

// Handle search filters
$where = " WHERE 1=1 ";
$params = [];
$types = "";

if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
    $from_date = $_GET['from_date'];
    $to_date = $_GET['to_date'];
    $where .= " AND DATE(e.created_at) BETWEEN ? AND ? ";
    $params[] = $from_date;
    $params[] = $to_date;
    $types .= "ss";
}

if (!empty($_GET['category_id'])) {
    $category_id = intval($_GET['category_id']);
    $where .= " AND e.category_id = ? ";
    $params[] = $category_id;
    $types .= "i";
}

// Build query
$sql = "SELECT e.*, c.category_name 
        FROM expenses e 
        LEFT JOIN expense_categories c ON e.category_id = c.category_id 
        $where 
        ORDER BY e.expense_id DESC";

$stmt = $conn->prepare($sql);
if ($params) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Expense Report</title>
    <link rel="stylesheet" href="css/style.css" />
</head>
<body class="expense-rp-page">

     <!-- Sidebar -->
        <!-- 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 Report</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>John Doe</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">

    <!-- Search Filters -->
    <form method="GET" class="filter-box">
        <div class="form-group">
            <label>From Date:</label>
            <input type="date" name="from_date" value="<?= htmlspecialchars($_GET['from_date'] ?? '') ?>">
        </div>

        <div class="form-group">
            <label>To Date:</label>
            <input type="date" name="to_date" value="<?= htmlspecialchars($_GET['to_date'] ?? '') ?>">
        </div>

        <div class="form-group">
            <label>Category:</label>
        <select name="category_id">
            <option value="">All Categories</option>
            <?php while ($cat = $categories->fetch_assoc()): ?>
                <option value="<?= $cat['category_id'] ?>" <?= (isset($_GET['category_id']) && $_GET['category_id']==$cat['category_id'])?'selected':'' ?>>
                    <?= htmlspecialchars($cat['category_name']) ?>
                </option>
            <?php endwhile; ?>
        </select>
        </div>
        <div class="form-group submit-group">
            <button type="submit">🔍︎ Search</button>
        </div>
    </form>

    <!-- Expense Report Table -->
    <table>
        <thead>
            <tr>
                <th>SL</th>
                <th>Expense Name</th>
                <th>Category</th>
                <th>Transaction</th>
                <th>Date</th>
                <th>Note</th>
                <th>Amount (৳)</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
        <?php $sl=1; while($row=$result->fetch_assoc()): ?>
            <tr>
                <td><?= $sl++ ?></td>
                <td><?= htmlspecialchars($row['expense_name']) ?></td>
                <td><?= htmlspecialchars($row['category_name']) ?></td>
                <td><?= htmlspecialchars($row['transaction_method']) ?></td>
                <td><?= date('d-m-Y', strtotime($row['created_at'])) ?></td>
                <td><?= htmlspecialchars($row['note']) ?></td>
                <td><?= number_format($row['amount'],2) ?></td>
                <td>
                    <button class="btn btn-print" onclick='printExpense(<?= json_encode($row, JSON_HEX_APOS|JSON_HEX_QUOT) ?>)'>Print</button>
                </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 printExpense(expense) {
    const printContent = `
    <div class="global-print">
<style>
body{
    margin: 0 !important;
    padding: 0 !important;
}
    /* Global Print css */
.global-print .heading{
    text-align: center;
}
.global-print .print-bg{
    position: relative;
    height: auto !important;
}
.global-print .print-bg img{
    width: 300px;
    position: absolute;
    z-index: -1;
    top: 350px;
    left: 50%;
    transform: translate(-50%, -50%);
    opacity: .2;
}
.global-print .heading p{
    margin: 0;
    margin-bottom: 10px;
}
</style>



<?php
    include("global/global-print-heading.php");
?>
        <main class="print-body-content">
        <div style="font-family:Arial,sans-serif;">
            <h2 style="text-align:center;">Expense Report</h2>
            <p style="text-align:center;"><strong>Date:</strong> ${new Date(expense.created_at).toISOString().split('T')[0]}</p>
            <style>
                body{font-family:sans-serif;padding:20px}
                table{width:100%;border-collapse:collapse;margin-top:12px}
                td,th{border:1px solid #000;padding:8px;text-align:left}
            </style>
            <table>
                <tr>
                    <th>Expense Name:</th>
                    <th>Category:</th>
                    <th>Transaction Method:</th>
                    <th>Amount:</th>
                </tr>
                <tr>
                    <td> ${expense.expense_name}</td>
                    <td> ${expense.category_name}</td>
                    <td> ${expense.transaction_method}</td>
                    <td> ৳ ${parseFloat(expense.amount).toFixed(2)}</td>
                </tr>
            </table>
            <p><strong>Note:</strong> ${expense.note ?? ''}</p>
        </div>
    </div>
        </main>
     <?php
    include("global/global-print-footer.php");
?>
    `;
    const win = window.open("", "_blank", "height=700,width=900");
    win.document.write(printContent);
    win.document.close();
    win.focus();
    win.print();
}
</script>

</body>
</html>
