<?php
include("../db/cn.php");

$products_query = "SELECT * FROM products";
$products_result = mysqli_query($connection, $products_query);

// Store fetched products in an array
$products = array();
while ($row = mysqli_fetch_array($products_result)) {
    $product = array(
        "name" => $row["name"],
        "product_id" => $row["product_id"],
        "unit_price" => $row["unit_pr"],
        "trade_price" => $row["trade_price"],
        "retail_price" => $row["price"],
        "supplier_name" => $row["supplier_name"],
        "category" => $row["company_category"],
        "company_category" => $row["category"],
		"total_quantity" => $row["total_quantity"]
    );
    $products[] = $product;
}

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'];
}

// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
    // Initialize variables from form fields or set default values
    $orderId = uniqid('ORDER');
    $dateTime = $_POST['date_time'] ?? '';

    // Handle undefined array keys safely
    $taxAmount = $_POST['tax_amount'] ?? 0;
    $totalAmount = $_POST['total_input'] ?? 0;
    $paidBy = $_POST['paid_by'] ?? '';
    $customerName = $_POST['customer_name'] ?? '';
    $customerPhone = $_POST['customer_phone'] ?? '';
    $discountedAmount = $_POST['discounted'] ?? '';
    $discounted = $_POST['result'] ?? '';
    $discountper = $_POST['discount_percentage'] ?? '';
    $cashAmount = $_POST['cash_amount'] ?? '';
    $changeAmount = $_POST['change_amount'] ?? '';

    // Initialize arrays from form fields or set default values
    $productIds = $_POST['productIds'] ?? [];
    $productNames = $_POST['productNames'] ?? [];
    $productPrices = $_POST['productPrices'] ?? [];
    $productQuantities = $_POST['productQuantities'] ?? [];
    $retailPrices = $_POST['retailPrices'] ?? [];
    $supplierNames = $_POST['supplierNames'] ?? [];
    $companyCategories = $_POST['companyCategories'] ?? [];
    $companies = $_POST['companies'] ?? [];
	$bonuses = $_POST['bonuses'] ?? [];
	$discounts = $_POST['discounts'] ?? [];
	$taxes = $_POST['taxes'] ?? [];
	$netAmounts = $_POST['netAmounts'] ?? [];
	$tradePrices = $_POST['tradePrices'] ?? [];

    // Loop through product details and insert into database
    foreach ($productIds as $key => $productId) {
        // Retrieve corresponding product details
        $productName = $productNames[$key] ?? '';
		$tradePrice = $tradePrices[$key] ?? '';
        $productPrice = $productPrices[$key] ?? '';
        $productQuantity = $productQuantities[$key] ?? '';
        $productTotal = $retailPrices[$key] ?? '';
        $supplierName = $supplierNames[$key] ?? '';
        $companyCategory = $companyCategories[$key] ?? '';
        $company = $companies[$key] ?? '';
		$bonus = $bonuses[$key] ?? '';
		$discount = $discounts[$key] ?? '';
		$tax = $taxes[$key] ?? '';
		$netAmount = $netAmounts[$key] ?? '';

    // Insert product sale into database
    mysqli_query($connection,"INSERT INTO log_user_sales (product_id, supplier_name, company, company_category, product_name, trade_price, product_price, product_quantity, product_total, bonus, discount, tax, net_amount, tax_amount, total_amount, paid_by, 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', '$companyCategory', '$productName', '$tradePrice', '$productPrice', '$productQuantity', '$productTotal', '$bonus', '$discount', '$tax', '$netAmount', '$taxAmount', '$totalAmount', '$paidBy', '$customerName', '$customerPhone', '$discountedAmount', '$discounted', '$discountper', '$cashAmount', '$changeAmount', '$orderId', '$outlet_name', '$userName', '$userRole', '$outlet_address', '$dateTime')");
	
    // Update product quantity in products table
    mysqli_query($connection, "UPDATE products SET total_quantity = total_quantity - $productQuantity - $bonus WHERE name = '$productName'");
}
	// Redirect to print page
    header("Location: printpos.php?order_id=$orderId");
    exit();
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            background-image:url(img/glass-sheet.jpg);
            background-size: cover;
            background-position: center;
            background-attachment: fixed;
        }

        .wrapper {
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .header,
        .footer {
            width: 100%;
            height: 70px;
            background-color: #060606;
            color: #fff;
            text-align: ;
       /* Center text vertically */
        }

        .content {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
        }

        #product-container-wrapper {
            max-height: 250px;
            overflow-y: auto;
        }

        .dropdown-options {
            display: none;
            position: absolute;
            z-index: 1000;
            width: calc(89% - 2px);
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #ccc;
            background-color: #fff;
        }

        .option {
            padding: 5px 10px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .option:hover,
        .option.highlight {
            background-color: #353535;
            color: #fff;
        }

        @keyframes blink {
            0% {
                opacity: 1;
            }

            50% {
                opacity: 0;
            }

            100% {
                opacity: 1;
            }
        }

        #total-amount {
            font-size: 46px;
            font-weight: 700;
            color: #0A5064;
            animation: blink 1s step-start infinite;
        }

        label {
            font-weight: 600;
			font-size:14px;
        }

        .in_c {
            border: 1.5px solid #0A5064;
        }
		  img.pulse {
        width: 45px;
        height: 50px;
        animation: pulse 2s infinite;
    }
    @keyframes pulse {
        0% {
            transform: scale(1);
        }
        50% {
            transform: scale(1.2);
        }
        100% {
            transform: scale(1);
        }
    }
	.btn-success{ background:#0A5064;
	color:#fff;
     border:1px solid #353535;	
	}
	.input-height{
	    height:27px;
		font-size:14px
		}
    </style>
</head>

<body>
    <div class="wrapper">
        <div class="header row">
        <div class="col-sm-3">
<a href="addproduct.php"><img class="pulse" src="img/Jabbas Fav (1).png" width="38" height="55"></a>
        </div>
<div class="col-sm-6">
<h3 style="color:#fff; text-align:center;line-height:70px; font-weight:600;"><img src="img/Jabbar Glass House (1).png" width="160" height="60"></h3>
 </div>    
 <div class="col-sm-3"></div>
        </div>

        <div class="content">
            <div class="container">
<form action="newpos.php" method="post" enctype="multipart/form-data">
    <div class="container">
  
        <div class="row" style=" border:1px solid #0A5064; border-radius:7px; background:#FFF;padding:10px;">
        <div class="col-sm-2">
         <label>Invoice#</label>
                    <input type="text" class="form-control in_c input-height"  readonly />
          </div>
         <div class="col-sm-2">
           <label>Invoice Date</label>
                    <input type="text" class="form-control in_c input-height"  value="<?php echo date('Y-m-d'); ?>" readonly />
          </div>
         
          
          <div class="col-sm-2">
           <label>Customer Name</label>
                    <input type="text" class="form-control in_c input-height" name="customer_name" />
          </div>
          <div class="col-sm-2">
           <label>Cell#</label>
                    <input type="text" class="form-control in_c input-height" name="customer_phone" />
          </div>
          <div class="col-sm-2">
         <label>Customer ID</label>
                    <input type="text" class="form-control in_c input-height" name="customer_id" />
          </div>
          <div class="col-sm-2">
           <label>Go-Down</label>
                       <select class="form-control input-height" style="font-size:12px;">
                       <option>Select</option>
                       </select>
          </div>
          <br>
            <div class="col-sm-5">
            <br>
                <div class="form-group" style=" border:1px solid #ccc; border-radius:7px; background:#EFEFE5;padding:10px;">
                    <input type="text" id="searchInput" class="search-input form-control in_c input-height" placeholder="Enter The Product" />
                    <div id="filteredOptions" class="dropdown-options"></div>
                </div>
            </div>
            <div class="col-sm-4"></div>
            <div class="col-sm-3" style="margin-top:20px;background:#353535; text-align:center; padding:15px;border-radius:10px;border:1px solid #0A5064; ">

                <span style="font-size:46px; font-weight:700; color:#0A5064; " id="total-amount">0.00</span>
            </div>
        </div>
         <br>
        <div class="row">
            <div class="col-sm-12" id="product-container-wrapper" style="height:auto;  border:1px solid #0A5064; border-radius:7px; background:#F5F5F5;padding:10px;">
                <table id="cart-table" class="table table-striped table-sm text-center">
                    <thead>
                        <tr class="bg-dark text-white" style="border-radius:10px; font-size:14px;">
                        <th>R.Qty</th>
                        <th>Item Code</th>
                            <th>Description</th>
                            <th>Qty</th>
                            <th>Bonus</th>
                            <th>Unit Price</th>
                            <th>Amount</th>
                            <th>Disc %</th>
                            <th>Tax</th>
                            <th>Net Amount</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Cart items will be dynamically added here -->
                    </tbody>
                </table>
                <!-- Hidden inputs for additional required fields -->
      
        <input type="hidden" name="outlet_name" value="<?php echo $outlet_name; ?>" />
        <input type="hidden" name="login_user" value="<?php echo $userName; ?>" />
        <input type="hidden" name="user_role" value="<?php echo $userRole; ?>" />
        <input type="hidden" name="outlet_address" value="<?php echo $outlet_address; ?>" />
        <input type="hidden" name="date_time" value="<?php echo date('Y-m-d'); ?>" />

                <div id="hidden-fields-container"></div>
            </div>
        </div>
       
        
        <div class="row" style="margin-top:30px;">
    <div class="col-sm-12" style="background:#F5F5F5; padding:18px; border:1px solid #0A5064; border-radius:7px;">
        <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_c input-height" readonly />
                </div>
            </div>
            <div class="col-sm-2">
                <div class="form-group">
                    <label>Bill Amount</label>
          <input type="number" id="discount-input" name="discounted" class="form-control in_c input-height" oninput="calculateResult()" required />
                </div>
            </div>
            <div class="col-sm-2">
                <div class="form-group">
                    <label>Discount Amount</label>
                    <input type="number" id="result-input" name="result" class="form-control in_c input-height" readonly />
                </div>
            </div>
            <div class="col-sm-2">
                <div class="form-group">
                    <label>Discount %</label>
                    <input type="number" id="percentage-display" name="discount_percentage" class="form-control in_c input-height" readonly />
                </div>
            </div>
            <div class="col-sm-2">
                <div class="form-group">
                    <label>Cash Received</label>
                    <input type="number" id="cash-input" name="cash_amount" class="form-control in_c input-height" />
                </div>
            </div>
            <div class="col-sm-2">
                <div class="form-group">
                    <label>Cash Return</label>
                    <input type="number" id="balance-input" name="change_amount" class="form-control in_c input-height" readonly />
                </div>
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-sm-2">
                <div class="form-group">
                    <label>S.Tax(0%)</label>
                    <input type="text" class="form-control in_c input-height" name="tax_amount"  value="0" readonly/>
                </div>
            </div>
           
            <div class="col-sm-2">
                <div class="form-group">
                    <label>Method</label>
                    <select name="paid_by" class="form-control input-height" style="font-size:12px;">
                        <option value="cash">Cash</option>
                        <option value="credit">Credit</option>
                        <option value="other">Other</option>
                    </select>
                </div>
            </div>
            <div class="col-sm-3">
                <br>
                <button id="bill-button" class="btn btn-success form-control" type="submit" name="submit">Bill</button>
                
                <!--<button id="hold-bill-button" class="btn btn-dark" type="submit" name="hold_order">Hold</button>-->
            </div>
        </div>
    </div>
</div>


        <br>
        <div class="row">
            <div class="col-sm-5"></div>
            <div class="col-sm-2"></div>
            <div class="col-sm-5">
                
            </div>
        </div>
        <div class="row">
            <div class="col-sm-12 text-left">
               
            </div>
        </div>
    </div>
</form>
            </div>
        </div>

       
    </div>
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function calculateResult() {
    var total = document.getElementById('total-input').value;
    var discount = document.getElementById('discount-input').value;
    
    var result = parseFloat(total) - parseFloat(discount);
    
    document.getElementById('result-input').value = result.toFixed(2);
}

$(document).ready(function () {
    var products = <?php echo json_encode($products); ?>;
    var $searchInput = $('#searchInput');
    var $filteredOptions = $('#filteredOptions');
    var $cartTableBody = $('#cart-table tbody');
    var totalAmount = 0;

    $searchInput.on('input', function () {
        var value = $(this).val().toLowerCase();
        var html = '';
        products.forEach(function (product) {
            if (product.name.toLowerCase().includes(value)) {
                html += '<div class="option" data-value="' + product.name + '">' + product.name + '</div>';
            }
        });
        $filteredOptions.html(html);
        if (value.length > 0) {
            $filteredOptions.show();
            $filteredOptions.find('.option').first().addClass('highlight');
        } else {
            $filteredOptions.hide();
        }
    });

    $searchInput.on('keydown', function (e) {
        var $options = $('.option');
        var currentIndex = $options.index($('.option.highlight'));
        switch (e.which) {
            case 40: // Down Arrow
                e.preventDefault();
                if (currentIndex === -1 || currentIndex === $options.length - 1) {
                    $options.first().addClass('highlight').siblings().removeClass('highlight');
                } else {
                    $options.eq(currentIndex + 1).addClass('highlight').siblings().removeClass('highlight');
                }
                break;
            case 38: // Up Arrow
                e.preventDefault();
                if (currentIndex === -1 || currentIndex === 0) {
                    $options.last().addClass('highlight').siblings().removeClass('highlight');
                } else {
                    $options.eq(currentIndex - 1).addClass('highlight').siblings().removeClass('highlight');
                }
                break;
            case 13: // Enter
                if (currentIndex !== -1) {
                    var selectedProduct = $options.eq(currentIndex).data('value');
                    addProductToCart(selectedProduct);
                    $searchInput.val('');
                    $filteredOptions.hide();
                    return false; // Prevent form submission
                }
                break;
        }
    });

    $(document).on('click', '.option', function (e) {
        e.stopPropagation();
        var selectedProduct = $(this).data('value');
        addProductToCart(selectedProduct);
        $searchInput.val('');
        $filteredOptions.hide();
    });

   function addProductToCart(productName) {
    var product = products.find(function (p) {
        return p.name === productName;
    });

    if (product) {
        var unitPrice = parseFloat(product.unit_price);
        var tradePrice = parseFloat(product.trade_price); // Add the trade price
        var productId = product.product_id;
        var supplierName = product.supplier_name;
        var companyCategory = product.category;
        var company = product.company_category;
        var retailPrice = parseFloat(product.retail_price);
        var total_quantity = product.total_quantity;
        var $existingRow = $cartTableBody.find('tr[data-product="' + product.name + '"]');
        if ($existingRow.length > 0) {
            var $qtyInput = $existingRow.find('.qty-input');
            var newQty = parseInt($qtyInput.val()) + 1;
            $qtyInput.val(newQty);
            var newTotal = unitPrice * newQty;
            $existingRow.find('.total-price').text(newTotal.toFixed(2));

            var productIndex = $existingRow.index();
            $('input[name="productQuantities[]"]').eq(productIndex).val(newQty);
            $('input[name="retailPrices[]"]').eq(productIndex).val(newTotal.toFixed(2));
        } else {
            var newTotal = unitPrice;
            var netAmount = newTotal;

            var row = '<tr data-product="' + product.name + '">' +
                '<td style="color:#4C0027;font-weight:700;">' + total_quantity + '</td>' +
                '<td style="color:#4C0027;font-weight:700;">' + productId + '</td>' +
                '<td style="font-weight:600; font-size:14px;">' + product.name + '</td>' +
                '<td><center><input type="number" class="qty-input form-control input-height" value="1" min="1" style="width:80px;" /></center></td>' +
                '<td><center><input type="number" class="bonus-input input-height form-control" value="0" min="0" style="width:80px;" /></center></td>' +
                '<td>' + unitPrice + '</td>' +
                '<td class="total-price">' + newTotal.toFixed(2) + '</td>' +
                '<td><center><input type="number" class="discount-input form-control input-height" value="0" min="0" max="100" style="width:80px;" /></center></td>' +
                '<td><center class="tax-amount">0</center></td>' +
                '<td class="net-amount">' + netAmount.toFixed(2) + '</td>' +
                '<td><button class="btn btn-danger btn-sm remove-btn btn-sm">x</button></td>' +
                '</tr>';

            $cartTableBody.append(row);

            $('<input>').attr({
                type: 'hidden',
                name: 'productIds[]',
                value: productId
            }).appendTo('#hidden-fields-container');
            $('<input>').attr({
                type: 'hidden',
                name: 'productNames[]',
                value: product.name
            }).appendTo('#hidden-fields-container');
            $('<input>').attr({
                type: 'hidden',
                name: 'productPrices[]',
                value: unitPrice
            }).appendTo('#hidden-fields-container');
            $('<input>').attr({
                type: 'hidden',
                name: 'tradePrices[]', // Hidden field for trade price
                value: tradePrice
            }).appendTo('#hidden-fields-container');
            $('<input>').attr({
                type: 'hidden',
                name: 'productQuantities[]',
                value: 1
            }).appendTo('#hidden-fields-container');
            $('<input>').attr({
                type: 'hidden',
                name: 'retailPrices[]',
                value: newTotal.toFixed(2)
            }).appendTo('#hidden-fields-container');
            $('<input>').attr({
                type: 'hidden',
                name: 'supplierNames[]',
                value: supplierName
            }).appendTo('#hidden-fields-container');
            $('<input>').attr({
                type: 'hidden',
                name: 'companyCategories[]',
                value: companyCategory
            }).appendTo('#hidden-fields-container');
            $('<input>').attr({
                type: 'hidden',
                name: 'companies[]',
                value: company
            }).appendTo('#hidden-fields-container');
            $('<input>').attr({
                type: 'hidden',
                name: 'bonuses[]',
                value: 0
            }).appendTo('#hidden-fields-container');
            $('<input>').attr({
                type: 'hidden',
                name: 'discounts[]',
                value: 0
            }).appendTo('#hidden-fields-container');
            $('<input>').attr({
                type: 'hidden',
                name: 'taxes[]',
                value: 0
            }).appendTo('#hidden-fields-container');
            $('<input>').attr({
                type: 'hidden',
                name: 'netAmounts[]',
                value: netAmount.toFixed(2)
            }).appendTo('#hidden-fields-container');
        }

        totalAmount += unitPrice;
        $('#total-amount').text(totalAmount.toFixed(2));
        $('#total-input').val(totalAmount.toFixed(2));
        calculateDiscountedTotal();
    }
}


function calculateTotalNetAmount() {
    var totalNetAmount = 0;
    $('.net-amount').each(function () {
        var netAmount = parseFloat($(this).text());
        if (!isNaN(netAmount)) {
            totalNetAmount += netAmount;
        }
    });
    $('#total-input').val(totalNetAmount.toFixed(2));
}
     $cartTableBody.on('input', '.discount-input, .qty-input', function () {
        var $row = $(this).closest('tr');
        var discountPercentage = parseFloat($row.find('.discount-input').val());
        var qty = parseInt($row.find('.qty-input').val());
        var productName = $row.data('product');
        var product = products.find(function (p) {
            return p.name === productName;
        });
        var unitPrice = parseFloat(product.unit_price);
        var newTotal = unitPrice * qty;
        var discountAmount = (discountPercentage / 100) * newTotal;
        var netAmount = newTotal - discountAmount;
        $row.find('.net-amount').text(netAmount.toFixed(2));

        var productIndex = $row.index();
        $('input[name="productQuantities[]"]').eq(productIndex).val(qty); // Update the quantity in the hidden input
        $('input[name="discounts[]"]').eq(productIndex).val(discountPercentage);
        $('input[name="netAmounts[]"]').eq(productIndex).val(netAmount.toFixed(2));

        calculateTotalNetAmount();
    });

    $cartTableBody.on('input', '.bonus-input', function () {
        var $row = $(this).closest('tr');
        var bonusValue = parseFloat($row.find('.bonus-input').val());
        var productIndex = $row.index();
        $('input[name="bonuses[]"]').eq(productIndex).val(bonusValue);
    });

    $('#discount-input').on('input', function () {
        calculateDiscountedTotal();
        calculateDiscountPercentage();
    });

    function calculateDiscountPercentage() {
        var totalAmount = parseFloat($('#total-input').val());
        var discountedAmount = parseFloat($('#discount-input').val());

        if (!isNaN(totalAmount) && !isNaN(discountedAmount) && totalAmount > 0) {
            var discountPercentage = ((totalAmount - discountedAmount) / totalAmount) * 100;
            $('#percentage-display').val(discountPercentage.toFixed(2));
        } else {
            $('#percentage-display').val('0.00');
        }
    }

    function calculateDiscountedTotal() {
        var discountAmount = parseFloat($('#discount-input').val());
        if (!isNaN(discountAmount) && discountAmount > 0) {
            var discountedTotal = totalAmount - discountAmount;
            $('#discounted-input').val(discountedTotal.toFixed(2));
            $('#total-after-discount').text(discountedTotal.toFixed(2));
        } else {
            $('#discounted-input').val(totalAmount.toFixed(2));
            $('#total-after-discount').text(totalAmount.toFixed(2));
        }
    }

    $('#cash-input').on('input', function () {
        var cashReceived = parseFloat($(this).val()) || 0;
        var billAmount = parseFloat($('#discount-input').val()) || 0;
        var totalAmount = parseFloat($('#total-input').val()) || 0;

        // Determine the amount to subtract from
        var amountToSubtract = billAmount > 0 ? billAmount : totalAmount;
        var balance = cashReceived - amountToSubtract;

        $('#balance-input').val(balance.toFixed(2));
    });

    $(document).on('click', '.remove-btn', function () {
        var $row = $(this).closest('tr');
        var totalPrice = parseFloat($row.find('.net-amount').text());
        totalAmount -= totalPrice;
        $('#total-amount').text(totalAmount.toFixed(2));
        $('#total-input').val(totalAmount.toFixed(2));
        $row.remove();
        calculateDiscountedTotal();
    });

    $('#bill-amount').on('input', function () {
        var totalAmount = parseFloat($('#total-amount').val()) || 0;
        var billAmount = parseFloat($(this).val()) || 0;
        var discountAmount = totalAmount - billAmount;

        $('#discount-amount').val(discountAmount.toFixed(2));
    });
});
</script>

</body></html> 



