
<!----------------------------------Login------------------------------------>
<?php
session_start();
include 'php/db_connection.php';

// শুধুমাত্র লগইন করা ইউজার পেজ দেখতে পারবে
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userName = $_SESSION['user_name'];
$role = $_SESSION['role']; // ✅ এখানে role সেভ করা হচ্ছে
$userId = $_SESSION['user_id'];


$isAdmin = ($_SESSION['role'] == 'admin');

?>

<!---------------------------------কন্টেন------------------------------------>
<?php

// Fetch customers for dropdown
$customers = $con->query("SELECT id, customer_name, Customer_phone, Customer_address FROM customer");

// Fetch products for product selection dropdown
$products_cat = $con->query("SELECT Product_id, Product_name, price, purchase_price FROM product_cat");

// Action handling for creating a sale
if (isset($_POST['createSale'])) {
    $customer_id = $_POST['customer_id'] ?? null;
    $deposit = $_POST['deposit'] ?? 0;
    $discount = $_POST['discount'] ?? 0;
    $grand_total = $_POST['grand_total'] ?? 0;
    $created_at = date("Y-m-d H:i:s");

    // Validate and fetch customer details
    $customer_name = "";
    $customer_address = "";
    if ($customer_id) {
        $customer_query = $con->query("SELECT customer_name, Customer_address FROM customer WHERE id = '$customer_id'");
        $customer_data = $customer_query->fetch_assoc();
        if ($customer_data) {
            $customer_name = $customer_data['customer_name'];
            $customer_address = $customer_data['Customer_address'];
        }
    }

    // Insert into `sales` table
    $stmt = $con->prepare("INSERT INTO sales (customer_id, customer_name, customer_address, deposit, discount, grand_total, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("issddds", $customer_id, $customer_name, $customer_address, $deposit, $discount, $grand_total, $created_at);
    $stmt->execute();
    $sale_id = $stmt->insert_id;

    // Insert into `sales_items` table and deduct quantities from `product` table
    if (isset($_POST['product_id']) && is_array($_POST['product_id'])) {
        foreach ($_POST['product_id'] as $index => $product_id) {
            $product_description = $_POST['product_description'][$index];
            $quantity = $_POST['quantity'][$index];
            $price = $_POST['price'][$index];
            $purchase_price = $_POST['purchase_price'][$index];
            $total = $price * $quantity;

            // Check stock
            $check_stock = $con->query("SELECT SUM(Quantity) as available_quantity FROM product WHERE Product_id = '$product_id'");
            $row = $check_stock->fetch_assoc();
            $available_quantity = $row['available_quantity'];

            if ($quantity > $available_quantity) {
                echo "<script>alert('Insufficient stock for product ID $product_id. Only $available_quantity available.');</script>";
                continue;
            }

            // Insert item into `sales_items`
            $item_stmt = $con->prepare("INSERT INTO sales_items (sales_id, product_id, product_description, quantity, price, purchase_price, total) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $item_stmt->bind_param("iisiddd", $sale_id, $product_id, $product_description, $quantity, $price, $purchase_price, $total);
            $item_stmt->execute();

            // Deduct quantity from product table
            $con->query("UPDATE product SET Quantity = Quantity - $quantity WHERE Product_id = '$product_id' AND Quantity >= $quantity");
        }
    }

    $stmt->close();
    if (isset($item_stmt)) $item_stmt->close();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Sales</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script>
        function addProductToList(product) {
            const table = document.getElementById("productList");
            const row = table.insertRow();
            row.innerHTML = `
                <td><input type="hidden" name="product_id[]" value="${product.id}">${product.id}</td>
                <td><input type="hidden" name="product_description[]" value="${product.description}">${product.description}</td>
                <td><input type="number" name="quantity[]" value="1" min="1" onchange="updateTotal(this)"></td>
                <td><input type="hidden" name="price[]" value="${product.price}">${parseFloat(product.price).toFixed(2)}</td>
                <td class="total">${parseFloat(product.price).toFixed(2)}</td>
                <td><input type="hidden" name="purchase_price[]" value="${product.purchase_price}">${parseFloat(product.purchase_price).toFixed(2)}</td>
                <td><button type="button" class="btn btn-danger" onclick="removeProduct(this)">Remove</button></td>
            `;
            calculateGrandTotal();
        }

        function removeProduct(button) {
            const row = button.closest("tr");
            row.remove();
            calculateGrandTotal();
        }

        function updateTotal(quantityInput) {
            const row = quantityInput.closest("tr");
            const price = parseFloat(row.cells[3].innerText);
            const quantity = parseInt(quantityInput.value) || 0;
            const total = price * quantity;
            row.cells[4].innerText = total.toFixed(2);
            calculateGrandTotal();
        }

        function calculateGrandTotal() {
            const totals = document.querySelectorAll("#productList .total");
            let grandTotal = 0;
            totals.forEach(total => {
                grandTotal += parseFloat(total.innerText);
            });
            const discount = parseFloat(document.getElementById("discount").value) || 0;
            const finalAmount = grandTotal - discount;

            document.getElementById("grand_total").value = grandTotal.toFixed(2);
            document.getElementById("final_amount").value = finalAmount.toFixed(2);

            const collected = parseFloat(document.getElementById("collected").value) || 0;
            const change = collected - finalAmount;
            document.getElementById("change").value = change.toFixed(2);
        }

        function addSelectedProduct() {
            const productSelect = document.getElementById("productSelect");
            const selectedOption = productSelect.options[productSelect.selectedIndex];

            const product = {
                id: selectedOption.value,
                description: selectedOption.getAttribute("data-description"),
                price: parseFloat(selectedOption.getAttribute("data-price")),
                purchase_price: parseFloat(selectedOption.getAttribute("purchase_price")),
            };

            addProductToList(product);
        }
    </script>
</head>
<body>
<div class="container mt-5">
    <h2>Create Sale</h2>
    <form method="post">
        <!-- Customer Selection -->
        <div class="form-group">
            <label for="customer_id">Select Customer:</label>
            <select name="customer_id" id="customer_id" class="form-control" required>
                <option value="">Select Customer</option>
                <?php while ($customer = $customers->fetch_assoc()): ?>
                    <option value="<?= htmlspecialchars($customer['id']) ?>">
                        <?= htmlspecialchars($customer['customer_name']) ?> - <?= htmlspecialchars($customer['Customer_phone']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </div>

        <!-- Product Selection -->
        <div class="form-group">
            <label for="productSelect">Select Product:</label>
            <select id="productSelect" class="form-control">
                <option value="">Select a product</option>
                <?php while ($product_cat = $products_cat->fetch_assoc()): ?>
                    <option value="<?= htmlspecialchars($product_cat['Product_id']) ?>" 
                            data-description="<?= htmlspecialchars($product_cat['Product_name']) ?>" 
                            data-price="<?= htmlspecialchars($product_cat['price']) ?>" 
                            data-purchase_price="<?= htmlspecialchars($product_cat['purchase_price']) ?>">
                        <?= htmlspecialchars($product_cat['Product_name']) ?> - $<?= htmlspecialchars($product_cat['price']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
            <button type="button" class="btn btn-primary mt-2" onclick="addSelectedProduct()">Add Product</button>
        </div>

        <!-- Product Table -->
        <table class="table" id="productList">
            <thead>
            <tr>
                <th>Product ID</th>
                <th>Description</th>
                <th>Quantity</th>
                <th>Price</th>
                <th>Total</th>
                <th>Purchase Price</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>

        <!-- Summary Section -->
        <div class="form-group">
            <label for="discount">Discount:</label>
            <input type="number" name="discount" id="discount" class="form-control" onchange="calculateGrandTotal()">
        </div>

        <div class="form-group">
            <label for="grand_total">Grand Total:</label>
            <input type="text" name="grand_total" id="grand_total" class="form-control" readonly>
        </div>

        <div class="form-group">
            <label for="final_amount">Final Amount:</label>
            <input type="text" name="final_amount" id="final_amount" class="form-control" readonly>
        </div>

        <div class="form-group">
            <label for="collected">Amount Collected:</label>
            <input type="number" name="collected" id="collected" class="form-control" onchange="calculateGrandTotal()">
        </div>

        <div class="form-group">
            <label for="change">Change:</label>
            <input type="text" name="change" id="change" class="form-control" readonly>
        </div>

        <button type="submit" name="createSale" class="btn btn-primary">Create Sale</button>
    </form>
</div>
</body>
</html>
