<?php
include("../db/cn.php");
ob_start();
if (isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
}
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}
if (isset($_GET['query'])) {
    $query = $connection->real_escape_string($_GET['query']);
    $sql = "SELECT product_id, product_name, retail_price, length, width, supplier, company FROM products WHERE product_name LIKE '%$query%'";
    $result = $connection->query($sql);

    $suggestions = "";
    while ($row = $result->fetch_assoc()) {
        $suggestions .= "<li class='list-group-item' data-product-id='" . $row['product_id'] . "' data-retail-price='" . $row['retail_price'] . "' data-length='" . $row['length'] . "' data-width='" . $row['width'] . "' data-supplier='" . $row['supplier'] . "' data-company='" . $row['company'] . "'>" . $row['product_name'] . "</li>";
    }

    echo $suggestions;
    exit;
}


$user = $userName;
$role = $userRole;
$outlet = $outlet_name;
$address = $outlet_address;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check connection
    if ($connection->connect_error) {
        die("Connection failed: " . $connection->connect_error);
    }

    $productData = json_decode($_POST['productData'], true);
    $orderId = uniqid("order");
     // Example value, replace with actual data
    $companyCategory = "Company Category"; // Example value, replace with actual data
    $paidBy = $_POST['method']; // Payment method from the form
    $discount_amount = $_POST["bill_amount"];
    $discounted = $_POST["discount_amount"];
    $discount_per = $_POST["discount_percent"];
    $cash_amount = $_POST["cash_received"];
    $change_amount = $_POST["cash_return"];
    $customerName = $_POST["customer_name"];
    $customerPhone = $_POST["customer_phone"];
    $customer_type = $_POST["customer_type"];
    $customer_id = $_POST["customer_id"];
    $date_time = date("Y-m-d");
    $l_feet = isset($_POST["l_feet"]) ? $_POST["l_feet"] : '';
    $w_feet = isset($_POST["w_feet"]) ? $_POST["w_feet"] : '';
    $l_inch = isset($_POST["l_inch"]) ? $_POST["l_inch"] : '';
    $w_inch = isset($_POST["w_inch"]) ? $_POST["w_inch"] : '';
    $area = isset($_POST["sqarea"]) ? $_POST["sqarea"] : '';
    $piece = $_POST["piece1"];

    foreach ($productData as $product) {
        $productId = $product['productId'];
        $productName = $product['description'];
        $productPrice = $product['pricePerUnit'];
        $productQuantity = $product['quantity'];
        $productTotal = $product['totalPrice'];
        $discount = $product['discountPercentage'];
        $tax = $product['tax'];
        $netAmount = $product['netAmount'];
        $supplierName = $product['supplier']; 
        $company = $product['company'];
		
        $sql = "INSERT INTO log_user_sales (
            product_id,
            supplier_name,
            company,
            product_name,
            l_feet,
            w_feet,
            l_inch,
            w_inch,
            area,
            piece,
            product_price,
            product_quantity,
            product_total,
            bonus,
            discount,
            tax,
            net_amount,
            total_amount,
            paid_by,
            customer_id,
            customer_type,
            customer_name,
            customer_phone,
            discount_amount,
            discounted,
            discount_per,
            cash_amount,
            change_amount,
            order_id,
            outlet_name,
            login_user,
            user_role,
            outlet_address,
            date_time
        ) VALUES (
            '$productId',
            '$supplierName',
            '$company',
            '$productName',
            '$l_feet',
            '$w_feet',
            '$l_inch',
            '$w_inch',
            '$area',
            '$piece',
            '$productPrice',
            '$productQuantity',
            '$productTotal',
            '',
            '$discount',
            '$tax',
            '$netAmount',
            '$productTotal',
            '$paidBy',
            '$customer_id',
            '$customer_type',
            '$customerName',
            '$customerPhone',
            '$discount_amount',
            '$discounted',
            '$discount_per',
            '$cash_amount',
            '$change_amount',
            '$orderId',
            '$outlet',
            '$user',
            '$role',
            '$address',
            '$date_time'
        )";
        
    }
       ob_end_clean();
        if ($connection->query($sql) === TRUE) {
            
            echo "<script type='text/javascript'>
            window.location.href = 'printpos.php?order_id=$orderId';
          </script>";
        } else {
            echo "Error: " . $sql . "<br>" . $connection->error;
        }
}
ob_end_flush();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Jabbar Glass House</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>
        .bg {
            background: linear-gradient(270deg, #060606, #0A5064);
        }
        .input-group-text {
            font-weight: 600;
            font-size: 11px;
        }
        .in_form {
            height: 30px;
            font-size: 13px;
			border-color:#0A5064;
        }
        label {
            font-size: 13.5px;
            font-weight: 700;
        }
		.input-group-text {
    font-weight: 600;
    font-size: 11px;
    width: 73px;
}
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-sm-12 bg" style="width:100%; height:69px;">
            
                <a href="addproduct.php"><img src="img/Jabbar Glass House (1).png" style="margin-top:5px;" width="156" height="52"></a>
            
        </div>
    </div>
</div>
<div class="container-fluid">
    <form action="mainpos.php" method="post" enctype="multipart/form-data">
        <div class="row">
            <div class="col-sm-3" style="background:#F0F0F0; padding:10px; border:1px solid #CCC; ">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">Product</span>
                    </div>
                    <input type="text" class="form-control" id="productInput" placeholder="Start typing a product name...">
                </div>
                <ul class="list-group" id="suggestions" style="display: none;"></ul>

                <hr>
                <div class="row">
                    <div class="col-sm-6 input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-dark text-white">L (Inch)</span>
                        </div>
                        <input type="text" name="l_inch" id="lengthInch" class="form-control" placeholder="Inch" />
                    </div>
                    <div class="col-sm-6 input-group mb-3">
                        <input type="text" name="w_inch" id="widthInch" class="form-control" placeholder="Inch" />
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-dark text-white">W (Inch)</span>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-6 input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-dark text-white">L (Feet)</span>
                        </div>
                        <input type="text" name="l_feet" id="lengthFeet" class="form-control" placeholder="Feet" />
                    </div>
                    <div class="col-sm-6 input-group mb-3">
                        <input type="text" name="w_feet" id="widthFeet" class="form-control" placeholder="Feet" />
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-dark text-white">W (Feet)</span>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-6 input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-dark text-white">Area</span>
                        </div>
                        <input type="text" name="sqarea" id="area" class="form-control" placeholder="" readonly>
                    </div>
                    <div class="col-sm-6 input-group mb-3">
                        <input type="text" name="piece1" id="piece" class="form-control" placeholder="">
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-dark text-white">Piece</span>
                        </div>
                    </div>
                </div>
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">Quantity</span>
                    </div>
                    <input type="text" id="quantity" name="quantity" class="form-control" placeholder="" readonly>
                </div>
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">Price / Unit</span>
                    </div>
                    <input type="text" id="retail_price" name="retail_price" class="form-control" placeholder="">
                </div>
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">Total Price</span>
                    </div>
                    <input type="text" id="total_amount"  name="total_amount" class="form-control" placeholder="" readonly>
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">-/ PKR</span>
                    </div>
                </div>
                
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">Dis %</span>
                    </div>
                    <input type="text" id="percentage" name="percentage" class="form-control" placeholder="">
                </div>
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">Total Price</span>
                    </div>
                    <input type="text" id="trade_price" name="trade_price" class="form-control" placeholder="" readonly>
                </div>
                <br>
                <button type="button" class="form-control btn btn-dark" id="makeEntry">Make Entry</button>
                <hr>
                <button type="button" class="form-control btn btn-dark">Refresh</button>
            </div>
            <div class="col-sm-9">
                <div class="row" style="background:#F0F0F0; padding:10px; border:1px solid #CCC; ">
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label>Customer Type</label>
                            <select class="form-control in_form" name="customer_type">
                                <option value="">Select Customer</option>
                                <option value="walking Customer">Walking Customer</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label>Customer Name</label>
                            <input type="text" name="customer_name" class="form-control in_form"/>
                        </div>
                    </div>

                    <div class="col-sm-3">
                        <div class="form-group">
                            <label>Customer Phone</label>
                            <input type="text" 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" name="customer_id" class="form-control in_form"/>
                        </div>
                    </div>

                </div>

                <div class="row" style="background:#F0F0F0; padding:10px; border:1px solid #CCC;">
                    <div class="col-sm-12" style="height:400px;">
                        <table class="table table-borderless table-sm text-center" id="productsTable">
                            <tr class="text-white text-center" style="background:#0A5064;">
                                <td>Item Code</td>
                                <td>Description</td>
                                <td>Qty</td>
                                
                                <td>Unit Price</td>
                                <td>Amount</td>
                                <td>% Dis</td>
                                <td>Tax</td>
                                <td>Net Amount</td>
                                <td>Action</td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div class="row" style="margin-top: -10px;">
                    <div class="col-sm-12" style="background:#F0F0F0; padding:10px; border:1px solid #CCC;">
                        <br>
                        <div class="row">
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Total</label>
                                    <input type="number" id="total-input" name="total_input" class="form-control in_form input-height" readonly/>
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Bill Amount</label>
                                    <input type="text" id="bill-amount" name="bill_amount" class="form-control in_form input-height" required/>
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Discount Amount</label>
                                    <input type="number" id="discount_amount" name="discount_amount" class="form-control in_form input-height"/>
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Discount %</label>
                                    <input type="number" id="discount_percent" name="discount_percent" class="form-control in_form input-height" readonly/>
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Cash Received</label>
                                    <input type="number" id="cash_received" name="cash_received" class="form-control in_form input-height" />
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Cash Return</label>
                                    <input type="number" id="cash_return" name="cash_return" class="form-control in_form input-height" />
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>S.Tax(0%)</label>
                                    <input type="number" id="tax" name="tax" class="form-control in_form input-height" value="0" readonly/>
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Method</label>
                                    <select name="method" id="method" class="form-control in_form">
                                        <option>Cash</option>
                                        <option>Credit</option>
                                        <option>Others</option>
                                    </select>
                                </div>
                            </div>
                            <input type="hidden" id="productData" name="productData">
                            <div class="col-sm-3">
                            <hr>
                                <button type="submit" class="btn btn-dark btn-sm">Generate Invoice</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<script>
document.addEventListener("DOMContentLoaded", function() {
    // Function to calculate the area
    function calculateArea() {
        let lengthInch = parseFloat(document.getElementById("lengthInch").value) || 0;
        let widthInch = parseFloat(document.getElementById("widthInch").value) || 0;
        let lengthFeet = parseFloat(document.getElementById("lengthFeet").value) || 0;
        let widthFeet = parseFloat(document.getElementById("widthFeet").value) || 0;

        let areaInSquareFeet = 0;

        if (lengthInch && widthInch) {
            let lengthFeetFromInch = lengthInch / 12;
            let widthFeetFromInch = widthInch / 12;
            areaInSquareFeet = lengthFeetFromInch * widthFeetFromInch;
        } else if (lengthFeet && widthFeet) {
            areaInSquareFeet = lengthFeet * widthFeet;
        }

        document.getElementById("area").value = areaInSquareFeet.toFixed(2);
        calculateQuantity();
    }

    // Function to calculate quantity
    function calculateQuantity() {
        let area = parseFloat(document.getElementById("area").value) || 0;
        let piece = parseInt(document.getElementById("piece").value) || 0;

        if (!isNaN(area) && !isNaN(piece)) {
            let quantity = area * piece;
            document.getElementById("quantity").value = quantity.toFixed(2);
            calculateTotalPrice();
        }
    }

    // Function to calculate total price
    function calculateTotalPrice() {
        let quantity = parseFloat(document.getElementById("quantity").value) || 0;
        let pricePerUnit = parseFloat(document.getElementById("retail_price").value) || 0;
        let discountPercentage = parseFloat(document.getElementById("percentage").value) || 0;

        if (!isNaN(quantity) && !isNaN(pricePerUnit)) {
            let totalPrice = quantity * pricePerUnit;
            let discountedPrice = totalPrice;
            
            if (!isNaN(discountPercentage) && discountPercentage > 0) {
                discountedPrice = totalPrice - (totalPrice * (discountPercentage / 100));
            }

            document.getElementById("total_amount").value = totalPrice.toFixed(2);
            document.getElementById("trade_price").value = discountedPrice.toFixed(2);
        }
    }

    // Event listeners for input fields
    document.getElementById("lengthInch").addEventListener("input", calculateArea);
    document.getElementById("widthInch").addEventListener("input", calculateArea);
    document.getElementById("lengthFeet").addEventListener("input", calculateArea);
    document.getElementById("widthFeet").addEventListener("input", calculateArea);
    document.getElementById("piece").addEventListener("input", calculateQuantity);
    document.getElementById("retail_price").addEventListener("input", calculateTotalPrice);
    document.getElementById("percentage").addEventListener("input", calculateTotalPrice);

document.getElementById("suggestions").addEventListener("click", function(e) {
    if (e.target && e.target.nodeName === "LI") {
        var selectedProduct = e.target.textContent;
        var retailPrice = e.target.getAttribute('data-retail-price');
        var productId = e.target.getAttribute('data-product-id');
        var supplier = e.target.getAttribute('data-supplier');
        var company = e.target.getAttribute('data-company');
        
        document.getElementById("productInput").value = selectedProduct;
        document.getElementById("retail_price").value = retailPrice;
        document.getElementById("productInput").setAttribute('data-product-id', productId);
        document.getElementById("productInput").setAttribute('data-supplier', supplier);
        document.getElementById("productInput").setAttribute('data-company', company);

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

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

document.getElementById("makeEntry").addEventListener("click", function() {
    var productInput = document.getElementById("productInput");

    // Debugging logs
    console.log("Product ID: ", productInput.getAttribute('data-product-id'));
    console.log("Supplier: ", productInput.getAttribute('data-supplier'));
    console.log("Company: ", productInput.getAttribute('data-company'));

    var productId = productInput.getAttribute('data-product-id');
    var supplier = productInput.getAttribute('data-supplier');
    var company = productInput.getAttribute('data-company');

    var description = productInput.value;
    var quantity = document.getElementById("quantity").value;
    var pricePerUnit = document.getElementById("retail_price").value;
    var totalPrice = document.getElementById("total_amount").value;
    var discountPercentage = document.getElementById("percentage").value;
    var netAmount = document.getElementById("trade_price").value;

    if (productId && description && quantity && pricePerUnit && totalPrice && discountPercentage && netAmount) {
        var table = document.getElementById("productsTable");
        var row = table.insertRow();
        row.innerHTML = `
            <td>${productId}</td>
            <td style="color:#0A5064;font-weight:700px;">${description}</td>
            <td>${quantity}</td>
            <td>${pricePerUnit}</td>
            <td>${totalPrice}</td>
            <td>${discountPercentage}</td>
            <td>0</td>
            <td>${netAmount}</td>
            <td style="display:none;">${supplier}</td>
            <td style="display:none;">${company}</td>
            <td><button class="btn btn-danger btn-sm delete-row">X</button></td>
        `;

        document.getElementById("productInput").value = "";
        document.getElementById("quantity").value = "";
        document.getElementById("retail_price").value = "";
        document.getElementById("total_amount").value = "";
        document.getElementById("percentage").value = "";
        document.getElementById("trade_price").value = "";

        row.querySelector(".delete-row").addEventListener("click", function() {
            row.remove();
            calculateTotalAmount();
        });

        calculateTotalAmount();

        // Collect all rows' data
        var rows = document.querySelectorAll("#productsTable tr:not(:first-child)");
        var productData = [];
        rows.forEach(function(row) {
            var cells = row.querySelectorAll("td");
            var product = {
                productId: cells[0].innerText,
                description: cells[1].innerText,
                quantity: cells[2].innerText,
                pricePerUnit: cells[3].innerText,
                totalPrice: cells[4].innerText,
                discountPercentage: cells[5].innerText,
                tax: cells[6].innerText,
                netAmount: cells[7].innerText,
                supplier: cells[8].innerText,
                company: cells[9].innerText
            };
            productData.push(product);
        });

        console.log("Product Data: ", productData);
        document.getElementById("productData").value = JSON.stringify(productData);
    } else {
        console.log("Some required fields are missing");
    }
});

// Function to calculate total amount
function calculateTotalAmount() {
    var table = document.getElementById("productsTable");
    var rows = table.getElementsByTagName("tr");
    var total = 0;

    for (var i = 1; i < rows.length; i++) { // Start from 1 to skip the header row
        var netAmountCell = rows[i].cells[7]; // Assuming net amount is in the 9th cell (index 8)
        var netAmount = parseFloat(netAmountCell.textContent.trim());
        if (!isNaN(netAmount)) {
            total += netAmount;
        }
    }

    var totalInput = document.getElementById("total-input");
    totalInput.value = total.toFixed(2);
    updateDiscountAmount(total); // Update discount based on total amount
}

// Function to update discount amount and percentage
function updateDiscountAmount() {
    var total = parseFloat(document.getElementById("total-input").value) || 0;
    var billAmount = parseFloat(document.getElementById("bill-amount").value) || 0;
    var discountAmountInput = document.getElementById("discount_amount");
    var discountPercentInput = document.getElementById("discount_percent");

    if (!isNaN(billAmount) && !isNaN(total)) {
        var discountAmount = total - billAmount;
        discountAmountInput.value = Math.round(discountAmount);

        if (total > 0) {
            var discountPercent = (discountAmount / total) * 100;
            discountPercentInput.value = discountPercent.toFixed(2);
        } else {
            discountPercentInput.value = "0.00";
        }
    }
}

// Function to calculate cash return
function calculateCashReturn() {
    var billAmount = parseFloat(document.getElementById("bill-amount").value) || 0;
    var cashReceived = parseFloat(document.getElementById("cash_received").value) || 0;
    var cashReturnInput = document.getElementById("cash_return");

    if (!isNaN(billAmount) && !isNaN(cashReceived)) {
        var cashReturn = cashReceived - billAmount;
        cashReturnInput.value = cashReturn.toFixed(2);
    }
}

// Event listener for bill amount input
document.getElementById("bill-amount").addEventListener("input", function() {
    updateDiscountAmount();
});

// Event listener for cash received input
document.getElementById("cash_received").addEventListener("input", function() {
    calculateCashReturn();
});

// Initial calculation of total amount
calculateTotalAmount();
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</body>
</html>
