<?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'];
$userId = $_SESSION['user_id'];
$isAdmin = ($_SESSION['role'] == 'admin');

date_default_timezone_set('Asia/Dhaka');

// 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'] ?? '';
    $payment_method = $_POST['payment_method'] ?? '';
    $deposit = $_POST['deposit'] ?? 0;
    $discount = $_POST['discount'] ?? 0;
    $collected_one = $_POST['collected_one'] ?? 0;
    $final_amount = $_POST['final_amount'] ?? 0;
    $final_due = $_POST['final_due'] ?? 0;
    $collected = $_POST['collected'] ?? 0;
    $change = $_POST['change'] ?? 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, id, 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_id = $customer_data['id'];
    $customer_address = $customer_data['customer_address'];
    $customer_phone = $customer_data['Customer_phone'];

    // Insert into `sales` table
    $stmt = $con->prepare("INSERT INTO sales (customer_name, user_id, Customer_phone, customer_id, customer_address, deposit, discount, collected_one, final_amount, final_due, collected, `change`, grand_total, created_at) VALUES (?, ?, ?, ?, ?, ?,?,?,?, ?,?, ?,?,?)");
    $stmt->bind_param("sssisdddddddds", $customer_name, $userId, $customer_phone, $customer_id, $customer_address, $deposit, $discount, $collected_one, $final_amount, $final_due, $collected, $change, $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;
            $total_purchase = $purchase_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, total_purchase) VALUES (?, ?, ?, ?, ?, ?,?,?)");
            $item_stmt->bind_param("iisidddd", $sale_id, $product_id, $product_description, $quantity, $price, $purchase_price, $total, $total_purchase);
            $item_stmt->execute();
        }
    }
    
    // Use JavaScript redirect instead of header redirect
    echo "<script>window.location.href = 'sales_all_data.php';</script>";
    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">
    <link rel="stylesheet" href="css/pos.css">
</head>
<body>
    <?php include 'sidebar.php'; ?>
    <div class="container">
        <h2>Create Sale</h2>
       
        <form method="post">
            <div class="col-md-12">
                <div class="form-group">
                    <input type="hidden" name="userId" value="<?php echo $userId; ?>">
                   
                    <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-id="<?= 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>

                <!-- Product Scan Section -->
                <div class="form-group">
                    <label for="scanInput">Scan Product ID:</label>
                    <div class="input-group">
                        <input type="text" id="scanInput" class="form-control" placeholder="Enter or scan product ID" 
                               onkeypress="if(event.key === 'Enter') { scanProduct(); return false; }">
                        <div class="input-group-append">
                            <button type="button" class="btn btn-success" onclick="scanProduct()">Scan</button>
                        </div>
                    </div>
                </div>

                <!-- Product Selection Dropdown -->
                <div class="form-group">
                    <select id="productSelect" class="form-control">
                        <option value="">Select a product manually</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>

            <div class="col-md-12">
                <table class="table table-bordered" id="productList">
                    <thead class="thead-dark">
                        <tr>
                            <th>Product ID</th>
                            <th>Description</th>
                            <th>Quantity</th>
                            <th>Price</th>
                            <th>Total</th>
                            <th>Purchase</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <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>

                <div class="col-md-6">
                    <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="collected_one">Amount Collected One:</label>
                        <input type="number" name="collected_one" id="collected_one" class="form-control" onchange="calculateGrandTotal()">
                    </div>

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

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

            <button type="submit" name="createSale" class="btn btn-success btn-lg">Complete Sale</button>
        </form> 
    </div>

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

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

            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;
                    }
                    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 => {
                const value = parseFloat(total.innerText);
                if (!isNaN(value)) {
                    grandTotal += value;
                }
            });

            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_one = parseFloat(document.getElementById("collected_one").value) || 0;
            const change = collected_one > finalAmount ? collected_one - finalAmount : 0;
            const final_due = finalAmount > collected_one ? finalAmount - collected_one : 0;

            const collected = collected_one - change;
            document.getElementById("collected").value = collected.toFixed(2);

            document.getElementById("change").value = change.toFixed(2);
            document.getElementById("final_due").value = final_due.toFixed(2);
        }

        function scanProduct() {
            const productId = document.getElementById("scanInput").value.trim();
            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: data.purchase_price,
                            });
                            document.getElementById("scanInput").value = '';
                        } else {
                            alert(`Product ID ${productId} is out of stock.`);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('Product not found or an error occurred while scanning.');
                    });
            } else {
                alert('Please enter a product ID to scan.');
            }
        }

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

            if (selectedOption.value) {
                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);
                productSelect.selectedIndex = 0;
            }
        }

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

            if (guestName && guestAddress) {
                document.getElementById("customer_name").value = guestName;
                document.getElementById("customer_address").value = guestAddress;
                document.getElementById("guest_name").value = '';
                document.getElementById("guest_address").value = '';
            } else {
                alert('Please enter guest name and address.');
            }
        }

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

        // Focus on scan input when page loads
        window.addEventListener('load', function() {
            document.getElementById('scanInput').focus();
        });
    </script>
</body>
</html>