<?php
include("../db/cn.php");
include("common/tx.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ob_start();

// Add batch_no column if not exists in products table
$check_column3 = $connection->query("SHOW COLUMNS FROM products LIKE 'batch_no'");
if ($check_column3->num_rows == 0) {
    $connection->query("ALTER TABLE products ADD batch_no VARCHAR(100) DEFAULT ''");
}
$check_column4 = $connection->query("SHOW COLUMNS FROM purchase LIKE 'batch_no'");
if ($check_column4->num_rows == 0) {
    $connection->query("ALTER TABLE purchase ADD batch_no VARCHAR(100) DEFAULT ''");
}

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

// AJAX: product search - returns product names only
if (isset($_GET['query'])) {
    $query = $connection->real_escape_string($_GET['query']);
    $sql = "SELECT DISTINCT product_name FROM products WHERE product_name LIKE '%$query%' ORDER BY product_name LIMIT 20";
    $result = $connection->query($sql);
    $suggestions = "";
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $productName = $row['product_name'];
            $suggestions .= "<div class='dropdown-item product-name-item' data-product-name='" . htmlspecialchars($productName) . "'>" . htmlspecialchars($productName) . "</div>";
        }
    } else {
        $suggestions .= "<div class='dropdown-item text-danger'>No products found</div>";
    }
    echo $suggestions;
    exit;
}

// AJAX: Get batches for a selected product
if (isset($_GET['get_batches'])) {
    $productName = $connection->real_escape_string($_GET['get_batches']);
    $sql = "SELECT product_id, product_name, retail_price, trade_price, supplier, category, company, product_unit, quantity, inches, batch_no 
            FROM products 
            WHERE product_name = '$productName' AND quantity >= 0
            ORDER BY batch_no";
    $result = $connection->query($sql);
    $batches = "";
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $batchNo = $row['batch_no'] ?: 'No Batch';
            $quantity = $row['quantity'];
            $batches .= "<div class='batch-item' 
                data-product-id='" . $row['product_id'] . "' 
                data-category='" . $row['category'] . "' 
                data-product-quantity='" . $row['quantity'] . "' 
                data-retail-price='" . $row['retail_price'] . "' 
                data-trade-price='" . $row['trade_price'] . "' 
                data-supplier='" . $row['supplier'] . "' 
                data-company='" . $row['company'] . "' 
                data-product-unit='" . $row['product_unit'] . "' 
                data-batch-no='" . $row['batch_no'] . "' 
                data-inches='" . ($row['inches'] ?? 1) . "'
                data-product-name='" . $row['product_name'] . "'>" 
                . "<div class='batch-info'><strong>Batch: " . htmlspecialchars($batchNo) . "</strong></div>"
                . "<div class='batch-qty'>Available: " . $quantity . " units</div></div>";
        }
    } else {
        $batches .= "<div class='no-batches'>No batches available for this product</div>";
    }
    echo $batches;
    exit;
}

// AJAX: customer search
if (isset($_GET['customer_name'])) {
    $customerName = $connection->real_escape_string($_GET['customer_name']);
    $sql = "SELECT supplier_name, supplier_id, supplier_phone FROM supplier WHERE supplier_name LIKE '%$customerName%' LIMIT 5";
    $result = $connection->query($sql);
    $suggestions = "";

    while ($row = $result->fetch_assoc()) {
        $crName = $row['supplier_name'];
        $crId = $row['supplier_id'];
        $phone = $row['supplier_phone'];

        $remainSql = "SELECT closing_balance FROM supplier_closing WHERE supplier_name = '$crName' ORDER BY id DESC LIMIT 1";
        $remainResult = $connection->query($remainSql);
        $remainBalance = "0";
        if ($remainResult && $remainResult->num_rows > 0) {
            $remainRow = $remainResult->fetch_assoc();
            $remainBalance = $remainRow['closing_balance'];
        }

        $suggestions .= "<div class='dropdown-item' data-customer-name='$crName' data-customer-id='$crId' data-customer-phone='$phone' data-remain-balance='$remainBalance'>$crName</div>";
    }

    echo $suggestions;
    exit;
}

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

// AJAX: invoice search
if (isset($_GET['inv_id'])) {
    $order_id = $_GET['inv_id'];
    if (!empty($order_id)) {
        $stmt = $connection->prepare("SELECT inv_id FROM purchase WHERE inv_id LIKE ? GROUP BY inv_id");
        $like_order_id = "%" . $order_id . "%";
        $stmt->bind_param("s", $like_order_id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                echo '<div class="dropdown-item" data-order-id="' . $row['inv_id'] . '">' . $row['inv_id'] . '</div>';
            }
        } else {
            echo '<div class="dropdown-item">No Invoice found</div>';
        }
        $stmt->close();
    }
    $connection->close();
    exit;
}

// Purchase invoice submission (modified to include batch_no)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['inv_bill'])) {
    if ($connection->connect_error) {
        die("Connection failed: " . $connection->connect_error);
    }

    $productData = json_decode($_POST['productData'], true);
    $orderId = 'INV-' . random_int(1000000, 9999999);
    $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"];
    $preAmount = $_POST['pre_amount'];
    $grandAmount = $_POST['grand_amount'];
    $description = $_POST['desc_note'];
    $date_time = date("Y-m-d");

    foreach ($productData as $product) {
        $productId = $product['productId'];
        $productName = $product['description'];
        $productPrice = $product['pricePerUnit'];
        $tradePrice = $product['tradePrice'];
        $category = $product['category'];
        $productQuantity = $product['quantity'];
        $inches = $product['inches'];
        $batch_no = $product['batch_no'] ?? '';
        $productTotal = $product['totalPrice'];
        $discount = $product['discountPercentage'];
        $tax = $product['extraPer'];
        $disAmount = $product['disAmount'];
        $netAmount = $product['netAmount'];
        $supplierName = $product['supplier'];
        $company = $product['company'];
        $retailPPrice = $product['retailPPrice'];
        $sale_cost = $tradePrice * $productQuantity * $inches;
        $tp = ($productTotal / $productQuantity) / $inches;

        $sql = "INSERT INTO purchase (
            product_id,
            supplier_name,
            company,
            category,
            product_name,
            product_price,
            trade_price,
            product_quantity,
            product_total,
            bonus,
            discount,
            dis_amount,
            tax,
            net_amount,
            total_amount,
            pre_amount,
            grand_amount,
            paid_by,
            sale_cost,
            customer_id,
            customer_type,
            customer_name,
            customer_phone,
            discount_amount,
            discounted,
            discount_per,
            cash_amount,
            change_amount,
            inv_id,
            r_inv_id,
            status,
            outlet_name,
            login_user,
            user_role,
            outlet_address,
            date_time,
            desc_note,
            inches,
            batch_no
        ) VALUES (
            '$productId',
            '$supplierName',
            '$company',
            '$category',
            '$productName',
            '$productPrice',
            '$tradePrice',
            '$productQuantity',
            '$productTotal',
            '',
            '$discount',
            '$disAmount',
            '$tax',
            '$netAmount',
            '$productTotal',
            '$preAmount',
            '$grandAmount',
            '$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',
            '$description',
            '$inches',
            '$batch_no'
        )";

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

        // Check if product with same name and batch exists
        $checkSql = "SELECT product_id FROM products WHERE product_name = '$productName' AND batch_no = '$batch_no'";
        $checkResult = $connection->query($checkSql);
        
        if ($checkResult && $checkResult->num_rows > 0) {
            // Update existing product with same batch
            $updateSql = "UPDATE products SET quantity = quantity + $productQuantity, total_amount = total_amount + $netAmount, trade_price = $tp WHERE product_name = '$productName' AND batch_no = '$batch_no'";
        } else {
            // Insert new product with batch
            $updateSql = "INSERT INTO products (product_name, quantity, total_amount, trade_price, batch_no, inches, retail_price, supplier, company, category) 
                         VALUES ('$productName', $productQuantity, $netAmount, $tp, '$batch_no', $inches, $retailPPrice, '$supplierName', '$company', '$category')";
        }
        
        if ($connection->query($updateSql) !== TRUE) {
            echo "Error updating product quantity: " . $connection->error;
            ob_end_flush();
            exit;
        }

        $updateSqlRP = "UPDATE products SET retail_price = $retailPPrice WHERE product_name = '$productName' AND batch_no = '$batch_no'";
        if ($connection->query($updateSqlRP) !== TRUE) {
            echo "Error updating product quantity: " . $connection->error;
            ob_end_flush();
            exit;
        }
    }
    ob_end_clean();
    echo "<script type='text/javascript'>window.location.href = 'print_invoice_p.php?inv_id=$orderId';</script>";
}

// Return invoice submission (modified to include batch_no)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['return_bill'])) {
    if ($connection->connect_error) {
        die("Connection failed: " . $connection->connect_error);
    }

    $productData = json_decode($_POST['productData'], true);
    $r_inv_id = $_POST["r_inv_id"];
    $orderId = $r_inv_id;
    $status = 'return';
    $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"];
    $description = $_POST['desc_note'];
    $date_time = date("Y-m-d");

    foreach ($productData as $product) {
        $productId = $product['productId'];
        $productName = $product['description'];
        $productPrice = $product['pricePerUnit'];
        $tradePrice = $product['tradePrice'];
        $category = $product['category'];
        $productQuantity = $product['quantity'];
        $inches = $product['inches'];
        $batch_no = $product['batch_no'] ?? '';
        $productTotal = $product['totalPrice'];
        $discount = $product['discountPercentage'];
        $tax = $product['extraPer'];
        $disAmount = $product['disAmount'];
        $netAmount = $product['netAmount'];
        $supplierName = $product['supplier'];
        $company = $product['company'];
        $sale_cost = $tradePrice * $productQuantity * $inches;

        $sql = "INSERT INTO purchase (
            product_id,
            supplier_name,
            company,
            category,
            product_name,
            product_price,
            trade_price,
            product_quantity,
            product_total,
            bonus,
            discount,
            dis_amount,
            tax,
            net_amount,
            total_amount,
            pre_amount,
            grand_amount,
            paid_by,
            sale_cost,
            customer_id,
            customer_type,
            customer_name,
            customer_phone,
            discount_amount,
            discounted,
            discount_per,
            cash_amount,
            change_amount,
            inv_id,
            r_inv_id,
            status,
            outlet_name,
            login_user,
            user_role,
            outlet_address,
            date_time,
            desc_note,
            inches,
            batch_no
        ) VALUES (
            '$productId',
            '$supplierName',
            '$company',
            '$category',
            '$productName',
            '$productPrice',
            '$tradePrice',
            '$productQuantity',
            '$productTotal',
            '',
            '$discount',
            '$disAmount',
            '$tax',
            '$netAmount',
            '$productTotal',
            '$preAmount',
            '$grandAmount',
            '$paidBy',
            '$sale_cost',
            '$customer_id',
            '$customer_type',
            '$customerName',
            '$customerPhone',
            '$discount_amount',
            '$discounted',
            '$discount_per',
            '$cash_amount',
            '$change_amount',
            '$orderId',
            '$r_inv_id',
            '$status',
            '$outlet',
            '$user',
            '$role',
            '$address',
            '$date_time',
            '$description',
            '$inches',
            '$batch_no'
        )";

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

        $updateSql = "UPDATE products SET quantity = quantity - $productQuantity, total_amount = total_amount - $netAmount WHERE product_name = '$productName' AND batch_no = '$batch_no'";
        if ($connection->query($updateSql) !== TRUE) {
            echo "Error updating product quantity: " . $connection->error;
            ob_end_flush();
            exit;
        }
    }
    ob_end_clean();
    echo "<script type='text/javascript'>window.location.href = 'purchase_n.php';</script>";
}

ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?php echo $tx; ?></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">
    <style>
        body {
            font-family: 'Quicksand', sans-serif;
        }
        #table-container-wrapper {
            max-height: 450px; 
            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;
        }
        .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;
        }
        tr {
            font-weight: 700;
            background: #fff;
        }
        .form-control {
            font-weight: 700;
        }
        .btn, .input-group-prepend {
            font-weight: 700;
        }
        .btn-primary {
            background: #0A4657;
            color: #fff;
            border: 1px solid #0A4657;
        }
        .btn-primary:hover {
            background: #fff;
            color: #0A4657;
            border: 1px solid #0A4657;
        }
        .form-control {
            font-weight: 700;
            color: #000;
        }

        /* Batch List Styles - inside col-sm-3 */
        .batch-list-container {
            margin-top: 15px;
            border: 1px solid #dee2e6;
            border-radius: 10px;
            background: white;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            display: none;
        }
        .batch-list-header {
            background: #0A4657;
            color: white;
            padding: 10px 12px;
            font-weight: bold;
            font-size: 14px;
        }
        .batch-list-body {
            max-height: 280px;
            overflow-y: auto;
        }
        .batch-item {
            padding: 12px 15px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: all 0.2s ease;
            animation: fadeInUp 0.3s ease;
        }
        .batch-item:hover {
            background-color: #e8f4f8;
            transform: translateX(5px);
        }
        .batch-info {
            font-weight: 600;
            color: #0A4657;
            font-size: 14px;
        }
        .batch-qty {
            font-size: 12px;
            color: #28a745;
            margin-top: 4px;
        }
        .no-batches {
            padding: 20px;
            text-align: center;
            color: #dc3545;
            font-weight: 500;
        }
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        .product-name-item {
            padding: 8px 10px;
            font-weight: 600;
            border-bottom: 1px solid #dee2e6;
            cursor: pointer;
        }
        .product-name-item:hover {
            background-color: #e9ecef;
        }
        option{
            font-weight:700;
            color:#000;
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row bg">
        <div class="col-sm-3" style="width:100%; height:69px;">
            <img src="../img/logo231.png" style="margin-top:5px; background:#fff; border-radius:60px;" width="56" height="56">
        </div>
        <div class="col-sm-6">
            <h3 style="color:#fff; font-weight:700; text-transform:uppercase; text-align:center; line-height:60px; font-size:33px;">
                <?php echo $tx; ?>
            </h3>
        </div>
        <div class="col-sm-3">
            <a href="addproduct.php">
                <button type="button" class="btn btn-light mt-3" style="float:right;">Back</button>
            </a>
        </div>
    </div>
</div>
<div class="container-fluid">
    <form action="purchase_n.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>
                
                <!-- Batch List Container - shows inside col-sm-3 after product selection -->
                <div id="batchListContainer" class="batch-list-container">
                    <div class="batch-list-header">
                        <i class="fas fa-boxes"></i> Select Batch Number
                    </div>
                    <div id="batchListBody" class="batch-list-body">
                        <!-- Batches will be loaded here dynamically -->
                    </div>
                </div>
                
                <hr>
                <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">P.Price</span>
                        </div>
                        <input type="text" id="p_price" name="p_price" class="form-control" placeholder="" readonly>
                    </div>
                    <div class="input-group mb-3 col-6">
                        <input type="text" id="remain_quantity" name="remain_quantity" class="form-control" placeholder="" readonly>
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-dark text-white">R.Qty</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">Inches</span>
                    </div>
                    <input type="text" id="inches" name="inches" class="form-control" placeholder="Inches" value="1">
                </div>
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">R.P</span>
                    </div>
                    <input type="text" id="retail_prices" name="retail_prices" 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="trade_prices" name="trade_prices" class="form-control" placeholder="">
                </div>
                <div class="">
                    <input type="hidden" 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="row">
                    <div class="input-group mb-3 col-6">
                        <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="" style="font-weight:700;">
                    </div>
                    <div class="input-group mb-3 col-6">
                        <input type="text" id="dis_amount" name="dis_amount" class="form-control" placeholder="" style="font-weight:700;">
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-dark text-white">Dis PKR</span>
                        </div>
                    </div>
                </div>
                <div class="">
                    <input type="hidden" 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">Net Amount</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 text-white" id="makeEntry">Make Entry</button>
                <hr>
                <div class="row">
                    <div class="col-6">
                        <button type="button" class="form-control btn btn-dark text-white" onclick="location.reload();">Refresh</button>
                    </div>
                    <div class="col-6">
                        <a href="purchase_detail_v.php" class="btn btn-primary form-control text-white">View Purchase</a>
                    </div>
                </div>
                <hr>
                <div class="form-group">
                    <label>Note Description</label>
                    <textarea class="form-control" name="desc_note"></textarea>
                </div>
            </div>
            <div class="col-sm-9">
                <div class="row" style="background:#F0F0F0; padding:10px; border:1px solid #CCC;">
                    <div class="">
                        <div class="form-group">
                            <input type="hidden" class="form-control in_form" name="customer_type">
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label>Supplier Name</label>
                            <input type="text" id="customer_name" name="customer_name" class="form-control in_form" autocomplete="off">
                            <div class="dropdown-menu" id="customer_suggestions"></div>
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label>Supplier Phone</label>
                            <input type="text" id="customer_phone" name="customer_phone" class="form-control in_form">
                        </div>
                    </div>
                    <div class="">
                        <div class="">
                            <input type="hidden" id="customer_id" name="customer_id" class="form-control in_form">
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label>Return ID</label>
                            <input type="text" id="r_order_id" name="r_inv_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:#F0F0F0; padding:10px; border:1px solid #CCC;">
                    <div class="col-sm-12" style="height:450px;" id='table-container-wrapper'>
                        <table class="table table-borderless table-sm text-center" id="productsTable">
                            <tr class="text-white text-center" style="background:#0A4657;">
                                <th>Item Code</th>
                                <th>Description</th>
                                <th>Batch No</th>
                                <th>Qty</th>
                                <th>Inches</th>
                                <th>Unit Price</th>
                                <th>Sale Price</th>
                                <th>Amount</th>
                                <th>% Dis</th>
                                <th>Dis.PKR</th>
                                <th>Tax</th>
                                <th>Net Amount</th>
                                <th>Action</th>
                             </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="">
                                <div class="">
                                    <input type="hidden" step="0.01" 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" step="0.01" name="bill_amount" class="form-control in_form input-height" required>
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Previous</label>
                                    <input type="text" id="pre_amount" step="0.01" name="pre_amount" class="form-control in_form input-height" required>
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Grand Total</label>
                                    <input type="text" id="grand_amount" step="0.01" name="grand_amount" class="form-control in_form input-height" readonly>
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Discount Amount</label>
                                    <input type="number" id="discount_amount" step="0.01" 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" step="0.01" name="discount_percent" class="form-control in_form input-height" readonly>
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Cash Paid</label>
                                    <input type="number" id="cash_received" step="0.01" name="cash_received" class="form-control in_form input-height">
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Cash Remaining</label>
                                    <input type="number" id="cash_return" step="0.01" name="cash_return" class="form-control in_form input-height">
                                </div>
                            </div>
                            <div class="">
                                <div class="">
                                    <input type="hidden" id="tax" name="tax" class="form-control in_form input-height" 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 font-weight-bold">
                                        <option style="font-weight:700;" value="cash">Cash</option>
                                        <option style="font-weight:700;" value="credit">Credit</option>
                                   <option value="bank1">Ibrahim Meezan</option>
                                        <option value="bank2">Adil Meezan </option>
                                        <option value="bank3">HBL Bank</option>
                                        <option value="bank3">JazzCash</option>
                                        <option style="font-weight:700;" value="others">Others</option>
                                    </select>
                                </div>
                            </div>
                            <input type="hidden" id="productData" name="productData">
                            <div class="col-sm-4">
                                <hr>
                                <button type="submit" class="btn btn-dark btn-sm" name="inv_bill" id="generateInvoiceBtn">Generate Invoice</button>
                                <button type="submit" class="btn btn-danger btn-sm" name="return_bill">Return Invoice</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<script>
// ==================== AJAX / SUGGESTIONS ====================
document.addEventListener("DOMContentLoaded", function() {
    let currentFocus = -1;
    let selectedProductName = '';

    // Function to load and display batches in the col-sm-3 container
    function loadBatchesForProduct(productName) {
        const batchContainer = document.getElementById('batchListContainer');
        const batchBody = document.getElementById('batchListBody');
        
        if (!productName) {
            batchContainer.style.display = 'none';
            return;
        }
        
        batchContainer.style.display = 'block';
        batchBody.innerHTML = '<div class="no-batches"><i class="fas fa-spinner fa-spin"></i> Loading batches...</div>';
        
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "?get_batches=" + encodeURIComponent(productName), true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                batchBody.innerHTML = xhr.responseText;
                // Add click listeners to batch items
                document.querySelectorAll('.batch-item').forEach(function(item) {
                    item.addEventListener('click', function() {
                        selectBatch(this);
                    });
                });
            }
        };
        xhr.send();
    }

    function selectBatch(batchElement) {
        const productId = batchElement.getAttribute('data-product-id');
        const retailPrice = batchElement.getAttribute('data-retail-price');
        const productQuantity = batchElement.getAttribute('data-product-quantity');
        const tradePrice = batchElement.getAttribute('data-trade-price');
        const supplier = batchElement.getAttribute('data-supplier');
        const company = batchElement.getAttribute('data-company');
        const category = batchElement.getAttribute('data-category');
        const productUnit = batchElement.getAttribute('data-product-unit');
        const inches = batchElement.getAttribute('data-inches') || 1;
        const batchNo = batchElement.getAttribute('data-batch-no');
        const productName = batchElement.getAttribute('data-product-name');
        
        const input = document.getElementById("productInput");
        input.value = productName + " (Batch: " + (batchNo || 'No Batch') + ")";
        input.setAttribute('data-product-id', productId);
        input.setAttribute('data-product-quantity', productQuantity);
        input.setAttribute('data-supplier', supplier);
        input.setAttribute('data-company', company);
        input.setAttribute('data-trade-price', tradePrice);
        input.setAttribute('data-product-unit', productUnit);
        input.setAttribute('data-inches', inches);
        input.setAttribute('data-batch-no', batchNo);
        input.setAttribute('data-product-name', productName);
        input.setAttribute('data-category', category);
        
        document.getElementById("remain_quantity").value = productQuantity;
        document.getElementById("p_price").value = tradePrice;
        document.getElementById("trade_prices").value = tradePrice;
        document.getElementById("inches").value = inches;
        document.getElementById("suggestions").style.display = 'none';
        
        // Hide batch list after selection
        document.getElementById('batchListContainer').style.display = 'none';
        
        calculateTotalPrice();
        document.getElementById("quantity").focus();
    }

    // ---- Return ID Suggestions ----
    document.getElementById("r_order_id").addEventListener("input", function() {
        var orderIdInput = this.value;
        if (orderIdInput.length > 0) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "?inv_id=" + encodeURIComponent(orderIdInput), true);
            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';
        }
    });

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

    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;
        if (items[currentFocus]) {
            items[currentFocus].classList.add("active");
            items[currentFocus].scrollIntoView({ block: "nearest" });
        }
    }

    function removeActive(items) {
        for (var i = 0; i < items.length; i++) {
            if (items[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';
    }

    // ---- Customer Suggestions ----
    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 selectCustomer(item) {
        var customerName = item.getAttribute('data-customer-name');
        var customerId = item.getAttribute('data-customer-id');
        var customerPhone = item.getAttribute('data-customer-phone');
        var remainBalance = item.getAttribute('data-remain-balance');

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

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

    // ---- Product Suggestions ----
    document.getElementById("suggestions").addEventListener("click", function(e) {
        if (e.target && e.target.classList.contains("product-name-item")) {
            const productName = e.target.getAttribute('data-product-name');
            selectedProductName = productName;
            document.getElementById("productInput").value = productName;
            document.getElementById("suggestions").style.display = 'none';
            loadBatchesForProduct(productName);
        }
    });

    document.getElementById("productInput").addEventListener("input", function() {
        var query = this.value.trim();
        if (query.length > 0) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "?query=" + encodeURIComponent(query), true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var suggestions = document.getElementById("suggestions");
                    var response = xhr.responseText;
                    if (response.trim() === "") {
                        suggestions.innerHTML = '<div class="dropdown-item text-danger">No products found</div>';
                    } else {
                        suggestions.innerHTML = response;
                    }
                    suggestions.style.display = 'block';
                }
            };
            xhr.send();
        } else {
            document.getElementById("suggestions").style.display = 'none';
            document.getElementById('batchListContainer').style.display = 'none';
        }
    });

    document.getElementById("productInput").addEventListener("keydown", function(e) {
        var suggestions = document.getElementById("suggestions");
        if (suggestions.style.display === 'block') {
            var items = suggestions.querySelectorAll(".product-name-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 && items[currentFocus]) {
                    const productName = items[currentFocus].getAttribute('data-product-name');
                    selectedProductName = productName;
                    document.getElementById("productInput").value = productName;
                    document.getElementById("suggestions").style.display = 'none';
                    loadBatchesForProduct(productName);
                }
            }
        }
    });

    const productInputField = document.getElementById("productInput");
    productInputField.addEventListener("keypress", function (e) {
        if (e.key === "Enter") {
            e.preventDefault(); 
            if (selectedProductName) {
                loadBatchesForProduct(selectedProductName);
            }
        }
    });

    // ---- Calculation Functions (with inches) ----
    function calculateTotalPrice() {
        const quantity = parseFloat(document.getElementById("quantity").value) || 0;
        const pricePerUnit = parseFloat(document.getElementById("trade_prices").value) || 0;
        const inches = parseFloat(document.getElementById("inches").value) || 1;

        if (isNaN(quantity) || isNaN(pricePerUnit) || isNaN(inches)) return;

        const totalAmount = quantity * pricePerUnit * inches;
        document.getElementById("total_amount").value = totalAmount.toFixed(2);
        applyFinalPrice(totalAmount);
    }

    function updatePriceFromPercentage() {
        const quantity = parseFloat(document.getElementById("quantity").value) || 0;
        const pricePerUnit = parseFloat(document.getElementById("trade_prices").value) || 0;
        const inches = parseFloat(document.getElementById("inches").value) || 1;
        const discountPercentage = parseFloat(document.getElementById("percentage").value) || 0;

        if (isNaN(quantity) || isNaN(pricePerUnit) || isNaN(discountPercentage) || isNaN(inches)) return;

        const totalAmount = quantity * pricePerUnit * inches;
        const discountAmount = (totalAmount * discountPercentage) / 100;
        const afterDiscount = totalAmount - discountAmount;

        document.getElementById("total_amount").value = totalAmount.toFixed(2);
        document.getElementById("dis_amount").value = discountAmount.toFixed(2);
        applyFinalPrice(afterDiscount);
    }

    function updatePriceFromAmount() {
        const quantity = parseFloat(document.getElementById("quantity").value) || 0;
        const pricePerUnit = parseFloat(document.getElementById("trade_prices").value) || 0;
        const inches = parseFloat(document.getElementById("inches").value) || 1;
        const discountAmount = parseFloat(document.getElementById("dis_amount").value) || 0;

        if (isNaN(quantity) || isNaN(pricePerUnit) || isNaN(discountAmount) || isNaN(inches)) return;

        const totalAmount = quantity * pricePerUnit * inches;
        const discountPercentage = (discountAmount / totalAmount) * 100;
        const afterDiscount = totalAmount - discountAmount;

        document.getElementById("total_amount").value = totalAmount.toFixed(2);
        document.getElementById("percentage").value = discountPercentage.toFixed(2);
        applyFinalPrice(afterDiscount);
    }

    function applyFinalPrice(baseAmount) {
        const saleTaxPercentage = parseFloat(document.getElementById("sale_tax").value) || 0;
        const saleTaxAmount = (baseAmount * saleTaxPercentage) / 100;
        const finalPrice = baseAmount + saleTaxAmount;
        document.getElementById("trade_price").value = finalPrice.toFixed(2);
    }

    // Event listeners for calculation
    document.getElementById("quantity").addEventListener("input", debounce(calculateTotalPrice));
    document.getElementById("trade_prices").addEventListener("input", debounce(calculateTotalPrice));
    document.getElementById("inches").addEventListener("input", debounce(calculateTotalPrice));
    document.getElementById("percentage").addEventListener("input", debounce(updatePriceFromPercentage));
    document.getElementById("dis_amount").addEventListener("input", debounce(updatePriceFromAmount));
    document.getElementById("sale_tax").addEventListener("input", debounce(() => {
        const totalAmount = parseFloat(document.getElementById("total_amount").value);
        if (!isNaN(totalAmount)) applyFinalPrice(totalAmount);
    }));

    function debounce(fn, delay = 300) {
        let timer;
        return function (...args) {
            clearTimeout(timer);
            timer = setTimeout(() => fn.apply(this, args), delay);
        };
    }

    // ---- Make Entry (with batch_no) ----
    document.getElementById("makeEntry").addEventListener("click", function() {
        var productInput = document.getElementById("productInput");
        var productId = productInput.getAttribute('data-product-id');
        var batchNo = productInput.getAttribute('data-batch-no') || '';
        var productQuantity = parseFloat(document.getElementById("quantity").value) || 0;
        var inches = parseFloat(document.getElementById("inches").value) || 1;
        var supplier = productInput.getAttribute('data-supplier') || '';
        var company = productInput.getAttribute('data-company') || '';
        var category = productInput.getAttribute('data-category') || '';

        var description = productInput.getAttribute('data-product-name') || productInput.value;
        description = description.replace(/\s*\(Batch:.*?\)\s*$/, '');
        
        var quantity = productQuantity;
        var pricePerUnit = parseFloat(document.getElementById("retail_price").value) || 0;
        var retailPPrice = parseFloat(document.getElementById("retail_prices").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 disAmount = parseFloat(document.getElementById("dis_amount").value) || 0;
        var extraPer = parseFloat(document.getElementById("sale_tax").value) || 0;
        var tradePrice = productInput.getAttribute('data-trade-price') || 0;

        if (!batchNo) {
            alert("Please select a batch number first.");
            return;
        }

        if (quantity <= 0) {
            alert("Quantity must be greater than zero.");
            return;
        }

        if (productId && description && quantity && pricePerUnit && totalPrice && netAmount) {
            var table = document.getElementById("productsTable");
            var row = table.insertRow();
            row.innerHTML = `
                <td style="display:none;">${quantity}</td>
                <td>${productId}</td>
                <td style="color:#0A5064;font-weight:700px;">${escapeHtml(description)}</td>
                <td>${escapeHtml(batchNo) || '-'}</td>
                <td>${quantity}</td>
                <td>${inches}</td>
                <td>${pricePerUnit}</td>
                <td>${retailPPrice}</td>
                <td>${totalPrice}</td>
                <td>${discountPercentage || '0.00'}</td>
                <td>${disAmount || '0.00'}</td>
                <td>${extraPer || '0.00'}</td>
                <td>${netAmount}</td>
                <td style="display:none;">${supplier}</td>
                <td style="display:none;">${company}</td>
                <td style="display:none;">${tradePrice}</td>
                <td style="display:none;">${category}</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();

            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,
                    batch_no: cells[3].innerText,
                    quantity: cells[4].innerText,
                    inches: cells[5].innerText,
                    pricePerUnit: cells[6].innerText,
                    retailPPrice: cells[7].innerText,
                    totalPrice: cells[8].innerText,
                    discountPercentage: cells[9].innerText,
                    disAmount: cells[10].innerText,
                    extraPer: cells[11].innerText,
                    netAmount: cells[12].innerText,
                    supplier: cells[13].innerText,
                    company: cells[14].innerText,
                    tradePrice: cells[15].innerText,
                    category: cells[16].innerText
                };
                productData.push(product);
            });

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

            resetProductFields();
            productInput.focus();
        } else {
            alert("Some required fields are missing");
        }
    });

    function resetProductFields() {
        document.getElementById("productInput").value = '';
        document.getElementById("quantity").value = '';
        document.getElementById("inches").value = '1';
        document.getElementById("retail_price").value = '';
        document.getElementById("total_amount").value = '';
        document.getElementById("percentage").value = '';
        document.getElementById("trade_price").value = '';
        document.getElementById("trade_prices").value = '';
        document.getElementById("dis_amount").value = '';
        document.getElementById("sale_tax").value = '';
        document.getElementById("retail_prices").value = '';
        document.getElementById("remain_quantity").value = '';
        document.getElementById("p_price").value = '';
        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');
        document.getElementById("productInput").removeAttribute('data-inches');
        document.getElementById("productInput").removeAttribute('data-batch-no');
        document.getElementById("productInput").removeAttribute('data-product-name');
        document.getElementById("productInput").removeAttribute('data-category');
        document.getElementById('batchListContainer').style.display = 'none';
        selectedProductName = '';
    }

    function escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // ---- Totals and Discounts ----
    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[12];
            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);

        updateDiscountAmount();
        updateGrandAmount();
    }

    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 updateGrandAmount() {
        var billAmount = parseFloat(document.getElementById("bill-amount").value) || 0;
        var preAmount = parseFloat(document.getElementById("pre_amount").value) || 0;
        var grandAmountInput = document.getElementById("grand_amount");
        var grandAmount = billAmount + preAmount;
        grandAmountInput.value = grandAmount.toFixed(2);
        calculateCashReturn();
    }

    function calculateCashReturn() {
        var grandAmount = parseFloat(document.getElementById("grand_amount").value) || 0;
        var cashReceived = parseFloat(document.getElementById("cash_received").value) || 0;
        var cashReturnInput = document.getElementById("cash_return");
        var cashReturn =  cashReceived  - grandAmount;
        cashReturnInput.value = cashReturn.toFixed(2);
    }

    function attachInputListener(id, callback) {
        var el = document.getElementById(id);
        if (el) {
            el.addEventListener("input", callback);
        }
    }

    attachInputListener("bill-amount", function () {
        updateDiscountAmount();
        updateGrandAmount();
    });
    attachInputListener("pre_amount", updateGrandAmount);
    attachInputListener("cash_received", calculateCashReturn);

    attachInputListener("discount_amount", function () {
        const total = parseFloat(document.getElementById("total-input").value) || 0;
        const discountAmount = parseFloat(document.getElementById("discount_amount").value) || 0;
        const newBillAmount = total - discountAmount;
        document.getElementById("bill-amount").value = newBillAmount.toFixed(2);
        const discountPercent = (discountAmount / total) * 100;
        document.getElementById("discount_percent").value = discountPercent.toFixed(2);
        updateGrandAmount();
        calculateCashReturn();
    });

    attachInputListener("discount_percent", function () {
        const total = parseFloat(document.getElementById("total-input").value) || 0;
        const discountPercent = parseFloat(document.getElementById("discount_percent").value) || 0;
        const discountAmount = (discountPercent / 100) * total;
        document.getElementById("discount_amount").value = Math.round(discountAmount);
        const newBillAmount = total - discountAmount;
        document.getElementById("bill-amount").value = newBillAmount.toFixed(2);
        updateGrandAmount();
        calculateCashReturn();
    });

    (function watchPreAmount() {
        var preAmountEl = document.getElementById("pre_amount");
        var lastValue = preAmountEl ? preAmountEl.value : null;
        setInterval(function () {
            if (!preAmountEl) return;
            if (preAmountEl.value !== lastValue) {
                lastValue = preAmountEl.value;
                updateGrandAmount();
            }
        }, 300);
    })();

    window.addEventListener("DOMContentLoaded", function () {
        calculateTotalAmount();
        updateGrandAmount();
    });
});

// Method change handling (credit mode)
document.getElementById("method").addEventListener("change", function () {
    const cashInput = document.getElementById("cash_received");
    if (this.value === "credit") {
        cashInput.readOnly = true;
        cashInput.value = "";
    } else {
        cashInput.readOnly = false;
    }
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</body>
</html>