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

require_once "db.php"; // $conn is mysqli

// ----------------------
// Generate Unique Invoice No
// ----------------------
function generateInvoiceNo($conn) {
    do {
        $invoice = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT); // 6 digit padded
        $check = $conn->prepare("SELECT invoice_no FROM purchases WHERE invoice_no=?");
        $check->bind_param("s", $invoice);
        $check->execute();
        $check->store_result();
    } while ($check->num_rows > 0);
    $check->close();
    return $invoice;
}

// ----------------------
// Handle form submission
// ----------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $supplier_id   = isset($_POST['supplier']) ? intval($_POST['supplier']) : 0;
    $purchase_date = isset($_POST['purchase_date']) ? $_POST['purchase_date'] : '';
    $paid_input    = isset($_POST['paid']) ? (float)$_POST['paid'] : 0.0;

    if ($supplier_id <= 0 || empty($purchase_date)) {
        echo "<script>alert('Please select supplier and date.');</script>";
    } else {
        $products = $_POST['product'] ?? [];
        $sizes    = $_POST['size'] ?? [];
        $rates    = $_POST['rate'] ?? [];
        $qtys     = $_POST['qty'] ?? [];

        $total = 0.0;
        $subtotals = [];
        $count = count($products);

        for ($i = 0; $i < $count; $i++) {
            $r = isset($rates[$i]) ? (float)$rates[$i] : 0.0;
            $q = isset($qtys[$i]) ? intval($qtys[$i]) : 0;
            $st = $r * $q;
            $subtotals[$i] = $st;
            $total += $st;
        }

        $paid = $paid_input;
        $due  = $total - $paid;
        if ($due < 0) $due = 0.0;

        // Generate invoice
        $invoice_no = generateInvoiceNo($conn);

        // Insert into purchases table
        $stmt = $conn->prepare("INSERT INTO purchases (invoice_no, supplier_id, purchase_date, total, paid, due) VALUES (?, ?, ?, ?, ?, ?)");
        if (!$stmt) {
            die("Prepare failed (purchases): " . $conn->error);
        }
        $stmt->bind_param("sissdd", $invoice_no, $supplier_id, $purchase_date, $total, $paid, $due);
        if (!$stmt->execute()) {
            $stmt->close();
            die("Execute failed (purchases): " . $conn->error);
        }
        $purchase_id = $stmt->insert_id;
        $stmt->close();

        // Insert purchase items
        if ($count > 0) {
            $stmtItem = $conn->prepare("INSERT INTO purchase_items (purchase_id, product, size, rate, qty, subtotal) VALUES (?, ?, ?, ?, ?, ?)");
            if (!$stmtItem) {
                $conn->query("DELETE FROM purchases WHERE purchase_id=" . (int)$purchase_id);
                die("Prepare failed (items): " . $conn->error);
            }

            for ($i = 0; $i < $count; $i++) {
                $prod = trim($products[$i]);
                if ($prod === '') continue;
                $size = $sizes[$i] ?? '';
                $rate = (float)($rates[$i] ?? 0.0);
                $qty  = (int)($qtys[$i] ?? 0);
                $subtotal = $subtotals[$i] ?? ($rate * $qty);

                $stmtItem->bind_param("issdid", $purchase_id, $prod, $size, $rate, $qty, $subtotal);
                if (!$stmtItem->execute()) {
                    $stmtItem->close();
                    $conn->query("DELETE FROM purchase_items WHERE purchase_id=" . (int)$purchase_id);
                    $conn->query("DELETE FROM purchases WHERE purchase_id=" . (int)$purchase_id);
                    die("Execute failed (items): " . $conn->error);
                }
            }
            $stmtItem->close();
        }

        header("Location: purchase.php?added=1");
        exit();
    }
}

// ----------------------
// Fetch suppliers
// ----------------------
$suppliers = $conn->query("SELECT supplier_id, supplier_name AS name FROM suppliers ORDER BY supplier_name ASC");
if (!$suppliers) die("Failed to fetch suppliers: " . $conn->error);

// ----------------------
// Fetch recent 5 purchases
// ----------------------
$recentSql = "
SELECT p.invoice_no, p.purchase_id, p.purchase_date, p.total, p.paid, p.due,
       s.supplier_name AS supplier_name
FROM purchases p
LEFT JOIN suppliers s ON p.supplier_id = s.supplier_id
ORDER BY p.purchase_id DESC
LIMIT 5";
$recent = $conn->query($recentSql);
if (!$recent) die("Failed to fetch recent purchases: " . $conn->error);
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>Purchase</title>
    <link rel="stylesheet" href="css/style.css">
</head>

<body>
        <!-- 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> Purchase List</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">

                <?php if (isset($_GET['added'])): ?>
                <div class="notice">Purchase saved successfully.</div>
                <?php endif; ?>

                <form method="post" id="purchaseForm">
                    <div class="form-row">
                        <div class="form-group">
                            <label>Supplier</label>
                            <select name="supplier" required>
        <option value="">-- Select Supplier --</option>
        <?php while ($s = $suppliers->fetch_assoc()): ?>
          <option value="<?php echo $s['supplier_id']; ?>"><?php echo htmlspecialchars($s['name']); ?></option>
        <?php endwhile; ?>
      </select>
                        </div>
                        <div class="form-group">
                            <label>Purchase Date</label>
                            <input type="date" name="purchase_date" required>
                        </div>
                    </div>

                    <table>
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th>Size</th>
                                <th>Rate</th>
                                <th>Qty</th>
                                <th>Subtotal</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="productRows">
                            <tr>
                                <td><input type="text" name="product[]" required></td>
                                <td><input type="text" name="size[]"></td>
                                <td><input type="number" name="rate[]" class="rate" step="0.01" min="0" value="0"></td>
                                <td><input type="number" name="qty[]" class="qty" min="0" value="0"></td>
                                <td><input type="text" name="subtotal[]" class="subtotal" readonly value="0.00"></td>
                                <td><button class="btn-danger" type="button" onclick="removeRow(this)">Remove</button></td>
                            </tr>
                        </tbody>
                    </table>

                    <div class="pcs-add-btn">
                        <button class="btn" type="button" onclick="addRow()">✚ Add Product</button>
                    </div>

                    <div class="summary">
                        <div>Total: ৳ <input type="text" id="total" name="total" readonly></div>
                        <div>Paid: ৳ <input type="number" id="paid" name="paid" value="0" min="0" step="0.01"></div>
                        <div>Due: ৳ <input type="text" id="due" name="due" readonly></div>
                    </div>

                    <div class="pcs-submit-btn">
                        <button class="btn" type="submit">Submit Purchase</button>
                    </div>
                </form>

                <div class="recent-box">
                    <h3>Recent 5 Purchases</h3>
                    <table>
                        <thead>
                            <tr>
                                <th>Invoice</th>
                                <th>Supplier</th>
                                <th>Date</th>
                                <th>Total</th>
                                <th>Paid</th>
                                <th>Due</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($recent->num_rows > 0): while ($r = $recent->fetch_assoc()): ?>
                            <tr>
                                <td>
                                    <?php echo htmlspecialchars($r['invoice_no']); ?>
                                </td>
                                <td>
                                    <?php echo htmlspecialchars($r['supplier_name']); ?>
                                </td>
                                <td>
                                    <?php echo htmlspecialchars($r['purchase_date']); ?>
                                </td>
                                <td>
                                    <?php echo number_format($r['total'],2); ?>
                                </td>
                                <td>
                                    <?php echo number_format($r['paid'],2); ?>
                                </td>
                                <td>
                                    <?php echo number_format($r['due'],2); ?>
                                </td>
                            </tr>
                            <?php endwhile; else: ?>
                            <tr>
                                <td colspan="6">No recent purchases</td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

            </div>
        </section>

        
    </main>
    <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>
            document.getElementById('productRows').addEventListener('input', function(e) {
                if (e.target.classList.contains('rate') || e.target.classList.contains('qty')) calculateTotals();
            });
            document.getElementById('paid').addEventListener('input', calculateTotals);

            function calculateTotals() {
                let total = 0;
                document.querySelectorAll('#productRows tr').forEach(row => {
                    let rate = parseFloat(row.querySelector('.rate').value) || 0;
                    let qty = parseInt(row.querySelector('.qty').value) || 0;
                    let sub = rate * qty;
                    row.querySelector('.subtotal').value = sub.toFixed(2);
                    total += sub;
                });
                document.getElementById('total').value = total.toFixed(2);
                let paid = parseFloat(document.getElementById('paid').value) || 0;
                let due = total - paid;
                if (due < 0) due = 0;
                document.getElementById('due').value = due.toFixed(2);
            }

            function addRow() {
                let tr = document.createElement('tr');
                tr.innerHTML = `<td><input type="text" name="product[]" required></td>
  <td><input type="text" name="size[]"></td>
  <td><input type="number" name="rate[]" class="rate" step="0.01" min="0" value="0"></td>
  <td><input type="number" name="qty[]" class="qty" min="0" value="0"></td>
  <td><input type="text" name="subtotal[]" class="subtotal" readonly value="0.00"></td>
  <td><button class="btn-danger" type="button" onclick="removeRow(this)">Remove</button></td>`;
                document.getElementById('productRows').appendChild(tr);
            }

            function removeRow(btn) {
                btn.closest('tr').remove();
                calculateTotals();
            }
            calculateTotals();
        </script>
        <script>
// Limit native select dropdown to max 10 visible options by toggling the `size` attribute.
// Works by expanding the select on focus/click and restoring on blur/change/escape.

(function() {
  const MAX_VISIBLE = 10;

  function openSelect(e) {
    const sel = e.currentTarget;
    // only expand if there are more than MAX_VISIBLE options
    if (sel.options.length > MAX_VISIBLE) {
      // Save original size (usually 0/1)
      sel.dataset.origSize = sel.size || 1;
      sel.size = MAX_VISIBLE;
      // optional: add a class for styling when expanded
      sel.classList.add('select-expanded');
    }
  }

  function closeSelect(e) {
    const sel = e.currentTarget;
    if (sel.dataset.origSize !== undefined) {
      sel.size = sel.dataset.origSize;
      delete sel.dataset.origSize;
      sel.classList.remove('select-expanded');
    } else {
      // ensure reset to 1 as fallback
      sel.size = 1;
      sel.classList.remove('select-expanded');
    }
  }

  function onKey(e) {
    // close on Escape
    if (e.key === 'Escape') {
      closeSelect({ currentTarget: e.currentTarget });
      e.currentTarget.blur();
    }
  }

  // Apply to all selects (you can add a selector if you don't want all selects affected)
  document.addEventListener('DOMContentLoaded', function() {
    const selects = document.querySelectorAll('select');

    selects.forEach(sel => {
      // Expand on focus or click (some browsers need click to open properly)
      sel.addEventListener('focus', openSelect);
      sel.addEventListener('click', openSelect);

      // Close on blur, change, or when user presses Escape
      sel.addEventListener('blur', closeSelect);
      sel.addEventListener('change', closeSelect);
      sel.addEventListener('keydown', onKey);

      // Also ensure it resets if the page loses visibility (optional)
      document.addEventListener('visibilitychange', () => {
        if (document.visibilityState === 'hidden') closeSelect({ currentTarget: sel });
      });
    });
  });
})();
</script>

<!-- Optional minimal CSS to make the expanded select nicer -->
<style>
/* Ensure expanded select shows scrollbar when needed */
select.select-expanded {
  overflow-y: auto;    /* most browsers will show scroll when needed */
}
</style>

</body>

</html>