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

// Handle create payment by invoice (POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'pay_due') {
    $invoice_no = trim($_POST['invoice_no'] ?? '');
    $supplier_id = intval($_POST['supplier_id'] ?? 0);
    $purchase_id = intval($_POST['purchase_id'] ?? 0);
    $payment_date = $_POST['payment_date'] ?: date('Y-m-d');
    $amount = floatval($_POST['amount'] ?? 0);
    $method = $_POST['method'] ?? 'Cash';
    $note = trim($_POST['note'] ?? '');

    // If invoice_no provided but purchase_id not, find purchase
    if ($purchase_id <= 0 && $invoice_no !== '') {
        $stmt = $conn->prepare("SELECT purchase_id, supplier_id FROM purchases WHERE invoice_no = ? LIMIT 1");
        $stmt->bind_param("s", $invoice_no);
        $stmt->execute();
        $res = $stmt->get_result();
        $p = $res->fetch_assoc();
        $stmt->close();
        if ($p) {
            $purchase_id = (int)$p['purchase_id'];
            $supplier_id = (int)$p['supplier_id'];
        }
    }

    if ($supplier_id > 0 && $purchase_id > 0 && $amount > 0) {
        $conn->begin_transaction();
        try {
            $ins = $conn->prepare("INSERT INTO due_payments (purchase_id, supplier_id, invoice_no, payment_date, amount, method, note) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $ins->bind_param("iissdss", $purchase_id, $supplier_id, $invoice_no, $payment_date, $amount, $method, $note);
            $ins->execute();
            $ins->close();

            // update purchase paid/due
            $upd = $conn->prepare("UPDATE purchases SET paid = paid + ?, due = due - ? WHERE purchase_id = ?");
            $upd->bind_param("ddi", $amount, $amount, $purchase_id);
            $upd->execute();
            $upd->close();

            $conn->commit();
            header("Location: due-payments.php?added=1");
            exit();
        } catch (Exception $ex) {
            $conn->rollback();
            $error = "Payment failed: " . $ex->getMessage();
        }
    } else {
        $error = "Invalid payment data (check invoice or amounts).";
    }
}

// Handle delete payment (GET)
if (isset($_GET['delete'])) {
    $del_id = intval($_GET['delete']);
    if ($del_id > 0) {
        $conn->begin_transaction();
        try {
            $q = $conn->prepare("SELECT purchase_id, amount FROM due_payments WHERE due_payment_id = ?");
            $q->bind_param("i", $del_id);
            $q->execute();
            $res = $q->get_result();
            $row = $res->fetch_assoc();
            $q->close();

            if ($row) {
                $purchase_id = (int)$row['purchase_id'];
                $amount = (float)$row['amount'];

                $d = $conn->prepare("DELETE FROM due_payments WHERE due_payment_id = ?");
                $d->bind_param("i", $del_id);
                $d->execute();
                $d->close();

                $u = $conn->prepare("UPDATE purchases SET paid = paid - ?, due = due + ? WHERE purchase_id = ?");
                $u->bind_param("ddi", $amount, $amount, $purchase_id);
                $u->execute();
                $u->close();

                $conn->commit();
            } else {
                $conn->rollback();
            }
        } catch (Exception $ex) {
            $conn->rollback();
            die("Delete failed: " . $ex->getMessage());
        }
    }
    header("Location: due-payments.php");
    exit();
}

// Filters
$filterSupplier = isset($_GET['supplier']) ? intval($_GET['supplier']) : 0;
$filterFrom = isset($_GET['from_date']) ? $_GET['from_date'] : '';
$filterTo = isset($_GET['to_date']) ? $_GET['to_date'] : '';

// suppliers list
$supRes = $conn->query("SELECT supplier_id, supplier_name FROM suppliers ORDER BY supplier_name ASC");

// pending invoices grouped by supplier (due > 0)
$pending = [];
$pr = $conn->query("SELECT purchase_id, invoice_no, supplier_id, purchase_date, total, paid, due FROM purchases WHERE due > 0 ORDER BY purchase_date ASC");
while ($r = $pr->fetch_assoc()) {
    $pending[$r['supplier_id']][] = $r;
}

// fetch payments
$sql = "SELECT dp.*, p.purchase_date, p.invoice_no, p.total AS purchase_total, s.supplier_name
        FROM due_payments dp
        LEFT JOIN purchases p ON dp.purchase_id = p.purchase_id
        LEFT JOIN suppliers s ON dp.supplier_id = s.supplier_id
        WHERE 1";
$params = []; $types = "";
if ($filterSupplier > 0) { $sql .= " AND dp.supplier_id = ?"; $types .= "i"; $params[] = $filterSupplier; }
if ($filterFrom) { $sql .= " AND dp.payment_date >= ?"; $types .= "s"; $params[] = $filterFrom; }
if ($filterTo)   { $sql .= " AND dp.payment_date <= ?"; $types .= "s"; $params[] = $filterTo; }
$sql .= " ORDER BY dp.due_payment_id DESC";

$stmt = $conn->prepare($sql);
if (!empty($params)) $stmt->bind_param($types, ...$params);
$stmt->execute();
$payments = $stmt->get_result();

// make JSON for JS
$pending_json = json_encode($pending, JSON_HEX_APOS|JSON_HEX_QUOT);




?>




<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <title>Due Payments by Invoice</title>
        <link rel="stylesheet" href="css/style.css">
        <style>
            /* styles similar to your previous pages */


         

            .modal {
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                justify-content: center;
                align-items: center;
                z-index: 1000
            }

            .modal-content {
                background: #fff;
                padding: 20px;
                border-radius: 10px;
                width: 520px;
                max-width: 95%
            }

            .close {
                float: right;
                cursor: pointer;
                font-weight: bold
            }

            .small {
                padding: 6px 8px;
                border-radius: 6px
            }

            .input-inline {
                display: flex;
                gap: 8px;
                align-items: center
            }
        </style>
    </head>

    <body class="due-payments-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> Due Payments</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($error)): ?>
                <div style="padding:10px;background:#fee;border:1px solid #fca;border-radius:8px;margin-bottom:12px;color:#900">
                    <?php echo htmlspecialchars($error); ?>
                </div>
                <?php endif; ?>
                <?php if (isset($_GET['added'])): ?>
                <div style="padding:10px;background:#ecfeff;border:1px solid #a5f3fc;color:#065f46;border-radius:8px;margin-bottom:12px">Payment saved successfully.</div>
                <?php endif; ?>

                <div class="">
                    <div class="filter-group">
                        <div class="due-btn">
                            <button class="btn" onclick="openDueModal()">✚ Make Due Payment</button>
                        </div>
                        <form method="get" id="filterForm" class="filter-box">
                            <div class="form-group">
                                <select name="supplier" id="filterSupplier">
                                    <option value="0">-- All Suppliers --</option>
                                    <?php while ($s = $supRes->fetch_assoc()): ?>
                                    <option value="<?php echo $s['supplier_id']; ?>" <?php if ($filterSupplier == $s['supplier_id']) echo 'selected'; ?>>
                                        <?php echo htmlspecialchars($s['supplier_name']); ?>
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>From:</label>
                                <input type="date" name="from_date" value="<?php echo htmlspecialchars($filterFrom); ?>">
                            </div>
                            <div class="form-group">
                                <label>To:</label>
                                <input type="date" name="to_date" value="<?php echo htmlspecialchars($filterTo); ?>">
                            </div>
                            <div class="form-group">
                                <button type="submit" class="btn">🔎︎ Search</button>
                            </div>
                        </form>
                        
                    </div> 
                </div>

                <table>
                    <thead>
                        <tr>
                            <th>SL</th>
                            <th>Invoice</th>
                            <th>Supplier</th>
                            <th>Payment Date</th>
                            <th>Amount (৳)</th>
                            <th>Method</th>
                            <th>Note</th>
                            <th style="text-align:center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $sl=1; if ($payments && $payments->num_rows>0): while ($p = $payments->fetch_assoc()): ?>
                        <tr>
                            <td>
                                <?php echo $sl++; ?>
                            </td>
                            <td>
                                <?php echo htmlspecialchars($p['invoice_no']); ?>
                            </td>
                            <td>
                                <?php echo htmlspecialchars($p['supplier_name']); ?>
                            </td>
                            <td>
                                <?php echo htmlspecialchars($p['payment_date']); ?>
                            </td>
                            <td>
                                <?php echo number_format($p['amount'],2); ?>
                            </td>
                            <td>
                                <?php echo htmlspecialchars($p['method']); ?>
                            </td>
                            <td>
                                <?php echo htmlspecialchars($p['note']); ?>
                            </td>
                            <td class="due-action-btn">
                                <a class="btn btn-danger" href="?delete=<?php echo $p['due_payment_id']; ?>" onclick="return confirm('Delete this payment?')">Delete</a>
                                <button class="btn btn-print" onclick="window.open('due_payment_print.php?id=<?php echo $p['due_payment_id']; ?>','_blank','width=900,height=700')">Print</button>
                            </td>
                        </tr>
                        <?php endwhile; else: ?>
                        <tr>
                            <td colspan="8" style="text-align:center;color:#6b7280;">No payments found</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <!-- Modal -->
        <div class="modal" id="dueModal">
            <div class="modal-content">
                <span class="close" onclick="closeDueModal()">&times;</span>
                <h3>Make Due Payment</h3>

                <form method="post" id="dueForm">
                    <input type="hidden" name="action" value="pay_due">

                    <!-- Option 1: Enter invoice number directly -->
                    <div clsss="invoice-lookup">
                        <label>Enter Invoice No (6 digits)</label>
                        <div class="input-inline ">
                            <input type="text" id="invoiceInput" name="invoice_no" placeholder="e.g. 000123" maxlength="6">
                            <button type="button" class="btn" onclick="lookupInvoice()">Search</button>
                        </div>
                        <span id="invoiceLookupInfo" style="margin-left:8px;color:red;"></span>
                    </div>

                    <hr>

                    <!-- Or choose supplier then invoice -->
                    <div class="form-group">
                        <label>Or choose Supplier</label>
                        <select id="supplierSelect" name="supplier_id">
          <option value="">-- Select Supplier --</option>
          <?php
          // re-fetch suppliers
          $s2 = $conn->query("SELECT supplier_id, supplier_name FROM suppliers ORDER BY supplier_name ASC");
          while ($row = $s2->fetch_assoc()):
          ?>
          <option value="<?php echo $row['supplier_id']; ?>"><?php echo htmlspecialchars($row['supplier_name']); ?></option>
          <?php endwhile; ?>
        </select>
                    </div>

                    <div class="form-group">
                        <label>Invoice (only unpaid invoices)</label>
                        <select id="invoiceSelect" name="purchase_id">
          <option value="">-- Select Invoice --</option>
        </select>
                    </div>

                    <div style="display:flex;gap:8px;">
                        <div style="flex:1;">
                            <label>Payment Date</label>
                            <input type="date" name="payment_date" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                        <div style="width:160px;">
                            <label>Amount (৳)</label>
                            <input type="number" name="amount" id="payAmount" step="0.01" min="0" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Method</label>
                        <select name="method">
          <option>Cash</option>
          <option>Card</option>
          <option>Bank</option>
          <option>Mobile Banking</option>
        </select>
                    </div>

                    <div class="form-group">
                        <label>Note</label>
                        <textarea name="note" rows="2"></textarea>
                    </div>

                    <div style="margin-top:10px;display:flex;gap:8px;">
                        <button type="submit" class="btn submit-btn">Submit Payment</button>
                    </div>
                </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>
            // pending invoices grouped by supplier (from PHP)
            const pendingBySupplier = <?php echo $pending_json ?: '{}' ?>;

            // helper: populate invoices when supplier selected
            document.getElementById('supplierSelect').addEventListener('change', function() {
                const sid = this.value;
                const inv = document.getElementById('invoiceSelect');
                inv.innerHTML = '<option value="">-- Select Invoice --</option>';
                if (!sid) return;
                const arr = pendingBySupplier[sid] || [];
                arr.forEach(row => {
                    const opt = document.createElement('option');
                    opt.value = row.purchase_id;
                    opt.textContent = `${row.invoice_no} — Date: ${row.purchase_date} — Due: ৳${parseFloat(row.due).toFixed(2)}`;
                    inv.appendChild(opt);
                });
            });


            // when invoice selected (from select) populate amount
            document.getElementById('invoiceSelect').addEventListener('change', function() {
                const pid = this.value;
                if (!pid) {
                    document.getElementById('payAmount').value = '';
                    return;
                }
                // find in pending
                const sid = document.getElementById('supplierSelect').value;
                const arr = pendingBySupplier[sid] || [];
                const found = arr.find(x => String(x.purchase_id) === String(pid));
                if (found) {
                    document.getElementById('payAmount').value = parseFloat(found.due).toFixed(2);
                } else {
                    document.getElementById('payAmount').value = '';
                }
            });

            // open / close modal
            function openDueModal() {
                document.getElementById('dueModal').style.display = 'flex';
            }

            function closeDueModal() {
                document.getElementById('dueModal').style.display = 'none';
                document.getElementById('dueForm').reset();
                document.getElementById('invoiceLookupInfo').textContent = '';
                document.getElementById('invoiceSelect').innerHTML = '<option value="">-- Select Invoice --</option>';
            }

            // lookup invoice by number (AJAX)
            function lookupInvoice() {
                const inv = document.getElementById('invoiceInput').value.trim();
                const info = document.getElementById('invoiceLookupInfo');
                if (!inv) {
                    info.textContent = 'Enter invoice no.';
                    return;
                }
                info.textContent = 'Searching...';
                fetch('purchase_lookup.php?invoice_no=' + encodeURIComponent(inv))
                    .then(r => r.json())
                    .then(data => {
                        if (!data.ok) {
                            info.textContent = data.msg || 'Not found';
                            // clear possible fields
                            document.getElementById('supplierSelect').value = '';
                            document.getElementById('invoiceSelect').innerHTML = '<option value="">-- Select Invoice --</option>';
                            document.getElementById('payAmount').value = '';
                            return;
                        }
                        const p = data.purchase;
                        info.textContent = `Invoice ${p.invoice_no} — Due: ৳${parseFloat(p.due).toFixed(2)} — Supplier: ${p.supplier_name}`;
                        // set supplier select to this supplier and populate invoiceSelect with single option selected
                        document.getElementById('supplierSelect').value = p.supplier_id;
                        const invSel = document.getElementById('invoiceSelect');
                        invSel.innerHTML = `<option value="${p.purchase_id}" selected>#${p.invoice_id || p.purchase_id} — ${p.invoice_no}</option>`;
                        document.getElementById('payAmount').value = parseFloat(p.due).toFixed(2);
                    })
                    .catch(err => {
                        console.error(err);
                        info.textContent = 'Lookup failed';
                    });
            }

            // clicking outside modal closes it
            window.addEventListener('click', function(e) {
                if (e.target.classList && e.target.classList.contains('modal')) {
                    e.target.style.display = 'none';
                }
            });
        </script>



    </body>

</html>