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

require_once "db.php";

// Search/filter
$searchSupplier = isset($_GET['supplier']) ? intval($_GET['supplier']) : 0;
$searchFromDate = isset($_GET['from_date']) ? $_GET['from_date'] : '';
$searchToDate   = isset($_GET['to_date']) ? $_GET['to_date'] : '';

// Fetch suppliers for filter dropdown
$supQuery = "SELECT supplier_id, supplier_name FROM suppliers ORDER BY supplier_name ASC";
$suppliers = $conn->query($supQuery);

// Fetch purchases
$sql = "SELECT p.purchase_id, p.invoice_no, p.purchase_date, p.total, p.paid, p.due, s.supplier_name
        FROM purchases p
        LEFT JOIN suppliers s ON p.supplier_id = s.supplier_id
        WHERE 1";
$params = []; $types = "";
if ($searchSupplier > 0) { $sql .= " AND p.supplier_id=?"; $types.="i"; $params[]=$searchSupplier;}
if ($searchFromDate) { $sql .= " AND p.purchase_date>=?"; $types.="s"; $params[]=$searchFromDate;}
if ($searchToDate)   { $sql .= " AND p.purchase_date<=?"; $types.="s"; $params[]=$searchToDate;}
$sql .= " ORDER BY p.purchase_id DESC";

$stmt = $conn->prepare($sql);
if (!empty($params)) { $stmt->bind_param($types,...$params);}
$stmt->execute();
$purchases = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Purchase List</title>
        <link rel="stylesheet" href="css/style.css" />
        <style>
            .form-row {
                display: flex;
                gap: 12px;
                flex-wrap: wrap;
                margin-bottom: 12px
            }
           
        </style>
    </head>

    <body class="purchase-list-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> Profit Loss 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>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">
                <form method="get" class="filter-box">
                    <div class="form-group">
                            <label>Supplier</label>
                            <select name="supplier">
                                <option value="0">-- All Suppliers --</option>
                                <?php while($s = $suppliers->fetch_assoc()): ?>
                                <option value="<?php echo $s['supplier_id'];?>" <?php if($searchSupplier==$s['supplier_id']) echo "selected";?>><?php echo htmlspecialchars($s['supplier_name']);?></option>
                                <?php endwhile;?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>From Date</label>
                            <input type="date" name="from_date" value="<?php echo htmlspecialchars($searchFromDate);?>">
                        </div>
                        <div class="form-group">
                            <label>To Date</label>
                            <input type="date" name="to_date" value="<?php echo htmlspecialchars($searchToDate);?>">
                        </div>
                        <div class="form-group pcs-list-submit-btn">
                            <label>&nbsp;</label>
                            <button type="submit" class="btn">🔎︎ Search</button>
                        </div>
                        <div class="form-group pcs-list-reset-btn">
                            <a href="purchase-list.php"><button type="button" class="filter-reset-btn"> ↻ Reset</button></a>
                        </div>
                </form>

                <table class="purchase-list-table">
                    <thead>
                        <tr>
                            <th>Supplier</th>
                            <th>Date</th>
                            <th>Invoice</th>
                            <th>Products</th>
                            <th>Total (৳)</th>
                            <th>Paid (৳)</th>
                            <th>Due (৳)</th>
                            <th style="text-align: center;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if($purchases->num_rows>0): ?>
                        <?php while($p = $purchases->fetch_assoc()): 
                            // fetch items
                            $stmtItems = $conn->prepare("SELECT product, size, rate, qty, subtotal FROM purchase_items WHERE purchase_id=?");
                            $stmtItems->bind_param("i",$p['purchase_id']);
                            $stmtItems->execute();
                            $itemsResult = $stmtItems->get_result();
                        ?>
                        <tr>
                            <td>
                                <?php echo htmlspecialchars($p['supplier_name']);?>
                            </td>
                            <td>
                                <?php echo htmlspecialchars($p['purchase_date']);?>
                            </td>
                            <td>
                                <?php echo htmlspecialchars($p['invoice_no']);?>
                            </td>
                            <td>
                                <?php while($item = $itemsResult->fetch_assoc()): ?>
                                <?php echo htmlspecialchars($item['product']).' ('.htmlspecialchars($item['size']).') - '.$item['qty'].' x '.$item['rate'].'<br>';?>
                                <?php endwhile;?>
                            </td>
                            <td>
                                <?php echo number_format($p['total'],2);?>
                            </td>
                            <td>
                                <?php echo number_format($p['paid'],2);?>
                            </td>
                            <td>
                                <?php echo number_format($p['due'],2);?>
                            </td>
                            <td class="action-btn">
                                <button class="btn" onclick="openEditModal(<?php echo $p['purchase_id'];?>)">Edit</button>
                                <a href="purchase_delete.php?id=<?php echo $p['purchase_id'];?>" class="btn btn-danger" onclick="return confirm('Delete this purchase?')">Delete</a>
                                <button class="btn btn-print" onclick="printInvoice(<?php echo $p['purchase_id'];?>)">Print</button>
                            </td>
                        </tr>
                        <?php endwhile;?>
                        <?php else: ?>
                        <tr>
                            <td colspan="7" style="text-align:center;color:#6b7280;">No purchases found</td>
                        </tr>
                        <?php endif;?>
                    </tbody>
                </table>
            </div>
        </section>

        <!-- Edit Modal -->
        <div class="modal" id="editModal">
            <div class="modal-content" id="editModalContent">
                <button class="close-btn" onclick="closeEditModal()">X</button>
                <div id="editFormContainer">Loading...</div>
            </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>
            // open edit modal
            function openEditModal(purchaseId) {
                document.getElementById('editModal').style.display = "flex";
                document.getElementById('editFormContainer').innerHTML = 'Loading...';
                fetch('purchase_edit_popup.php?id=' + purchaseId)
                    .then(res => res.text())
                    .then(html => {
                        document.getElementById('editFormContainer').innerHTML = html;
                    });
            }

            function closeEditModal() {
                document.getElementById('editModal').style.display = "none";
            }

            // Print
            function printInvoice(purchaseId) {
                window.open('purchase_print.php?id=' + purchaseId, '_blank', 'width=900,height=700');
            }
        </script>
    </body>
</html>