<?php
include("../db/cn.php");
ob_start(); // Ensure output buffering starts

// Check if session variables are set
if (isset($_SESSION['user_name'], $_SESSION['user_role'], $_SESSION['outlet_name'], $_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
} else {
    die("Session variables not set.");
}

// Check connection
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// Fetch hold items based on order_id if provided via GET request
$orderId = isset($_GET['order_id']) ? $_GET['order_id'] : null;
$holdItems = [];
if ($orderId) {
    $sql = "SELECT product_id, supplier_name, company, product_name, net_amount, discount, product_price, trade_price, product_quantity, product_total 
            FROM pay_hold 
            WHERE order_id = '$orderId'";
    $result = $connection->query($sql);

    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $holdItems[] = $row;
        }
    }
}


if (isset($_GET['customer_name'])) {
    $customerName = $connection->real_escape_string($_GET['customer_name']);
    $sql = "SELECT cr_name, cr_id, phone_number FROM credit_note WHERE cr_name LIKE '%$customerName%' LIMIT 5";

    $result = $connection->query($sql);
    $suggestions = "";

    while ($row = $result->fetch_assoc()) {
        $suggestions .= "<div class='dropdown-item' data-customer-name='" . $row['cr_name'] . "' data-customer-id='" . $row['cr_id'] . "' data-customer-phone='" . $row['phone_number'] . "'>" . $row['cr_name'] . "</div>";
    }

    echo $suggestions;
    exit;
}


// Handle product search by product name
$searchResults = [];
if (isset($_GET['search_query'])) {
    $searchQuery = $_GET['search_query'];
    $sql = "SELECT product_id, product_name, company, product_unit, retail_price, trade_price, supplier 
            FROM products 
            WHERE product_name LIKE '%$searchQuery%'";
    $result = $connection->query($sql);

    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $searchResults[] = $row;
        }
    }

    // Return search results in JSON format for JavaScript handling
    echo json_encode($searchResults);
    exit;
}

// Handle form submission to insert data into `log_user_sales`
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['inv_bill'])) {
    $order_id = uniqid("ORDER_");
    $products = json_decode($_POST['products'], true);
    $bill_amount = isset($_POST['bill_amount']) ? $_POST['bill_amount'] : 0;
    $total_amount = isset($_POST['total_amount']) ? $_POST['total_amount'] : 0;
    $change_amount = isset($_POST['change_amount']) ? $_POST['change_amount'] : 0;
    $cash_received = isset($_POST['cash_received']) ? $_POST['cash_received'] : 0;
    $cash_return = isset($_POST['cash_return']) ? $_POST['cash_return'] : 0;
    $paid_by = $_POST['paid_by']; // Payment method

    // Customer-related fields with default values
    $customer_id = $_POST['customer_id'];
    $customer_name = $_POST['customer_name'];
    $customer_phone = $_POST['customer_phone'];

    // Discounts and bonus
    $discount_amount = $bill_amount;
    $discounted = $change_amount;
    $discount_per = isset($_POST['discount_per']) ? $_POST['discount_per'] : 0;
    $date_time = date("Y-m-d");

    // Tax and net amount calculations
    $tax_amount = isset($_POST['tax_amount']) ? $_POST['tax_amount'] : 0;
    $tax = isset($_POST['tax']) ? $_POST['tax'] : 0;

foreach ($products as $product) {
    $productId = $product['product_id'];
    $company = isset($product['company']) ? $product['company'] : '';
    $productQuantity = isset($product['product_quantity']) ? $product['product_quantity'] : 1;
    $trade_price = isset($product['trade_price']) ? $product['trade_price'] : 0;  // Make sure trade price is passed
    $product_price = isset($product['product_price']) ? $product['product_price'] : 0;  // Ensure product price is passed
    $sale_cost = $trade_price * $productQuantity;  // Correct sale cost calculation
    $product_total = isset($product['product_total']) ? $product['product_total'] : 0; // Ensure product total is passed
    $discount = isset($product['discount']) ? $product['discount'] : 0;  // Fetch discount value
    $net_amount = $product_total;  // Set net amount as product total

    // Insert into `log_user_sales`
    $sql = "INSERT INTO log_user_sales (
                product_id,
                supplier_name,
                company,
                product_name, 
                product_price,   
                trade_price,    
                product_quantity,
                product_total,   
                bonus,
                discount,
                tax,
                net_amount,
                tax_amount,
                total_amount, 
                paid_by, 
                sale_cost, 
                customer_id, 
                customer_type, 
                customer_name, 
                customer_phone, 
                discount_amount, 
                discounted, 
                discount_per, 
                cash_amount, 
                change_amount, 
                order_id, 
                r_order_id, 
                outlet_name, 
                login_user, 
                user_role, 
                outlet_address, 
                date_time
            ) VALUES (
                '{$product['product_id']}', 
                '{$product['supplier_name']}', 
                '$company', 
                '{$product['product_name']}', 
                '{$product['product_price']}',  
                '$trade_price',                
                '$productQuantity', 
                '$product_total',               
                0, 
                '$discount', 
                '$tax', 
                '$net_amount', 
                '$tax_amount', 
                '$total_amount', 
                '$paid_by', 
                '$sale_cost', 
                '$customer_id', 
                '', 
                '$customer_name', 
                '$customer_phone', 
                '$discount_amount', 
                '$discounted', 
                '$discount_per', 
                '$cash_received', 
                '$cash_return', 
                '$order_id', 
                '', 
                '$outlet_name', 
                '$userName', 
                '$userRole', 
                '$outlet_address', 
                '$date_time'
            )";

    // Execute the insert query
    if (!$connection->query($sql)) {
        echo "Error: " . $sql . "<br>" . $connection->error;
    }


        // Update product quantity in the `products` table
        $updateSql = "UPDATE products SET quantity = quantity - $productQuantity WHERE product_id = '$productId'";
        if ($connection->query($updateSql) !== TRUE) {
            echo "Error updating product quantity: " . $connection->error;
        }

        // Delete hold item
        $deleteSql = "DELETE FROM pay_hold WHERE order_id = '$order_id'";
        if ($connection->query($deleteSql) !== TRUE) {
            echo "Error deleting product from hold: " . $connection->error;
        }
    }

    // Clear output buffer and redirect
    ob_end_clean();
    echo "<script type='text/javascript'>window.location.href = 'mainpos.php';</script>";
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Amazon Fashion Store</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        #table-container-wrapper {
            max-height: 420px; 
            overflow-y: auto; 
        }
        /* Custom POS styling */
        body {
            background-color: #f8f9fa;
        }
        .pos-header {
            background: linear-gradient(270deg, #060606, #3C2F23);
            color: white;
            padding: 15px;
            text-transform:uppercase;
            font-weight:700;
        }
        .pos-container {
            margin-top: 30px;
        }
        .table-responsive {
            max-height: 300px;
            overflow-y: auto;
        }
        .table th, .table td {
            vertical-align: middle;
        }
        .total-section input {
            font-size: 1.5rem;
            text-align: right;
        }
        .btn-submit {
            background-color: #503F2E;
            color: white;
            font-size: 1.2rem;
            padding: 10px 20px;
            border-radius: 50px;
            width: 100%;
        }
		.in_height{
		 
		 height:49px;	
			
			}
    </style>
</head>
<body>
    <!-- POS Header -->
    <div class="container-fluid pos-header">
        <div class="row">
            <div class="col-sm-3" >
                <a href="orders_detail_v.php"><img src="img/Amazon Fashion STORE1.png" width="70" height="70" /></a>
            </div>
            <div class="col-sm-6">
                <h1 class="mb-0 text-center">Amazon Fashion Store</h1>
            </div>
            <div class="col-sm-3"></div>
        </div>
    </div>

 
    <div class="container-fluid">
        <div class="row">
            <div class="col-sm-3" style="padding:20px; border:1px solid #CCC;">
                <div class="search-section">
                 
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white" style="width:86px;">Product</span>
                    </div>
                      <input type="text" class="form-control" id="productSearchInput" placeholder="Search Product by Name..." onkeyup="searchProduct(event)">
                </div>
                
                  
                    <div id="searchResults" class="list-group mt-2"></div>
                </div>
 <hr>
                <div id="productDetails" class=" mt-4" style="background:none;">
                
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white" style="width:86px;">Name</span>
                    </div>
                     <span id="selectedProductName" class="form-control in_height"></span>
                </div>
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white" style="width:86px;">Supplier</span>
                    </div>
                     <span id="selectedSupplier" class="form-control in_height"></span>
                </div>
                
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white" style="width:86px;">Price</span>
                    </div>
                     <input type="number" id="retailPrice" class="form-control in_height">
                </div>
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white" style="width:86px;">Qty</span>
                    </div>
                     <input type="number" id="productQuantity" class="form-control in_height" value="1" min="1" oninput="calculateTotal()">
                </div>
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white" style="width:86px;">Dis</span>
                    </div>
                     <input type="number" id="discount" class="form-control in_height" value="1" min="1" oninput="">
                </div>
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white" style="width:86px;">Total</span>
                    </div>
                     <input type="number" id="totalPrice" class="form-control in_height" readonly>
                </div>
                
                
                       
                      
                        <button class="btn btn-dark mt-3 form-control" onclick="addProductToTable()">Make Entry</button>
                         <hr>
                <button type="button" class="form-control btn btn-dark" onclick="location.reload();">Refresh</button>
                   
                </div>
            </div>

            <div class="col-sm-9">
                <div class="row">
                    <div class="col-sm-12 " style="padding:20px; border:1px solid #CCC;">
                    <div class="row">
                     <div class="col-sm-3">
                        <div class="form-group">
                            <label>Customer Name</label>
                            <input type="text" id="customer_name" name="customer_name" class="form-control in_form" autocomplete="off">
                            <div class="dropdown-menu" id="customer_suggestions"></div>
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label>Customer Phone</label>
                            <input type="text" id="customer_phone" name="customer_phone" class="form-control in_form">
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label>Customer ID</label>
                            <input type="text" id="customer_id" name="customer_id" class="form-control in_form">
                        </div>
                    </div>
                    </div>

                    <div class="col-sm-12" style="padding:20px; border:1px solid #CCC;">
                        <div class="table-responsive" style="height:480px;" id="table-container-wrapper">
                            <table class="table table-stripped table-sm text-center" style="font-size:14.7px;">
                                <thead>
                                    <tr class="bg-dark text-white">
                                        <th>Product Name</th>
                                        <th>Quantity</th>
                                        <th>Unit Price</th>
                                        <th>Discount</th>
                                        <th>Total Price</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody id="holdItemsTable">
                                    <?php foreach ($holdItems as $item): ?>
                                        <tr>
                                            <td><?= $item['product_name'] ?></td>
                                            <td><?= $item['product_quantity'] ?></td>
                                            <td><?= $item['product_total'] ?></td>
                                            <td><?= $item['discount'] ?></td>
                                            <td><?= $item['net_amount'] ?></td>
                                            <td><button type="button" class="btn btn-danger btn-sm" onclick="removeRow(this)">X</button></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="col-sm-12 " style="padding:20px; border:1px solid #CCC;">
                    <div class="row">
                        <div class="form-group col-3">
                            <label>Total Amount:</label>
                            <input type="number" id="totalAmount" class="form-control" value="0" readonly>
                        </div>
                        <div class="form-group col-3">
                            <label>Bill Amount:</label>
                            <input type="number" id="billAmount" class="form-control" oninput="calculateChange()">
                        </div>
                        <div class="form-group col-3">
                            <label>Discount:</label>
                            <input type="number" id="changeAmount" class="form-control" readonly>
                        </div>
                        <div class="form-group col-3">
                            <label>Cash Received</label>
                            <input type="number" id="cashReceived" class="form-control" oninput="calculateCashReturn()">
                        </div>
                        <div class="form-group col-3">
                            <label>Cash Return</label>
                            <input type="number" id="cashReturn" class="form-control" readonly>
                        </div>
                        <div class="form-group col-3">
                            <label>Sale Tax(%):</label>
                            <input type="number" class="form-control" readonly>
                        </div>
                        <div class="form-group col-3">
                            <label>Method</label>
                            <Select class="form-control" name="paid_by">
                                <option value="cash">Cash</option>
                                <option value="credit">Credit</option>
                                <option value="other">Others</option>
                            </Select>
                        </div>

                        <!-- Submit Button -->
                        <form method="POST" onsubmit="prepareDataForSubmission()">
                            <input type="hidden" name="products" id="productsInput">
                            <input type="hidden" name="total_amount" id="hiddenTotalAmount">
                            <input type="hidden" name="bill_amount" id="hiddenBillAmount">
                            <input type="hidden" name="change_amount" id="hiddenChangeAmount">
                            <input type="hidden" name="cash_received" id="hiddenCashReceived">
                            <input type="hidden" name="cash_return" id="hiddenCashReturn">

                            <!-- Add hidden inputs for customer and payment details -->
                            <input type="hidden" name="customer_name" id="hiddenCustomerName">
                            <input type="hidden" name="customer_phone" id="hiddenCustomerPhone">
                            <input type="hidden" name="customer_id" id="hiddenCustomerID">
                            <input type="hidden" name="paid_by" id="hiddenPaidBy">

                            <button type="submit" class="btn btn-dark mt-4" name="inv_bill">Submit Order</button>
                        </form>
                    </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>

  document.getElementById("customer_name").addEventListener("input", function() {
        var customerName = this.value;
        if (customerName.length > 0) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "?customer_name=" + customerName, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var suggestions = document.getElementById("customer_suggestions");
                    suggestions.innerHTML = xhr.responseText;
                    suggestions.style.display = 'block';
                }
            };
            xhr.send();
        } else {
            document.getElementById("customer_suggestions").style.display = 'none';
        }
    });

    document.getElementById("customer_suggestions").addEventListener("click", function(e) {
        if (e.target && e.target.classList.contains("dropdown-item")) {
            selectCustomer(e.target);
        }
    });

    document.getElementById("customer_name").addEventListener("keydown", function(e) {
        var suggestions = document.getElementById("customer_suggestions");
        if (suggestions.style.display === 'block') {
            var items = suggestions.getElementsByClassName("dropdown-item");
            if (e.key === "ArrowDown") {
                currentFocus++;
                addActive(items);
            } else if (e.key === "ArrowUp") {
                currentFocus--;
                addActive(items);
            } else if (e.key === "Enter") {
                e.preventDefault();
                if (currentFocus > -1) {
                    if (items[currentFocus]) {
                        selectCustomer(items[currentFocus]);
                    }
                }
            }
        }
    });

    function addActive(items) {
        if (!items) return false;
        removeActive(items);
        if (currentFocus >= items.length) currentFocus = 0;
        if (currentFocus < 0) currentFocus = items.length - 1;
        items[currentFocus].classList.add("active");
        items[currentFocus].scrollIntoView({ block: "nearest" });
    }

    function removeActive(items) {
        for (var i = 0; i < items.length; i++) {
            items[i].classList.remove("active");
        }
    }

    function selectCustomer(item) {
        var customerName = item.getAttribute('data-customer-name');
        var customerId = item.getAttribute('data-customer-id');
        var customerPhone = item.getAttribute('data-customer-phone');

        document.getElementById("customer_name").value = customerName;
        document.getElementById("customer_phone").value = customerPhone;
        document.getElementById("customer_id").value = customerId;

        document.getElementById("customer_suggestions").style.display = 'none';
    }





let selectedProduct = null;
let products = [];
let selectedIndex = -1;

<?php if (!empty($holdItems)): ?>
    products = <?= json_encode($holdItems); ?>;
    updateTotalAmount();
<?php endif; ?>

function searchProduct(event) {
    const query = document.getElementById('productSearchInput').value;
    if (query.length > 2) {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', '?search_query=' + query, true);
        xhr.onload = function() {
            if (this.status == 200) {
                const productList = JSON.parse(this.responseText);
                let searchResultsHtml = '';
                productList.forEach((product, index) => {
                    searchResultsHtml += `<a href="#" class="list-group-item list-group-item-action" data-index="${index}" onclick="selectProduct(${product.product_id}, '${product.product_name}', '${product.supplier}', ${product.retail_price})">${product.product_name}</a>`;
                });
                document.getElementById('searchResults').innerHTML = searchResultsHtml;
                document.getElementById('searchResults').style.display = 'block';

                // Handle arrow key navigation and Enter selection
                document.onkeydown = function(e) {
                    if (e.key === 'ArrowDown') {
                        moveSelection(1, productList);
                    } else if (e.key === 'ArrowUp') {
                        moveSelection(-1, productList);
                    } else if (e.key === 'Enter' && selectedIndex >= 0) {
                        const selectedProductElement = document.querySelector(`.list-group-item[data-index="${selectedIndex}"]`);
                        selectedProductElement.click();
                    }
                };
            }
        };
        xhr.send();
    }
}

function moveSelection(direction, productList) {
    const items = document.querySelectorAll('.list-group-item');
    if (items.length > 0) {
        selectedIndex = (selectedIndex + direction + items.length) % items.length;
        items.forEach((item, index) => {
            item.classList.toggle('active', index === selectedIndex);
        });
    }
}

function selectProduct(id, name, supplier, retailPrice) {
    selectedProduct = { id, name, supplier, retailPrice };
    document.getElementById('selectedProductName').innerText = name;
    document.getElementById('selectedSupplier').innerText = supplier;
    document.getElementById('retailPrice').value = retailPrice;
    document.getElementById('productQuantity').value = 1;
    calculateTotal();
    document.getElementById('productDetails').style.display = 'block';
    document.getElementById('searchResults').style.display = 'none';
}

// Function to calculate total price including discount
function calculateTotal() {
    const quantity = document.getElementById('productQuantity').value;
    const retailPrice = document.getElementById('retailPrice').value;
    const discount = document.getElementById('discount').value;

    // Calculate total after applying discount
    const total = (quantity * retailPrice) - discount;
    
    // Ensure total does not go below zero
    document.getElementById('totalPrice').value = total > 0 ? total : 0;
}

function addProductToTable() {
    if (selectedProduct) {
        const quantity = document.getElementById('productQuantity').value;
        const retailPrice = document.getElementById('retailPrice').value;
        const tradePrice = selectedProduct.retailPrice; // Assuming `retailPrice` is trade price in this case
        const discount = document.getElementById('discount').value;
        const totalPrice = document.getElementById('totalPrice').value;

        // Add the product with the correct values including trade_price and product_total
        products.push({
            product_id: selectedProduct.id,
            product_name: selectedProduct.name,
            supplier_name: selectedProduct.supplier,
            product_price: retailPrice,
            trade_price: tradePrice,  // Include trade price
            product_quantity: quantity,
            discount: discount,  // Include discount field
            product_total: totalPrice,  // Include product total (net after discount)
            net_amount: totalPrice
        });

        const table = document.getElementById('holdItemsTable');
        const row = document.createElement('tr');

        row.innerHTML = `
            <td>${selectedProduct.name}</td>
            <td>${quantity}</td>
            <td>${retailPrice}</td>
            <td>${discount}</td>
            <td>${totalPrice}</td>
            <td><button type="button" class="btn btn-danger btn-sm" onclick="removeRow(this)">X</button></td>
        `;
        table.appendChild(row);
        updateTotalAmount();
    }
}
function removeRow(button) {
    const row = button.parentElement.parentElement;
    row.remove();
    const productName = row.cells[0].innerText;
    products = products.filter(p => p.product_name !== productName);
    updateTotalAmount();
}

// Function to update the total amount after all products are added
function updateTotalAmount() {
    const total = products.reduce((sum, product) => sum + parseFloat(product.net_amount), 0);
    document.getElementById('totalAmount').value = total;
}

function calculateChange() {
    const totalAmount = document.getElementById('totalAmount').value;
    const billAmount = document.getElementById('billAmount').value;
    const changeAmount = billAmount - totalAmount;
    document.getElementById('changeAmount').value = changeAmount;
}

function calculateCashReturn() {
    const billAmount = parseFloat(document.getElementById('billAmount').value);
    const cashReceived = parseFloat(document.getElementById('cashReceived').value);
    const cashReturn = cashReceived - billAmount;
    document.getElementById('cashReturn').value = cashReturn >= 0 ? cashReturn : 0;
}

function prepareDataForSubmission() {
    // Prepare product details
    document.getElementById('productsInput').value = JSON.stringify(products);
    
    // Set the values for total_amount, bill_amount, and change_amount
    document.getElementById('hiddenTotalAmount').value = document.getElementById('totalAmount').value;
    document.getElementById('hiddenBillAmount').value = document.getElementById('billAmount').value;
    document.getElementById('hiddenChangeAmount').value = document.getElementById('changeAmount').value;
    
    // Set values for cash_received and cash_return
    document.getElementById('hiddenCashReceived').value = document.getElementById('cashReceived').value;
    document.getElementById('hiddenCashReturn').value = document.getElementById('cashReturn').value;
    
    // Capture customer details and payment method
    document.getElementById('hiddenCustomerName').value = document.getElementById('customer_name').value;
    document.getElementById('hiddenCustomerPhone').value = document.getElementById('customer_phone').value;
    document.getElementById('hiddenCustomerID').value = document.getElementById('customer_id').value;
    document.getElementById('hiddenPaidBy').value = document.querySelector('select[name="paid_by"]').value;
}
</script>
</body>
</html>
