<?php
include("../db/cn.php");
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
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']) && isset($_GET['type'])) {
    $query = $connection->real_escape_string($_GET['query']);
    $type = $_GET['type'];

    // Check if the type is product or code
    if ($type == 'product') {
        $sql = "SELECT product_id, product_name, retail_price, trade_price, rpperpack, tpperpack, noofunit, supplier, company, product_unit, total_quantity 
                FROM products 
                WHERE product_name LIKE '%$query%'";
    } else {
        $sql = "SELECT product_id, product_name, retail_price, trade_price, rpperpack, tpperpack, noofunit, supplier, company, product_unit, total_quantity 
                FROM products 
                WHERE product_id LIKE '%$query%'";
    }

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

    while ($row = $result->fetch_assoc()) {
        $suggestions .= "<div class='dropdown-item' data-product-id='" . $row['product_id'] . "' data-product-unit='" . $row['noofunit'] . "' data-product-quantity='" . $row['total_quantity'] . "' data-product-unit='" . $row['product_unit'] . "' data-retail-price='" . $row['rpperpack'] . "' data-trade-price='" . $row['tpperpack'] . "' data-supplier='" . $row['supplier'] . "' data-company='" . $row['company'] . "'>" . $row['product_name'] . "</div>";
    }

    echo $suggestions;
    exit;
}


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

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

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

    echo $suggestions;
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (isset($_GET['customerQuery'])) {
        $customerQuery = $connection->real_escape_string($_GET['customerQuery']);
        $sql = "SELECT DISTINCT customer_name FROM log_user_sales WHERE LOWER(customer_name) LIKE LOWER('%$customerQuery%') LIMIT 5"; // case-insensitive search

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

        if ($result) {
            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    $suggestions .= "<div class='dropdown-item select-customer'>" . htmlspecialchars($row['customer_name']) . "</div>";
                }
            } else {
                $suggestions = "<div class='dropdown-item text-danger'>No customers found</div>";
            }
        } else {
            echo "<div class='dropdown-item text-danger'>Error fetching customers: " . $connection->error . "</div>";
        }

        echo $suggestions;
        exit;
    }

    if (isset($_GET['productQuery']) && isset($_GET['customer_name2'])) {
        $productQuery = $connection->real_escape_string($_GET['productQuery']);
        $customerName2 = $connection->real_escape_string($_GET['customer_name2']);

        $sql = "
            SELECT DISTINCT product_name, product_price, order_id  
            FROM log_user_sales 
            WHERE LOWER(customer_name) = LOWER('$customerName2') 
            AND LOWER(product_name) LIKE LOWER('%$productQuery%') 
            LIMIT 5
        ";

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

        if ($result) {
            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    $suggestions .= "<div class='dropdown-item select-product'>" . htmlspecialchars($row['product_name']) . "</div>";
                }
            } else {
                $suggestions = "<div class='dropdown-item text-danger'>No products found for this customer</div>";
            }
        } else {
            echo "<div class='dropdown-item text-danger'>Error fetching products: " . $connection->error . "</div>";
        }

        echo $suggestions;
        exit;
    }

    if (isset($_GET['productInput2']) && isset($_GET['customer_name2'])) {
    $productName = $connection->real_escape_string($_GET['productInput2']);
    $customerName2 = $connection->real_escape_string($_GET['customer_name2']);

    $sql = "
        SELECT product_name, product_price, order_id 
        FROM log_user_sales 
        WHERE LOWER(customer_name) = LOWER('$customerName2') 
        AND LOWER(product_name) = LOWER('$productName')
        LIMIT 1
    ";

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

    if ($result) {
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $productDetails .= "<tr><td>" . htmlspecialchars($row['order_id']) . "</td><td>" . htmlspecialchars($row['product_name']) . "</td><td>" . htmlspecialchars($row['product_price']) . "</td></tr>";
            }
        } else {
            $productDetails = "<tr><td colspan='3'>No product details found</td></tr>";
        }
    } else {
        $productDetails = "<tr><td colspan='3'>Error fetching product details: " . $connection->error . "</td></tr>";
    }

    echo $productDetails;
    exit;
}

}


if (isset($_GET['order_id'])) {
   

    // Get the search term
    $order_id = $_GET['order_id'];

    if (!empty($order_id)) {
        // Query to search for order_ids in the log_user_sales table
        $stmt = $connection->prepare("SELECT order_id FROM log_user_sales WHERE order_id LIKE ? GROUP BY order_id");
        $like_order_id = "%" . $order_id . "%";
        $stmt->bind_param("s", $like_order_id);
        $stmt->execute();
        $result = $stmt->get_result();

        // Generate HTML output
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                echo '<div class="dropdown-item" data-order-id="' . $row['order_id'] . '">Order #' . $row['order_id'] . '</div>';
            }
        } else {
            echo '<div class="dropdown-item">No orders found</div>';
        }

        $stmt->close();
    }

    $connection->close();
    exit; // End the PHP processing for AJAX request here
}

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

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

    $productData = json_decode($_POST['productData'], true);
    $orderId = uniqid("ORDER");
    $paidBy = $_POST['method'];
    $discount_amount = $_POST["bill_amount"];
    $discounted = $_POST["discount_amount"];
    $discount_per = $_POST["discount_percent"];
    $cash_amount = $_POST["cash_received"] ?? 0;
    $change_amount = $_POST["cash_return"] ?? 0;
    $customerName = $_POST["customer_name"];
    $customerPhone = $_POST["customer_phone"];
    $customer_type = $_POST["customer_type"];
    $stax = $_POST["stax"];
    $total_input = $_POST["total_input"];
    $tax_amount = (int)$total_amount / 100 * (int)$stax; 
    $customer_type = $_POST["customer_type"];
    $customer_id = $_POST["customer_id"];
	$r_order_id = $_POST["r_order_id"];
    $date_time = date("Y-m-d");

    foreach ($productData as $product) {
        $productId = $product['productId'];
        $productName = $product['description'];
        $productPrice = $product['pricePerUnit'];
        $nPrice = $product['nPerUnit'];
        $tradePrice = $product['tradePrice'];
        $productQuantity = $product['quantity'];
        $productTotal = $product['totalPrice'];
        $discount = $product['discountPercentage'];
        $tax = $product['tax'];
        $saleT = $product['tax'];
        $sku = $product['productUnit'];
        $batchNo = $product['BatchNo'];
        $Exp = $product['EXp'];
        $netAmount = $product['netAmount'];
        $supplierName = $product['supplier'];
        $company = $product['company'];
        $sale_cost = $tradePrice * $productQuantity;
		$tp = $sale_cost;
        $sql = "INSERT INTO log_user_sales (
            product_id,
            supplier_name,
            company,
            product_name,
            product_price,
            n_price,
            trade_price,
            product_quantity,
            product_total,
            product_unit,
            bonus,
            discount,
            tax,
            net_amount,
            stax,
            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,
			status,
			batch_no,
			expiry,
			sale_tax,
            outlet_name,
            login_user,
            user_role,
            outlet_address,
            date_time
        ) VALUES (
            '$productId',
            '$supplierName',
            '$company',
            '$productName',
            '$productPrice',
            '$nPrice',
            '$tradePrice',
            '$productQuantity',
            '$productTotal',
            '$sku',
            '',
            '$discount',
            '$tax',
            '$netAmount',
            '$stax',
            '$tax_amount',
            '$productTotal',
            '$paidBy',
            '$sale_cost',
            '$customer_id',
            '$customer_type',
            '$customerName',
            '$customerPhone',
            '$discount_amount',
            '$discounted',
            '$discount_per',
            '$cash_amount',
            '$change_amount',
            '$orderId',
			'$r_order_id',
			'',
			'$batchNo',
			'$Exp',
			'$saleT',
            '$outlet',
            '$user',
            '$role',
            '$address',
            '$date_time'
        )";
        
        if ($connection->query($sql) !== TRUE) {
            echo "Error: " . $sql . "<br>" . $connection->error;
            ob_end_flush();
            exit;
        }
 // Update product quantity based on payment type
            
                $updateSql = "UPDATE products SET total_quantity = total_quantity - $productQuantity, total_amount = total_amount - $tp  WHERE product_id = '$productId'";
          
            if ($connection->query($updateSql) !== TRUE) {
                throw new Exception("Error updating product quantity: " . $connection->error);
            }
        }

    ob_end_clean();
    echo "<script type='text/javascript'>window.location.href = 'printtype.php?order_id=$orderId';</script>";
}




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

    $productData = json_decode($_POST['productData'], true);
    $paidBy = $_POST["method"];
    $status = 'Refund';
    $discount_amount = $_POST["bill_amount"];
    $discounted = $_POST["discount_amount"];
    $discount_per = $_POST["discount_percent"];
    $cash_amount = $_POST["cash_received"] ?? 0;
    $change_amount = $_POST["cash_return"] ?? 0;
    $customerName = $_POST["customer_name"];
    $customerPhone = $_POST["customer_phone"];
    $customer_type = $_POST["customer_type"];
    $customer_id = $_POST["customer_id"];
    $r_order_id = $_POST["r_order_id"];
    $date_time = date("Y-m-d");
    $orderId = $r_order_id;

    foreach ($productData as $product) {
        $productId = $product['productId'];
        $productName = $product['description'];
        $productPrice = $product['pricePerUnit'];
        $tradePrice = $product['tradePrice'];
        $productQuantity = $product['quantity'];
        $productTotal = $product['totalPrice'];
        $discount = $product['discountPercentage'];
        $tax = $product['tax'];
        $sku = $product['productUnit'];
        $saleT = $product['tax'];
        $batchNo = $product['BatchNo'];
        $Exp = $product['EXp'];
        $netAmount = $product['netAmount'];
        $supplierName = $product['supplier'];
        $company = $product['company'];
        
        // Calculate the sale cost to add to total_amount on refund
        $refundAmount = $tradePrice * $productQuantity; // Total amount for the refund

        // Insert refund entry 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,
            product_unit,
            bonus,
            discount,
            tax,
            net_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,
            status,
            batch_no,
            expiry,
            sale_tax,
            outlet_name,
            login_user,
            user_role,
            outlet_address,
            date_time
        ) VALUES (
            '$productId',
            '$supplierName',
            '$company',
            '$productName',
            '$productPrice',
            '$tradePrice',
            '-$productQuantity', /* Negative quantity for logging refund in log_user_sales */
            '$productTotal',
            '$sku',
            '',
            '$discount',
            '$tax',
            '$netAmount',
            '$productTotal',
            '$paidBy',
            '$refundAmount',
            '$customer_id',
            '$customer_type',
            '$customerName',
            '$customerPhone',
            '$discount_amount',
            '$discounted',
            '$discount_per',
            '$cash_amount',
            '$change_amount',
            '$orderId',
            '$r_order_id',
            '$status',
            '$batchNo',
            '$Exp',
            '$saleT',
            '$outlet',
            '$user',
            '$role',
            '$address',
            '$date_time'
        )";

        if ($connection->query($sql) !== TRUE) {
            echo "Error: " . $sql . "<br>" . $connection->error;
            ob_end_flush();
            exit;
        }

        // Update the products table to increase both quantity and total_amount for the refund
        $updateSql = "UPDATE products 
                      SET total_quantity = total_quantity + $productQuantity, 
                          total_amount = total_amount + $refundAmount 
                      WHERE product_id = '$productId'";

        if ($connection->query($updateSql) !== TRUE) {
            throw new Exception("Error updating product quantity: " . $connection->error);
        }
    }

    ob_end_clean();
    echo "<script type='text/javascript'>window.location.href = 'mainpos.php';</script>";
}



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

    $productData = json_decode($_POST['productData'], true);
    $orderId = uniqid("ORDER");
    $paidBy = $_POST['method'];
    $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"];
	$r_order_id = $_POST["r_order_id"];
    $date_time = date("Y-m-d");

    foreach ($productData as $product) {
        $productId = $product['productId'];
        $productName = $product['description'];
        $productPrice = $product['pricePerUnit'];
        $tradePrice = $product['tradePrice'];
        $productQuantity = $product['quantity'];
        $productTotal = $product['totalPrice'];
        $discount = $product['discountPercentage'];
        $tax = $product['tax'];
        $netAmount = $product['netAmount'];
        $supplierName = $product['supplier'];
        $company = $product['company'];
        $sale_cost = (int)$tradePrice * (int)$productQuantity;
       
        $sql = "INSERT INTO pay_hold (
            product_id,
            supplier_name,
            company,
            product_name,
            product_price,
            trade_price,
            product_quantity,
            product_total,
            bonus,
            discount,
            tax,
            net_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,
            outlet_name,
            login_user,
            user_role,
            outlet_address,
            date_time
        ) VALUES (
            '$productId',
            '$supplierName',
            '$company',
            '$productName',
            '$productPrice',
            '$tradePrice',
            '$productQuantity',
            '$productTotal',
            '',
            '$discount',
            '$tax',
            '$netAmount',
            '$productTotal',
            '$paidBy',
            '$sale_cost',
            '$customer_id',
            '$customer_type',
            '$customerName',
            '$customerPhone',
            '$discount_amount',
            '$discounted',
            '$discount_per',
            '$cash_amount',
            '$change_amount',
            '$orderId',
            '$outlet',
            '$user',
            '$role',
            '$address',
            '$date_time'
        )";
        
        if ($connection->query($sql) !== TRUE) {
            echo "Error: " . $sql . "<br>" . $connection->error;
            ob_end_flush();
            exit;
        }
            
        }
   
    ob_end_clean();
    echo "<script type='text/javascript'>window.location.href = 'mainpos.php';</script>";
}



ob_end_flush();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Irfan Traders</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">
     <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
     <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
    body {
    font-family: 'Quicksand', sans-serif;
    
}
    
    
 #table-container-wrapper {
    max-height: 390px; 
    overflow-y: auto; 
}
        .bg {
            background: linear-gradient(270deg, #060606, #0A4657);
        }
        .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;
            display:
        }
        .dropdown-menu {
            max-height: 200px;
            overflow-y: auto;
            position: absolute;
            z-index: 1000;
            width: 100%;
        }
        .input-group {
            position: relative;
        }
		.dropdown-item.active, .dropdown-item:active {
    color: #fff;
    text-decoration: none;
    background-color: #0A5064;
}

.form-control{
    font-weight:700;
}
.btn{
    font-weight:700;
}
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row bg">
        <div class="col-sm-3 " style="width:100%; height:69px;">
            <img src="../img/if.png" style="margin-top:5px;" width="70" height="70">
        </div>
        <div class="col-sm-6">
        <h3 class="mb-4" style="color:#fff; font-weight:700; text-align:center; text-transform:uppercase;line-height:60px;">
            Irfan Traders</h3>
        
        </div>
        <div class="col-sm-3">
            <a href="addproduct.php" class="btn btn-light" style="margin-top:20px; float:right;" >Back</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..." autocomplete="off">
        <div class="dropdown-menu" id="suggestions"></div>
    </div>

    <!-- New Item Code Input for Search -->
    <div class="input-group mb-3">
        <div class="input-group-prepend">
            <span class="input-group-text bg-dark text-white">Item Code</span>
        </div>
        <input type="text" class="form-control" id="productInputCode" placeholder="Start typing an item code..." autocomplete="off">
        <div class="dropdown-menu" id="codeSuggestions"></div>
    </div>
                <hr>
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">Batch No.</span>
                    </div>
                    <input type="text" id="batch_no" name="batch_no" class="form-control" placeholder="" style="font-weight:700;">
                </div>
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">Expiry</span>
                    </div>
                    <input type="date" id="expiry" name="expiry" class="form-control" placeholder="" style="font-weight:700;" >
                </div>
                <div class="row">
                <div class="input-group mb-3 col-6">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">Carton</span>
                    </div>
                    <input type="text" id="carton" name="carton" class="form-control" placeholder="" style="font-weight:700;" >
                </div>
                <div class="input-group mb-3 col-6">
                    
                    <input type="text" id="box" name="box" class="form-control" placeholder="" style="font-weight:700;" >
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">Box</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="">
                </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="" readonly>
                </div>
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">N.Price</span>
                    </div>
                    <input type="text" id="n_price" name="n_price" 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">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 PKR</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">S.Tax %</span>
                    </div>
                    <input type="text" id="sale_tax" name="sale_tax" class="form-control"  placeholder="" style="font-weight:700;">
                </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>
                <h3 class="text-center" style="font-size:18px; font-weight:700; padding:13px; width:100%; background:#0A4657;color:#fff;">History</h3>
                 <div class="form-group position-relative">
        <label for="customer_name2">Customer Name:</label>
        <input type="text" id="customer_name2" class="form-control" placeholder="Type customer name..." style="font-weight:700; color:#000;">
        <div id="customerSuggestions" class="dropdown-menu"></div>
    </div>

    <!-- Product Input -->
    <div class="form-group position-relative">
        <label for="productInput2">Product Name:</label>
        <input type="text" id="productInput2" class="form-control" placeholder="Type product name..." style="font-weight:700; color:#000;">
        <div id="productSuggestions" class="dropdown-menu"></div>
    </div>

    <!-- Product Details Table -->
    <table class="table table-bordered mt-4 text-center bg-white">
        <thead>
        <tr class="bg-dark text-white">
            <th>Order ID</th>
            <th>Product</th>
            <th>Price</th>
        </tr>
        </thead>
        <tbody id="productTableBody"></tbody>
    </table>
                
                <!--<a href="view_hold.php"><button type="button" class="form-control btn btn-dark" >View Hold Bill</button></a>
                <hr>
                <button type="button" class="form-control btn btn-dark" onclick="location.reload();">Refresh</button>-->
                  
            </div>
            <?php
            $b = mysqli_query($connection,"select * from booker");
            ?>
            <div class="col-sm-9">
                <div class="row" style="background:#F0F0F0; padding:10px; border:1px solid #CCC;">
                    <div class="col-sm-2">
                        <div class="form-group">
                         <label>Booker</label>
                            <select style="font-weight:700;" class="form-control in_form" name="customer_type">
                            <option value="">Select</option>
                            <?php
                            while($br = mysqli_fetch_array($b)){
                            ?>
                            <option valu="<?php echo $br["name"];?>"><?php echo $br["name"]; ?></option>
                            <?php
                            }
                            ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-sm-2">
                        <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-2">
                        <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-2">
                        <div class="form-group">
                            <label>Customer Address</label>
                            <input type="text" id="customer_id" name="customer_id" class="form-control in_form">
                        </div>
                    </div>
                     <div class="col-sm-2">
    <div class="form-group">
        <label>Refund ID</label>
        <input type="text" id="r_order_id" name="r_order_id" class="form-control in_form">
        <div id="order_suggestions" class="dropdown-menu" style="display: none;"></div>
    </div>
</div>
                </div>
                <div class="row" style="background:#fff; padding:10px; border:1px solid #CCC;">
                    <div class="col-sm-12" style="height:780px;">
                        <table class="table table-borderless table-sm text-center" id="productsTable">
                             <tr class="text-white text-center" style="background:#0A4657;font-weight:700;">
                                <td>R.Qty</td>
                                <td>Item Code</td>
                                <td>Description</td>
                                <td>Batch No.</td>
                                <td>Carton</td>
                                <td>Box</td>
                                <td>Qty</td>
                                <td>Unit Price</td>
                                <td>New Price</td>
                                <td>Amount</td>
                                <td>% Dis</td>
                                <td>Tax</td>
                                <td>Exp</td>
                                <td>SKU</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>S.Tax(0%)</label>
                                    <input type="number" id="stax" name="stax" class="form-control in_form input-height"  >
                                </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="">
                                <div class="">
                          
                                    <input type="hidden"  id="cash_received" name="cash_received" step="0.01" class="form-control in_form input-height">
                                </div>
                            </div>
                            <div class="">
                                <div class="">
                                  
                                    <input type="hidden" id="cash_return" name="cash_return" step="0.01" class="form-control in_form input-height">
                                </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 value="credit">Credit</option>
                                        <option value="cash">Cash</option>
                                        
                                        <option value="bank1">Bank 1</option>
                                    <option value="bank2">Bank 2 </option>
                                    <option value="bank3">Bank 3</option>
                                       
                                        <option value="others">Others</option>
                                    </select>
                                </div>
                            </div>
                            <input type="hidden" id="productData" name="productData">
                            <div class="col-sm-5">
                                <hr>
                                <button type="submit" name="bill" class="btn btn-dark btn-sm">Generate Invoice</button>
                                <!--<button type="submit" name="hold" class="btn btn-success btn-sm">Hold Bill</button>-->
                                <button type="submit" name="refund" class="btn btn-danger btn-sm">Refund</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<script>
document.addEventListener("DOMContentLoaded", function () {
    let cartonInput = document.getElementById("carton");
    let boxInput = document.getElementById("box");
    let productInput = document.getElementById("productInput");
    let productInputCode = document.getElementById("productInputCode");

    function getProductUnit() {
        return parseFloat(productInput.getAttribute("data-product-unit")) || 
               parseFloat(productInputCode.getAttribute("data-product-unit")) || 1;
    }

    function updateBoxFromCarton() {
        let productUnit = getProductUnit();
        let cartonValue = parseFloat(cartonInput.value) || 0;
        boxInput.value = (cartonValue * productUnit).toFixed(0); // Round to whole number
    }

    function updateCartonFromBox() {
        let productUnit = getProductUnit();
        let boxValue = parseFloat(boxInput.value) || 0;
        cartonInput.value = (boxValue / productUnit).toFixed(2); // Keep two decimal places
    }

    cartonInput.addEventListener("input", updateBoxFromCarton);
    boxInput.addEventListener("input", updateCartonFromBox);
});


</script>
<script>
$(document).ready(function () {
    // Live Search for Customer
    $('#customer_name2').on('input', function () {
        let customerQuery = $(this).val();
        if (customerQuery.length > 1) {
            $.ajax({
                url: '',
                method: 'GET',
                data: { customerQuery: customerQuery },
                success: function (response) {
                    if (response.trim() !== "") {
                        $('#customerSuggestions').html(response).show();
                    } else {
                        $('#customerSuggestions').hide();
                    }
                },
                error: function () {
                    $('#customerSuggestions').html('<div class="dropdown-item text-danger">Error fetching results</div>').show();
                }
            });
        } else {
            $('#customerSuggestions').hide();
        }
    });

    // Select Customer
    $(document).on('click', '.select-customer', function () {
        $('#customer_name2').val($(this).text());
        $('#customerSuggestions').hide();
    });

    // Live Search for Product
    $('#productInput2').on('input', function () {
        let productQuery = $(this).val();
        let customerName = $('#customer_name2').val();

        if (customerName === "") {
            alert('Please select a customer first!');
            return;
        }

        if (productQuery.length > 1) {
            $.ajax({
                url: '',
                method: 'GET',
                data: { productQuery: productQuery, customer_name2: customerName },
                success: function (response) {
                    if (response.trim() !== "") {
                        $('#productSuggestions').html(response).show();
                    } else {
                        $('#productSuggestions').hide();
                    }
                },
                error: function () {
                    $('#productSuggestions').html('<div class="dropdown-item text-danger">Error fetching results</div>').show();
                }
            });
        } else {
            $('#productSuggestions').hide();
        }
    });

    // Select Product
$(document).on('click', '.select-product', function () {
    $('#productInput2').val($(this).text());
    $('#productSuggestions').hide();
    let productName = $(this).text();
    let customerName = $('#customer_name2').val();

    $.ajax({
        url: '', // Ensure your PHP script is properly loaded
        method: 'GET',
        data: { productInput2: productName, customer_name2: customerName },
        success: function (response) {
            $('#productTableBody').html(response); // Update table body with product details
        },
        error: function () {
            $('#productTableBody').html('<tr><td colspan="2">Error fetching product details</td></tr>');
        }
    });
});

    // Hide dropdowns when clicking outside
    $(document).click(function (event) {
        if (!$(event.target).closest('.form-group').length) {
            $('.dropdown-menu').hide();
        }
    });
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    const generateInvoiceButton = document.querySelector("button[name='bill']");
    const refundButton = document.querySelector("button[name='refund']");

    generateInvoiceButton.addEventListener("click", function(event) {
        const method = document.getElementById("method").value;
        const customerName = document.getElementById("customer_name").value.trim();

        // Check if method is "credit" and customer name is empty
        if (method === "credit" && customerName === "") {
            event.preventDefault();  // Prevent form submission
            alert("Please fill in the Customer Name for Credit method.");
        }
    });

    refundButton.addEventListener("click", function(event) {
        const refundId = document.getElementById("r_order_id").value.trim();

        // Check if Refund ID is empty when "Refund" button is clicked
        if (refundId === "") {
            event.preventDefault();  // Prevent form submission
            alert("Please enter a Refund ID.");
        }
    });
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    let currentFocus = -1;

   
    // Event listener for input field to trigger AJAX request
    document.getElementById("r_order_id").addEventListener("input", function() {
        var orderIdInput = this.value;
        if (orderIdInput.length > 0) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "?order_id=" + encodeURIComponent(orderIdInput), true); // Sends request to the same page
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var suggestions = document.getElementById("order_suggestions");
                    suggestions.innerHTML = xhr.responseText;
                    suggestions.style.display = 'block';
                }
            };
            xhr.send();
        } else {
            document.getElementById("order_suggestions").style.display = 'none';
        }
    });

    // Handle clicking on suggestion items
    document.getElementById("order_suggestions").addEventListener("click", function(e) {
        if (e.target && e.target.classList.contains("dropdown-item")) {
            selectOrder(e.target);
        }
    });

    // Add keyboard navigation for dropdown items
    document.getElementById("r_order_id").addEventListener("keydown", function(e) {
        var suggestions = document.getElementById("order_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]) {
                        selectOrder(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 selectOrder(item) {
        var orderId = item.getAttribute('data-order-id');
        document.getElementById("r_order_id").value = orderId;
        document.getElementById("order_suggestions").style.display = 'none';
    }

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

function calculateTotalPrice() {
    // Get values from the form
    let carton = parseFloat(document.getElementById("carton").value) || 0;
    let box = parseFloat(document.getElementById("box").value) || 0;
    let pricePerUnit = parseFloat(document.getElementById("retail_price").value) || 0;
    let discountPercentage = parseFloat(document.getElementById("percentage").value) || 0; // Discount percentage
    let saleTaxPercentage = parseFloat(document.getElementById("sale_tax").value) || 0; // Sales tax percentage

    // Calculate quantity from carton and box
    let quantity =  box;
    document.getElementById("quantity").value = quantity;

     // Subtract the discount amount from price per unit
    let discountedPricePerUnit = pricePerUnit - discountPercentage;

    // Ensure discounted price per unit is not negative
    if (discountedPricePerUnit < 0) {
        discountedPricePerUnit = 0;
    }

    // Update the retail price with the discounted price
    document.getElementById("n_price").value = discountedPricePerUnit.toFixed(2);

    // Calculate the total price using the discounted price per unit
    let totalPrice = quantity * discountedPricePerUnit;

    // Calculate sales tax on the discounted total price
    let saleTaxAmount = (totalPrice * saleTaxPercentage) / 100;

    // Final trade price after applying sales tax
    let finalPrice = totalPrice + saleTaxAmount;

    // Update the form with the calculated prices
    document.getElementById("total_amount").value = totalPrice.toFixed(2);
    document.getElementById("trade_price").value = finalPrice.toFixed(2);
}

// Event listeners for input fields
document.getElementById("carton").addEventListener("input", calculateTotalPrice);
document.getElementById("box").addEventListener("input", calculateTotalPrice);
document.getElementById("quantity").addEventListener("input", calculateTotalPrice);
document.getElementById("retail_price").addEventListener("input", calculateTotalPrice);
document.getElementById("percentage").addEventListener("input", calculateTotalPrice); // Apply percentage discount
document.getElementById("sale_tax").addEventListener("input", calculateTotalPrice);



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

// Search by Product Name
document.getElementById("productInput").addEventListener("input", function() {
    searchProduct(this.value, 'product');
});

// Search by Item Code
document.getElementById("productInputCode").addEventListener("input", function() {
    searchProduct(this.value, 'code');
});

// Common search function for both Product Name and Item Code
function searchProduct(query, type) {
    if (query.length > 0) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "?query=" + query + "&type=" + type, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var suggestions = type === 'product' ? document.getElementById("suggestions") : document.getElementById("codeSuggestions");
                suggestions.innerHTML = xhr.responseText;
                suggestions.style.display = 'block';
            }
        };
        xhr.send();
    } else {
        var suggestions = type === 'product' ? document.getElementById("suggestions") : document.getElementById("codeSuggestions");
        suggestions.style.display = 'none';
    }
}

// Same function to handle arrow key navigation and selection logic for both inputs
document.getElementById("productInput").addEventListener("keydown", handleKeyDown);
document.getElementById("productInputCode").addEventListener("keydown", handleKeyDown);

function handleKeyDown(e) {
    var suggestions = e.target.id === 'productInput' ? document.getElementById("suggestions") : document.getElementById("codeSuggestions");
    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]) {
                    selectProduct(items[currentFocus], e.target.id);
                }
            }
        }
    }
}

function selectProduct(item, inputId) {
    var selectedProduct = item.textContent;
    var retailPrice = item.getAttribute('data-retail-price');
    var productQuantity = item.getAttribute('data-product-quantity');
    var productUnit = item.getAttribute('data-product-unit');
    var tradePrice = item.getAttribute('data-trade-price');
    var productId = item.getAttribute('data-product-id');
    var supplier = item.getAttribute('data-supplier');
    var company = item.getAttribute('data-company');

    var inputElement = document.getElementById(inputId);

    // Set values to product input fields
    inputElement.value = selectedProduct;
    document.getElementById("retail_price").value = retailPrice;
    inputElement.setAttribute('data-product-id', productId);
    inputElement.setAttribute('data-product-quantity', productQuantity);
    inputElement.setAttribute('data-supplier', supplier);
    inputElement.setAttribute('data-company', company);
    inputElement.setAttribute('data-trade-price', tradePrice);
    inputElement.setAttribute('data-product-unit', productUnit);

    // Hide suggestions dropdown
    document.getElementById("suggestions").style.display = 'none';
    document.getElementById("codeSuggestions").style.display = 'none';

    calculateTotalPrice();
}

// Functions to add and remove active class
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");
    }
}


 document.getElementById("makeEntry").addEventListener("click", function() {
    // Check both productInput and productInputCode for the required attributes
    var productInput = document.getElementById("productInput");
    var productInputCode = document.getElementById("productInputCode");

    // Determine which input was used to select the product
    var productElement = productInput.getAttribute('data-product-id') ? productInput : productInputCode;

    // Retrieve product details
    var productId = productElement.getAttribute('data-product-id');
    var productUnit = productElement.getAttribute('data-product-unit');
    var productQuantity = productElement.getAttribute('data-product-quantity');   // Parse the quantity and ensure it's a number
    var supplier = productElement.getAttribute('data-supplier');
    var company = productElement.getAttribute('data-company');
    var description = productElement.value;

    // Retrieve values from the form
    var quantity = parseFloat(document.getElementById("quantity").value) || 0;
    var pricePerUnit = parseFloat(document.getElementById("retail_price").value) || 0;
    var nPerUnit = parseFloat(document.getElementById("n_price").value) || 0;
    var Carton = parseFloat(document.getElementById("carton").value) || 0;
    var Box = parseFloat(document.getElementById("box").value) || 0;
    var EXp = document.getElementById("expiry").value || 0;
    var Stax = parseFloat(document.getElementById("sale_tax").value) || 0;
    var BatchNo = document.getElementById("batch_no").value || 0;
    var totalPrice = parseFloat(document.getElementById("total_amount").value) || 0;
    var discountPercentage = parseFloat(document.getElementById("percentage").value) || 0;
    var netAmount = parseFloat(document.getElementById("trade_price").value) || 0;
    var tradePrice = productElement.getAttribute('data-trade-price');

    // Check if quantity is zero or negative before making the entry
    if (quantity <= 0) {
        alert("Product is not in stock. Cannot add entry.");
        return; // Stop execution if quantity is zero or negative
    }

    // Ensure the required fields are available for entry
    if (productId && description && quantity && pricePerUnit && totalPrice && netAmount) {
        var table = document.getElementById("productsTable");
        var row = table.insertRow();
        row.innerHTML = `
            <td style="font-weight:700;">${productQuantity}</td>
            <td style="font-weight:700;">${productId}</td>
            <td style="color:#0A5064;font-weight:700;">${description}</td>
            <td style="font-weight:700;">${BatchNo}</td>
            <td style="font-weight:700;">${Carton}</td>
            <td style="font-weight:700;">${Box}</td>
            <td style="font-weight:700;">${quantity}</td>
            <td style="font-weight:700;">${pricePerUnit}</td>
            <td style="font-weight:700;">${nPerUnit}</td>
            <td style="font-weight:700;">${totalPrice}</td>
            <td style="font-weight:700;">${discountPercentage || '0.00'}</td>
            <td style="font-weight:700;">${Stax || '0.00'}</td>
            <td style="font-weight:700;">${EXp || '0.00'}</td>
            <td style="font-weight:700;text-transform:capitalize;">${productUnit || '0.00'}</td>
            <td style="font-weight:700;">${netAmount}</td>
            <td style="display:none;">${supplier}</td>
            <td style="display:none;">${company}</td>
            <td style="display:none;">${tradePrice}</td>
            <td><button class="btn btn-danger btn-sm delete-row">X</button></td>
        `;

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

        calculateTotalAmount();

        // Collect all the rows' data for the final submission
        var rows = document.querySelectorAll("#productsTable tr:not(:first-child)");
        var productData = [];
        rows.forEach(function(row) {
            var cells = row.querySelectorAll("td");
            var product = {
                productId: cells[1].innerText,
                description: cells[2].innerText,
                BatchNo: cells[3].innerText,
                Carton: cells[4].innerText,
                Box: cells[5].innerText,
                quantity: cells[6].innerText,
                pricePerUnit: cells[7].innerText,
                nPerUnit: cells[8].innerText,
                totalPrice: cells[9].innerText,
                discountPercentage: cells[10].innerText,
                tax: cells[11].innerText,
                EXp: cells[12].innerText,
                productUnit: cells[12].innerText,
                netAmount: cells[14].innerText,
                supplier: cells[15].innerText,
                company: cells[16].innerText,
                tradePrice: cells[17].innerText
            };
            productData.push(product);
        });

        document.getElementById("productData").value = JSON.stringify(productData);

        // Reset product fields after making an entry
        resetProductFields();
        
        // Automatically focus back to the productInput field
        productInput.focus();
        
    } else {
        alert("Some required fields are missing. Please select a product and fill all fields.");
    }
});

    function resetProductFields() {
        document.getElementById("productInput").value = '';
        document.getElementById("productInputCode").value = '';
        document.getElementById("quantity").value = '';
        document.getElementById("retail_price").value = '';
        document.getElementById("total_amount").value = '';
        document.getElementById("percentage").value = '';
        document.getElementById("trade_price").value = '';
        document.getElementById("sale_tax").value = '';
        document.getElementById("batch_no").value = '';
         document.getElementById("expiry").value = '';
         document.getElementById("carton").value = '';
         document.getElementById("box").value = '';
         document.getElementById("n_price").value = '';

        // Remove data attributes for the next product
        document.getElementById("productInput").removeAttribute('data-product-id');
        document.getElementById("productInput").removeAttribute('data-product-quantity');
        document.getElementById("productInput").removeAttribute('data-supplier');
        document.getElementById("productInput").removeAttribute('data-company');
        document.getElementById("productInput").removeAttribute('data-trade-price');
        document.getElementById("productInput").removeAttribute('data-product-unit');
    }

function calculateTotalAmount() {
    var table = document.getElementById("productsTable");
    var rows = table.getElementsByTagName("tr");
    var total = 0;

    for (var i = 1; i < rows.length; i++) {
        var netAmountCell = rows[i].cells[14];
        var netAmount = parseFloat(netAmountCell.textContent.trim());
        if (!isNaN(netAmount)) {
            total += netAmount;
        }
    }

    var totalInput = document.getElementById("total-input");
    var billAmountInput = document.getElementById("bill-amount");

    totalInput.value = total.toFixed(2);
    billAmountInput.value = total.toFixed(2); // Auto-reflect in bill-amount

    updateBillAmountWithTax(); // Apply tax on initial calculation
}

function updateBillAmountWithTax() {
    var total = parseFloat(document.getElementById("total-input").value) || 0;
    var stax = parseFloat(document.getElementById("stax").value) || 0;
    var billAmountInput = document.getElementById("bill-amount");

    // Calculate tax amount
    var taxAmount = (total * stax) / 100;
    var updatedBillAmount = total + taxAmount;

    billAmountInput.value = updatedBillAmount.toFixed(2);

    updateDiscountAmount(); // Update discount calculations
}

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

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

document.getElementById("cash_received").addEventListener("input", function() {
    calculateCashReturn();
});

// Listen for changes in S.Tax and update bill-amount
document.getElementById("stax").addEventListener("input", function() {
    updateBillAmountWithTax();
});

calculateTotalAmount();

});
</script>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</body>
</html>