<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

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

require_once "db.php";

// ============================
// Generate Invoice Number
// ============================
function generateInvoice($conn) {
    $prefix = "INV";
    $res = $conn->query("SELECT invoice_no FROM sales ORDER BY sale_id DESC LIMIT 1");
    $last = $res && $res->num_rows > 0 ? $res->fetch_assoc()['invoice_no'] : '';
    $num = intval(substr($last, 3)) + 1;
    return $prefix . str_pad($num, 6, '0', STR_PAD_LEFT);
}

// ============================
// Handle form submission
// ============================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $customer_id = intval($_POST['customer'] ?? 0);
    $sale_date   = $_POST['sale_date'] ?? '';
    $due_date    = $_POST['due_date'] ?? ''; // new field
    $paid_input  = floatval($_POST['paid'] ?? 0);

    if ($customer_id > 0 && !empty($sale_date)) {
        $products  = $_POST['product'] ?? [];
        $sizes     = $_POST['size'] ?? [];
        $sizeQtys  = $_POST['size_qty'] ?? [];
        $rates     = $_POST['rate'] ?? [];
        $qtys      = $_POST['qty'] ?? [];

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

        for ($i = 0; $i < $count; $i++) {
            $size = (float)($sizes[$i] ?? 0);
            $size_qty = (float)($sizeQtys[$i] ?? 1);
            $rate = (float)($rates[$i] ?? 0);
            $qty = (float)($qtys[$i] ?? 0);

            $subtotal = $size * $size_qty * $rate * $qty;
            $subtotals[$i] = $subtotal;
            $total += $subtotal;
        }

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

        $invoice_no = generateInvoice($conn);

        $payment_due_date = $_POST['payment_due_date'] ?? null;

        $stmt = $conn->prepare("INSERT INTO sales (customer_id, sale_date, total, paid, due, invoice_no, payment_due_date) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("isdddss", $customer_id, $sale_date, $total, $paid, $due, $invoice_no, $payment_due_date);
        $stmt->execute();
        $sale_id = $stmt->insert_id;
        $stmt->close();

        // Insert sale items
        $stmtItem = $conn->prepare("INSERT INTO sale_items (sale_id, product, size, rate, qty, subtotal) VALUES (?, ?, ?, ?, ?, ?)");
        for ($i = 0; $i < $count; $i++) {
            $prod = trim($products[$i]);
            if ($prod === '') continue;
            $size = (float)($sizes[$i] ?? 0);
            $size_qty = (float)($sizeQtys[$i] ?? 1);
            $rate = (float)($rates[$i] ?? 0);
            $qty = (float)($qtys[$i] ?? 0);
            $subtotal = (float)($subtotals[$i] ?? 0);
            $combinedSize = $size . " × " . $size_qty;
            $stmtItem->bind_param("issdid", $sale_id, $prod, $combinedSize, $rate, $qty, $subtotal);
            $stmtItem->execute();
        }
        $stmtItem->close();

        header("Location: new-sale.php?added=1");
        exit();
    }
}




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


// ----------------------
// Fetch recent 5 sales with customer name
// ----------------------
$recentSql = "
SELECT s.sale_id, s.sale_date, s.total, s.paid, s.due, s.invoice_no,
       c.customer_name AS customer_name
FROM sales s
LEFT JOIN customers c ON s.customer_id = c.customer_id
ORDER BY s.sale_id DESC
LIMIT 5
";
$recent = $conn->query($recentSql);
if (!$recent) die("Failed to fetch recent sales: " . $conn->error);

// ============================
// Fetch notifications (due today)
// ============================
$today = date('Y-m-d');
$notifQuery = "
SELECT s.invoice_no, s.due, c.customer_name 
FROM sales s
JOIN customers c ON s.customer_id = c.customer_id
WHERE s.payment_due_date = '$today' AND s.due > 0
";

$notifications = $conn->query($notifQuery);
$notif_count = $notifications ? $notifications->num_rows : 0;
?>

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <title>New Sale</title>
        <link rel="stylesheet" href="https://insaf.shopnofy.com/update7/css/style.css" />
        <style>
            .error-text {
                color: red;
                display: none;
                font-size: 13px;
            }
            input:invalid,
            select:invalid {
                border-color: red;
            }
            table {
                width: 100%;
                border-collapse: collapse;
                margin-top: 12px;
            }
            th,
            td {
                border: 1px solid #e6edf3;
                padding: 8px;
                text-align: left;
            }

        </style>
    </head>
    <body>
        <?php include("global/header.php"); ?>

        <main class="main">
            <header class="topbar">
                <button class="hamburger" id="hamburger">☰</button>
                <div style="margin-left: 8px; font-weight: 600">
                    Dashboard <span class="topbar-menu-space"> > </span> New Sale
                </div>

                <!-- Global Notification start -->
                <?php include("global/notify.php"); ?>
                <!-- Global Notification end -->

                <div class="profile">
                    <button class="profile-btn" id="profileBtn">
                        <span>Welcome <?= $_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">✅ Sale saved successfully.</div>
                    <?php endif; ?>

                    <form method="post" id="saleForm" onsubmit="return validateSaleForm();">
                        <div class="form-row">
                            <div class="form-group">
                                <label>Customer</label>
                                <select name="customer" id="customer" required>
                                    <option value="">-- Select Customer --</option>
                                    <?php while($c = $customers->fetch_assoc()): ?>
                                    <option value="<?= $c['customer_id'] ?>">
                                        <?= htmlspecialchars($c['customer_name']) ?>
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                                <small id="customerError" class="error-text">Please select customer</small>
                            </div>
                            <div class="form-group">
                                <label>Sale Date</label>
                                <input type="date" name="sale_date" id="saleDate" required />
                                <small id="dateError" class="error-text">Please select date</small>
                            </div>
                            <div class="form-group">
                                <label>Payment Due Date</label>
                                <input type="date" name="payment_due_date" id="payment_due_date" />
                            </div>
                            <div class="form-group">
                                <label>Invoice No</label>
                                <input type="text" value="<?= generateInvoice($conn); ?>" readonly />
                            </div>
                        </div>

                        <table>
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th>Size</th>
                                    <th>Size Qty</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="number" name="size[]" class="size" min="0" value="0" /></td>
                                    <td>
                                        <input type="number" name="size_qty[]" class="size_qty" min="0" value="0" />
                                    </td>
                                    <td>
                                        <input type="number" name="rate[]" class="rate" min="0" step="0.01" 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 btn-danger" type="button" onclick="removeRow(this)">Remove</button></td>
                                </tr>
                            </tbody>
                        </table>

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

                        <div class="summary" style="margin-top: 15px">
                            Total: <input type="text" id="total" name="total" readonly value="0.00" /> Paid:
                            <input type="number" id="paid" name="paid" value="0" min="0" step="0.01" /> Due:
                            <input type="text" id="due" name="due" readonly value="0.00" />
                        </div>

                        <div class="sale-submit-btn">
                            <button class="btn" type="submit">Submit Sale</button>
                        </div>
                    </form>
                    <div class="recent-box">
<h3>Recent 5 Sales</h3>
<table>
    <thead>
        <tr>
            <th>Customer</th>
            <th>Invoice</th>
            <th>Date</th>
            <th>Total (৳)</th>
            <th>Paid (৳)</th>
            <th>Due (৳)</th>
        </tr>
    </thead>
    <tbody>
        <?php if ($recent && $recent->num_rows > 0): ?>
            <?php while ($r = $recent->fetch_assoc()): ?>
            <tr>
                <td><?php echo htmlspecialchars($r['customer_name']); ?></td>
                <td><?php echo htmlspecialchars($r['invoice_no']); ?></td>
                <td><?php echo htmlspecialchars($r['sale_date']); ?></td>
                <td><?php echo number_format((float)$r['total'], 2); ?></td>
                <td><?php echo number_format((float)$r['paid'], 2); ?></td>
                <td><?php echo number_format((float)$r['due'], 2); ?></td>
            </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr><td colspan="7" style="text-align:center;color:#6b7280;">No recent sales</td></tr>
        <?php endif; ?>
    </tbody>
</table>
</div>
                </div>
            </section>
        </main>

        <script>
            function validateSaleForm() {
                let valid = true;
                const customer = document.getElementById("customer");
                const date = document.getElementById("saleDate");
                const customerError = document.getElementById("customerError");
                const dateError = document.getElementById("dateError");

                customerError.style.display = "none";
                dateError.style.display = "none";
                customer.style.borderColor = "";
                date.style.borderColor = "";

                if (customer.value === "") {
                    customerError.style.display = "block";
                    customer.style.borderColor = "red";
                    valid = false;
                }
                if (date.value === "") {
                    dateError.style.display = "block";
                    date.style.borderColor = "red";
                    valid = false;
                }
                if (!valid) return false;
                calculateTotals();
                return true;
            }

            function calculateTotals() {
                let total = 0;
                document.querySelectorAll("#productRows tr").forEach((row) => {
                    const size = parseFloat(row.querySelector(".size").value) || 0;
                    const size_qty = parseFloat(row.querySelector(".size_qty").value) || 1;
                    const rate = parseFloat(row.querySelector(".rate").value) || 0;
                    const qty = parseFloat(row.querySelector(".qty").value) || 0;
                    const subtotal = size * size_qty * rate * qty;
                    row.querySelector(".subtotal").value = subtotal.toFixed(2);
                    total += subtotal;
                });
                document.getElementById("total").value = total.toFixed(2);
                const paid = parseFloat(document.getElementById("paid").value) || 0;
                const due = total - paid;
                document.getElementById("due").value = due < 0 ? "0.00" : due.toFixed(2);
            }

            function addRow() {
                const tbody = document.getElementById("productRows");
                const tr = document.createElement("tr");
                tr.innerHTML = `
        <td><input type="text" name="product[]" required></td>
        <td><input type="number" name="size[]" class="size" min="0" value="0"></td>
        <td><input type="number" name="size_qty[]" class="size_qty" min="0" value="0"></td>
        <td><input type="number" name="rate[]" class="rate" min="0" step="0.01" 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 btn-danger" type="button" onclick="removeRow(this)">Remove</button></td>`;
                tbody.appendChild(tr);
            }

            function removeRow(btn) {
                btn.closest("tr").remove();
                calculateTotals();
            }
            document.getElementById("productRows").addEventListener("input", calculateTotals);
            document.getElementById("paid").addEventListener("input", calculateTotals);
            calculateTotals();

            // Notification toggle
            const notifBtn = document.getElementById("notifBtn");
            const notifList = document.getElementById("notifList");
            notifBtn.addEventListener("click", (e) => {
                e.stopPropagation();
                notifList.classList.toggle("open");
            });
            document.addEventListener("click", () => notifList.classList.remove("open"));
        </script>
        <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>
    </body>
</html>
