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

require_once "db.php";

// --- Handle POST: Add Collection ---
if($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action']) && $_POST['action']==='collect_due'){
    $sale_id = intval($_POST['sale_id'] ?? 0);
    $collected_amount = floatval($_POST['collected_amount'] ?? 0);
    $collection_date = $_POST['collection_date'] ?: date('Y-m-d');
    $note = trim($_POST['note'] ?? '');

    if($sale_id>0 && $collected_amount>0){
        $conn->begin_transaction();
        try{
            $ins = $conn->prepare("INSERT INTO due_collection (sale_id, collected_amount, collection_date, note) VALUES (?,?,?,?)");
            $ins->bind_param("idss", $sale_id, $collected_amount, $collection_date, $note);
            if(!$ins) die("Prepare failed: ".$conn->error);
            $ins->execute();
            $ins->close();

            // update sale due
            $upd = $conn->prepare("UPDATE sales SET paid = paid + ?, due = due - ? WHERE sale_id = ?");
            $upd->bind_param("ddi", $collected_amount, $collected_amount, $sale_id);
            if(!$upd) die("Prepare failed: ".$conn->error);
            $upd->execute();
            $upd->close();

            $conn->commit();
            header("Location: due-collection.php?added=1");
            exit();
        }catch(Exception $ex){
            $conn->rollback();
            $error = "Collection failed: ".$ex->getMessage();
        }
    }else{
        $error = "Invalid data (check sale and amount).";
    }
}

// --- Handle GET: Delete Collection ---
if(isset($_GET['delete'])){
    $del_id = intval($_GET['delete']);
    if($del_id>0){
        $conn->begin_transaction();
        try{
            $q = $conn->prepare("SELECT sale_id, collected_amount FROM due_collection WHERE collection_id=?");
            $q->bind_param("i",$del_id);
            $q->execute();
            $res = $q->get_result();
            $row = $res->fetch_assoc();
            $q->close();

            if($row){
                $sale_id = (int)$row['sale_id'];
                $collected = (float)$row['collected_amount'];

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

                $u = $conn->prepare("UPDATE sales SET paid = paid - ?, due = due + ? WHERE sale_id=?");
                $u->bind_param("ddi",$collected,$collected,$sale_id);
                $u->execute();
                $u->close();

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

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

// --- Customers list ---
$custRes = $conn->query("SELECT customer_id, customer_name FROM customers ORDER BY customer_name ASC");

// --- Fetch collections with filter ---
$sql = "SELECT dc.*, s.sale_date, s.invoice_no, s.total AS sale_total, cu.customer_name
        FROM due_collection dc
        LEFT JOIN sales s ON dc.sale_id = s.sale_id
        LEFT JOIN customers cu ON s.customer_id = cu.customer_id
        WHERE 1";
$params=[]; $types="";
if($filterCustomer>0){ $sql.=" AND cu.customer_id=?"; $types.="i"; $params[]=$filterCustomer; }
if($filterFrom){ $sql.=" AND dc.collection_date>=?"; $types.="s"; $params[]=$filterFrom; }
if($filterTo){ $sql.=" AND dc.collection_date<=?"; $types.="s"; $params[]=$filterTo; }
$sql.=" ORDER BY dc.collection_id DESC";

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

// --- Pending sales grouped by customer ---
$pending=[];
$pr = $conn->query("SELECT sale_id, invoice_no, customer_id, sale_date, total, paid, due FROM sales WHERE due>0 ORDER BY sale_date ASC");
while($r=$pr->fetch_assoc()){
    $pending[$r['customer_id']][]=$r;
}
$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 Collection</title>
    <link rel="stylesheet" href="css/style.css">
    <style>
        

        .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
        }

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

<body class="due-collection-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 Collections</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">Collection added successfully.</div>
            <?php endif; ?>

            <div class="filter-group">
                <div class="due-btn">
                    <button class="btn" onclick="openModal()">+ Collect Due</button>
                </div>
                <form method="get"  class="filter-box">
                    <div class="form-group">
                        <select name="customer">
                            <option value="0">-- All Customers --</option>
                            <?php while($c=$custRes->fetch_assoc()): ?>
                            <option value="<?php echo $c['customer_id']; ?>" <?php if($filterCustomer==$c['customer_id']) echo 'selected'; ?>><?php echo htmlspecialchars($c['customer_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>

            <table>
                <thead>
                    <tr>
                        <th>SL</th>
                        <th>Invoice</th>
                        <th>Customer</th>
                        <th>Collection Date</th>
                        <th>Collected Amount</th>
                        <th>Note</th>
                        <th style="text-align:center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $sl=1; if($collections && $collections->num_rows>0): while($row=$collections->fetch_assoc()): ?>
                    <tr>
                        <td>
                            <?php echo $sl++; ?>
                        </td>
                        <td>
                            <?php echo htmlspecialchars($row['invoice_no']); ?>
                        </td>
                        <td>
                            <?php echo htmlspecialchars($row['customer_name']); ?>
                        </td>
                        <td>
                            <?php echo htmlspecialchars($row['collection_date']); ?>
                        </td>
                        <td>
                            <?php echo number_format($row['collected_amount'],2); ?>
                        </td>
                        <td>
                            <?php echo htmlspecialchars($row['note']); ?>
                        </td>
                        <td class="due-action-btn">
                            <a class="btn btn-danger" href="?delete=<?php echo $row['collection_id']; ?>" onclick="return confirm('Delete this collection?')">Delete</a>
                            <button class="btn btn-print" onclick="window.open('due_collection_print.php?id=<?php echo $row['collection_id']; ?>','_blank','width=900,height=700')">Print</button>
                        </td>
                    </tr>
                    <?php endwhile; else: ?>
                    <tr>
                        <td colspan="7" style="text-align:center;color:#6b7280;">No collections found</td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </section>

    <!-- Modal -->
    <div class="modal" id="collectionModal">
        <div class="modal-content">
            <span class="close" onclick="closeModal()">&times;</span>
            <h3>Collect Due</h3>
            <form method="post" id="collectionForm">
                <input type="hidden" name="action" value="collect_due">

                <div style="margin-bottom:8px;">
                    <label>Enter Invoice No</label>
                    <div class="input-inline">
                        <input type="text" id="invoiceInput" placeholder="Invoice #">
                        <span id="invoiceInfo" style="margin-left:8px;color:#444"></span>
                    </div>
                </div>

                <div style="margin-bottom:8px;">
                    <label>Select Customer</label>
                    <select id="customerSelect">
          <option value="">-- Select Customer --</option>
          <?php
          $res2 = $conn->query("SELECT customer_id, customer_name FROM customers ORDER BY customer_name ASC");
          while($c=$res2->fetch_assoc()):
          ?>
          <option value="<?php echo $c['customer_id']; ?>"><?php echo htmlspecialchars($c['customer_name']); ?></option>
          <?php endwhile; ?>
        </select>
                </div>

                <div style="margin-bottom:8px;">
                    <label>Select Sale (Pending Due)</label>
                    <select id="saleSelect" name="sale_id">
          <option value="">-- Select Sale --</option>
        </select>
                    <div id="remainingDue" style="margin-top:4px;font-size:0.9em;color:#555">Remaining Due: 0</div>
                </div>

                <div style="margin-bottom:8px;">
                    <label>Collected Amount</label>
                    <input type="number" id="collectAmount" name="collected_amount" step="0.01" min="0" required>
                </div>

                <div style="margin-bottom:8px;">
                    <label>Collection Date</label>
                    <input type="date" name="collection_date" value="<?php echo date('Y-m-d'); ?>" required>
                </div>

                <div style="margin-bottom:8px;">
                    <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</button>
                    <button type="button" class="btn" onclick="closeModal()">Cancel</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>
        const pendingByCustomer = <?php echo $pending_json ?: '{}' ?>;
        const invoiceInput = document.getElementById('invoiceInput');
        const saleSelect = document.getElementById('saleSelect');
        const customerSelect = document.getElementById('customerSelect');
        const collectAmount = document.getElementById('collectAmount');
        const remainingDue = document.getElementById('remainingDue');
        const invoiceInfo = document.getElementById('invoiceInfo');

        function openModal() {
            document.getElementById('collectionModal').style.display = 'flex';
        }

        function closeModal() {
            document.getElementById('collectionModal').style.display = 'none';
            document.getElementById('collectionForm').reset();
            saleSelect.innerHTML = '<option value="">-- Select Sale --</option>';
            remainingDue.innerText = 'Remaining Due: 0';
            invoiceInfo.innerText = '';
        }

        // Live invoice lookup
        invoiceInput.addEventListener('input', function() {
            let val = this.value.trim();
            saleSelect.innerHTML = '<option value="">-- Select Sale --</option>';
            remainingDue.innerText = 'Remaining Due: 0';
            collectAmount.value = '';
            customerSelect.value = '';

            if (val.length > 0) {
                fetch('sale_lookup.php?invoice=' + encodeURIComponent(val))
                    .then(res => res.json())
                    .then(data => {
                        if (data.length > 0) {
                            let firstSale = data[0];
                            customerSelect.value = firstSale.customer_id;

                            // populate sale dropdown
                            data.forEach(s => {
                                let opt = document.createElement('option');
                                opt.value = s.sale_id;
                                opt.dataset.due = s.due;
                                opt.text = s.invoice_no + ' - Due: ' + s.due;
                                saleSelect.appendChild(opt);
                            });

                            // select the first sale
                            saleSelect.selectedIndex = 1;
                            let sel = saleSelect.selectedOptions[0];
                            collectAmount.value = parseFloat(sel.dataset.due).toFixed(2);
                            remainingDue.innerText = 'Remaining Due: ' + parseFloat(sel.dataset.due).toFixed(2);

                        } else {
                            invoiceInfo.innerText = 'Invoice not found';
                        }
                    });
            }
        });


        // Customer select -> load pending sales
        customerSelect.addEventListener('change', function() {
            let cid = this.value;
            saleSelect.innerHTML = '<option value="">-- Select Sale --</option>';
            remainingDue.innerText = 'Remaining Due: 0';
            collectAmount.value = '';
            if (cid && pendingByCustomer[cid]) {
                pendingByCustomer[cid].forEach(s => {
                    let opt = document.createElement('option');
                    opt.value = s.sale_id;
                    opt.dataset.due = s.due;
                    opt.text = s.invoice_no + ' - ' + s.due;
                    saleSelect.appendChild(opt);
                });
            }
        });

        // Sale select -> auto-fill amount
        saleSelect.addEventListener('change', function() {
            let sel = saleSelect.selectedOptions[0];
            if (sel) {
                collectAmount.value = parseFloat(sel.dataset.due || 0).toFixed(2);
                remainingDue.innerText = 'Remaining Due: ' + parseFloat(sel.dataset.due).toFixed(2);
            } else {
                collectAmount.value = '';
                remainingDue.innerText = 'Remaining Due: 0';
            }
        });

        // Update remaining due when amount input changes
        collectAmount.addEventListener('input', function() {
            let sel = saleSelect.selectedOptions[0];
            if (sel) {
                let due = parseFloat(sel.dataset.due || 0);
                let collected = parseFloat(collectAmount.value || 0);
                remainingDue.innerText = 'Remaining Due: ' + (due - collected).toFixed(2);
            } else remainingDue.innerText = 'Remaining Due: 0';
        });
    </script>
</body>

</html>