<!----------------------------------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_address, Customer_phone FROM customer");


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

// Fetch products for product selection dropdown
$products_cat = $con->query("SELECT * FROM product_cat");

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

// Get customer details from the customer table using customer_id
$customer_query = $con->query("SELECT Customer_name, customer_address, Customer_phone FROM customer WHERE id = '$customer_id'");
$customer_data = $customer_query->fetch_assoc();

// Customer details
$customer_name = $customer_data['Customer_name'];
$customer_address = $customer_data['customer_address'];
$customer_phone = $customer_data['Customer_phone'];


    // Insert into `sales` table
    $stmt = $con->prepare("INSERT INTO sales (customer_name, Customer_phone, customer_address,  deposit, discount, grand_total, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssddds", $customer_name,$customer_phone, $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();

            
        }
    }
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;

    $stmt->close();
    if (isset($item_stmt)) $item_stmt->close();
}

?>

<!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="checkQuantity(this, ${product.id})"></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}">${product.purchase_price}</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(); // Update grand total after removal
        }

        function checkQuantity(input, productId) {
            const quantity = parseInt(input.value) || 0;

            // Check available stock using AJAX
            fetch(`check_stock.php?product_id=${productId}`)
                .then(response => response.json())
                .then(data => {
                    const availableQuantity = data.available_quantity;
                    if (quantity > availableQuantity) {
                        alert(`Only ${availableQuantity} units are available for Product ID ${productId}.`);
                        input.value = availableQuantity; // Set to max available quantity
                    }
                    updateTotal(input);
                });
        }

        function updateTotal(quantityInput) {
            const row = quantityInput.closest("tr");
            const price = parseFloat(row.cells[3].innerText);
            const quantity = parseInt(quantityInput.value);
            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 scanProduct() {
            const productId = document.getElementById("scanInput").value;
            if (productId) {
                fetch(`check_stock.php?product_id=${productId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.available_quantity > 0) {
                            addProductToList({
                                id: productId,
                                description: data.description,
                                price: data.price,
                                purchase_price: purchase.price,
                            });
                        } else {
                            alert(`Product ID ${productId} is out of stock.`);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('An error occurred while scanning the product.');
                    });
            } else {
                alert('Please enter a product ID to scan.');
            }
        }

        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);
        }

        function addGuestCustomer() {
            const guestName = document.getElementById("guest_name").value;
            const guestAddress = document.getElementById("guest_address").value;

            if (guestName && guestAddress) {
                // Set guest information in the customer fields
                document.getElementById("customer_name").value = guestName;
                document.getElementById("customer_address").value = guestAddress;
                document.getElementById("guest_name").value = ''; // Clear guest fields
                document.getElementById("guest_address").value = '';
            } else {
                alert('Please enter guest name and address.');
            }
            
        }
    </script>
</head>
<body>
<div class="container mt-5">
    <h2>Create Sale</h2>
    <form method="post">
        <div class="form-group">
        <label for="customer_id">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']) ?>" 
                            data-name="<?= htmlspecialchars($customer['Customer_name']) ?>"
                            data-address="<?= htmlspecialchars($customer['customer_address']) ?>"
                            data-phone="<?= htmlspecialchars($customer['Customer_phone']) ?>">
                        <?= htmlspecialchars($customer['Customer_name']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </div>

        <div id="guest-info" style="display:none;">
            <div class="form-group">
                <label for="guest_name">Guest Name:</label>
                <input type="text" id="guest_name" class="form-control">
            </div>
            <div class="form-group">
                <label for="guest_address">Guest Address:</label>
                <input type="text" id="guest_address" class="form-control">
            </div>
            <button type="button" class="btn btn-secondary" onclick="addGuestCustomer()">Add Guest Customer</button>
        </div>

        <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']) ?>" purchase_price="<?= htmlspecialchars($product_cat['purchase_price']) ?>">
                        <?= htmlspecialchars($product_cat['Product_name']) ?> (<?= htmlspecialchars($product_cat['Product_id']) ?>) - $<?= htmlspecialchars($product_cat['price']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
            <button type="button" class="btn btn-primary mt-2" onclick="addSelectedProduct()">Add Product</button>
        </div>

        <div class="form-group">
            <label for="scanInput">Scan Product ID:</label>
            <input type="text" id="scanInput" class="form-control" onkeypress="if(event.key === 'Enter') { scanProduct(); return false; }">
        </div>

        <table class="table" id="productList">
            <thead>
            <tr>
                <th>Product ID</th>
                <th>Description</th>
                <th>Quantity</th>
                <th>Price</th>
                <th>Total</th>
                <th>P price</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>

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

<script>
    // Show guest info fields when guest option is selected
    document.getElementById("customer_name").addEventListener("change", function() {
        if (this.value === "guest") {
            document.getElementById("guest-info").style.display = "block";
        } else {
            document.getElementById("guest-info").style.display = "none";
        }
    });
</script>

</body>
  