<?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 (শুধুমাত্র active products, cancelled বাদ)
$current_date = date('Y-m-d');
$products_cat = $con->query("SELECT DISTINCT Product_id, name as Product_name, price, purchase_price FROM product WHERE status != 'cancelled' AND (Expiration_date IS NULL OR Expiration_date = '' OR Expiration_date >= '$current_date') ORDER BY name");

// Action handling for creating a sale
if (isset($_POST['createSale'])) {
    $customer_id = intval($_POST['customer_id'] ?? 0);
    $payment_method = $con->real_escape_string($_POST['payment_method'] ?? '');
    $deposit = floatval($_POST['deposit'] ?? 0);
    $discount = floatval($_POST['discount'] ?? 0);
    $collected_one = floatval($_POST['collected_one'] ?? 0);
    $final_amount = floatval($_POST['final_amount'] ?? 0);
    $final_due = floatval($_POST['final_due'] ?? 0);
    $collected = floatval($_POST['collected'] ?? 0);
    $change = floatval($_POST['change'] ?? 0);
    $grand_total = floatval($_POST['grand_total'] ?? 0);
    $created_at = date("Y-m-d H:i:s");

    // Get customer details from the customer table using customer_id
    $customer_stmt = $con->prepare("SELECT Customer_name, id, customer_address, Customer_phone FROM customer WHERE id = ?");
    $customer_stmt->bind_param("i", $customer_id);
    $customer_stmt->execute();
    $customer_result = $customer_stmt->get_result();
    $customer_data = $customer_result->fetch_assoc();

    if ($customer_data) {
        // 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("sisssdddddddds", $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_id = intval($product_id);
                $product_description = $con->real_escape_string($_POST['product_description'][$index]);
                $quantity = floatval($_POST['quantity'][$index]); // Changed to floatval for decimal support
                $price = floatval($_POST['price'][$index]);
                $purchase_price = floatval($_POST['purchase_price'][$index]);
                $total = $price * $quantity;
                $total_purchase = $purchase_price * $quantity;

                // Check stock with prepared statement
                $stock_stmt = $con->prepare("SELECT SUM(Quantity) as available_quantity FROM product WHERE Product_id = ?");
                $stock_stmt->bind_param("i", $product_id);
                $stock_stmt->execute();
                $stock_result = $stock_stmt->get_result();
                $row = $stock_result->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/poss.css">
    <style>
        .product-search {
            position: relative;
        }
        .product-suggestions {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #ddd;
            border-top: none;
            max-height: 200px;
            overflow-y: auto;
            z-index: 1000;
            display: none;
        }
        .product-suggestion {
            padding: 10px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
        }
        .product-suggestion:hover {
            background-color: #f8f9fa;
        }
        .product-suggestion:last-child {
            border-bottom: none;
        }
    </style>
</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" 
                               oninput="autoScanProduct(this.value)">
                        <div class="input-group-append">
                            <button type="button" class="btn btn-success" onclick="manualScanProduct()">Add</button>
                        </div>
                    </div>
                </div>

                <!-- Product Manual Search Section -->
                <div class="form-group">
                    <label for="productSearchInput">Search Product:</label>
                    <div class="product-search">
                        <input type="text" id="productSearchInput" class="form-control" placeholder="Type product name or ID..." 
                               oninput="searchProducts(this.value)">
                        <div id="productSuggestions" class="product-suggestions"></div>
                    </div>
                </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" step="0.01" min="0" 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 -->Net Collected:</label>
                        <input type="number" name="collected" id="collected" class="form-control" step="0.01" min="0" onchange="calculateGrandTotal()">
                    </div>

                    <div class="form-group">
                        <label for="collected_one"> <!--Amount Collected One-->Amount Collected :</label>
                        <input type="number" name="collected_one" id="collected_one" class="form-control" step="0.01" min="0" onchange="calculateGrandTotal()"required>
                    </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>
        let productData = [];
        
        // Load product data on page load
        function loadProductData() {
            fetch('get_products.php')
                .then(response => response.json())
                .then(data => {
                    productData = data;
                })
                .catch(error => console.error('Error loading products:', error));
        }

        // Auto scan product without button click
        function autoScanProduct(productId) {
            if (productId.trim() && productId.length >= 3) {
                // Clear previous timeout
                clearTimeout(window.scanTimeout);
                
                // Set new timeout for auto-scan after user stops typing
                window.scanTimeout = setTimeout(() => {
                    checkAndAddProduct(productId.trim());
                }, 500);
            }
        }

        // Manual scan when button is clicked
        function manualScanProduct() {
            const productId = document.getElementById("scanInput").value.trim();
            if (productId) {
                checkAndAddProduct(productId);
            } else {
                alert('Please enter a product ID to scan.');
            }
        }

        // Check product and add to list
        function checkAndAddProduct(productId) {
            fetch(`check_stock.php?product_id=${encodeURIComponent(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 or not found.`);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Product not found or an error occurred while scanning.');
                });
        }

        // Search products function
        function searchProducts(searchTerm) {
            const suggestions = document.getElementById('productSuggestions');
            
            if (searchTerm.length < 1) {
                suggestions.style.display = 'none';
                return;
            }

            fetch(`search_products.php?search=${encodeURIComponent(searchTerm)}`)
                .then(response => response.json())
                .then(data => {
                    if (data.length > 0) {
                        suggestions.innerHTML = '';
                        data.forEach(product => {
                            const div = document.createElement('div');
                            div.className = 'product-suggestion';
                            div.innerHTML = `
                                <strong>${product.Product_name}</strong> (${product.Product_id})<br>
                                <small>Price: ${parseFloat(product.price).toFixed(2)} | Stock: ${product.available_quantity}</small>
                            `;
                            div.onclick = () => selectProduct(product);
                            suggestions.appendChild(div);
                        });
                        suggestions.style.display = 'block';
                    } else {
                        suggestions.innerHTML = '<div class="product-suggestion">No products found</div>';
                        suggestions.style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('Error searching products:', error);
                    suggestions.innerHTML = '<div class="product-suggestion">Error searching products</div>';
                    suggestions.style.display = 'block';
                });
        }

        // Select product from suggestions
        function selectProduct(product) {
            if (product.available_quantity > 0) {
                addProductToList({
                    id: product.Product_id,
                    description: product.Product_name,
                    price: product.price,
                    purchase_price: product.purchase_price,
                });
                document.getElementById('productSearchInput').value = '';
                document.getElementById('productSuggestions').style.display = 'none';
            } else {
                alert('This product is out of stock.');
            }
        }

        // Hide suggestions when clicking outside
        document.addEventListener('click', function(event) {
            if (!event.target.closest('.product-search')) {
                document.getElementById('productSuggestions').style.display = 'none';
            }
        });

        function addProductToList(product) {
            const table = document.getElementById("productList").getElementsByTagName('tbody')[0];
            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="0.01" step="0.01" 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 = parseFloat(input.value) || 0;

            fetch(`check_stock.php?product_id=${productId}`)
                .then(response => response.json())
                .then(data => {
                    const availableQuantity = parseFloat(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 = parseFloat(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 => {
                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 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();
            loadProductData();
        });
    </script>
</body>
</html>