<?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();

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'];
} else {
    echo "<script>window.location.href = 'logout.php';</script>";
    exit;
}

function generateOrderId(mysqli $connection): string {
    $connection->query("INSERT INTO order_sequence () VALUES ()");
    return str_pad($connection->insert_id, 5, "0", STR_PAD_LEFT);
}

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 for product search
if (isset($_GET['query'])) {
    $query = $connection->real_escape_string($_GET['query']);
    $sql = "SELECT product_id, product_name, retail_price, trade_price, category, supplier, company, product_unit, quantity FROM products WHERE product_name LIKE '%$query%'";
    $result = $connection->query($sql);
    $suggestions = "";
    while ($row = $result->fetch_assoc()) {
        $suggestions .= "<div class='dropdown-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'] . "'>" . $row['product_name'] . "</div>";
    }
    echo $suggestions;
    exit;
}

// AJAX for customer search
if (isset($_GET['customer_name'])) {
    $customerName = $connection->real_escape_string($_GET['customer_name']);
    $sql = "SELECT cr_name, cr_id, phone_number, city, transport FROM credit_note WHERE cr_name LIKE '%$customerName%' LIMIT 5";
    $result = $connection->query($sql);
    $suggestions = "";
    while ($row = $result->fetch_assoc()) {
        $crName = $row['cr_name'];
        $city = $row['city'];
        $transport = $row['transport'];
        $crId = $row['cr_id'];
        $phone = $row['phone_number'];
        $remainSql = "SELECT remain_balance FROM creditor_closing WHERE creditor_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['remain_balance'];
        }
        $suggestions .= "<div class='dropdown-item' data-customer-name='$crName' data-customer-id='$crId' data-customer-phone='$phone' data-city='$city' data-transport='$transport' data-remain-balance='$remainBalance'>$crName</div>";
    }
    echo $suggestions;
    exit;
}

// AJAX for order ID search
if (isset($_GET['order_id'])) {
    $order_id = $_GET['order_id'];
    if (!empty($order_id)) {
        $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();
        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;
}

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

// ========== GENERATE BILL (INSERT) ==========
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 = generateOrderId($connection);
    $paidBy = $_POST['method'];
    $bill_amount = $_POST["BillAmount"];
    $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"];
    $pre_amount = $_POST["pre_amount"];
    $grand_amount = $_POST["grand_amount"];
    $desc_note = $_POST['desc_note'];
    $date_time = date("Y-m-d");

    // New charge fields
    $cutting = $_POST["cutting"] ?? 0;
    $loading = $_POST["loading"] ?? 0;
    $vehicle_rent = $_POST["vehicle_rent"] ?? 0;
    $ctn = $_POST["ctn"] ?? 0;
    $bora = $_POST["bora"] ?? 0;

    // city and transport
    $city = $_POST["city"] ?? '';
    $transport = $_POST["transport"] ?? '';

    foreach ($productData as $product) {
        $productId = $product['productId'];
        $category = $product['category'];
        $productName = $product['description'];
        $productPrice = $product['pricePerUnit'];
        $tradePrice = $product['tradePrice'];
        $productQuantity = $product['quantity'];
        $productTotal = $product['totalPrice'];
        $discount = $product['discountPercentage'];
        $discAmount = $product['discAmount'];
        $tax = $product['tax'];
        $netAmount = $product['netAmount'];
        $supplierName = $product['supplier'];
        $company = $product['company'];
        $productUnit = $product['productUnit']; // from the visible/editable input
        $sale_cost = $tradePrice * $productQuantity;
        $tp = $sale_cost;

        // INSERT query with product_unit added
        $sql = "INSERT INTO log_user_sales (
            product_id, supplier_name, company, category, product_unit, product_name,
            product_price, trade_price, product_quantity, product_total,
            bonus, discount, disc_amount, tax, net_amount,
            BillAmount, 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,
            order_id, r_order_id, outlet_name, login_user, user_role, outlet_address,
            date_time, desc_note, cutting, loading, vehicle_rent, ctn, bora, city, transport
        ) VALUES (
            '$productId', '$supplierName', '$company', '$category', '$productUnit', '$productName',
            '$productPrice', '$tradePrice', '$productQuantity', '$productTotal',
            '', '$discount', $discAmount, '$tax', '$netAmount',
            '$bill_amount', '$productTotal', '$pre_amount', '$grand_amount', '$paidBy',
            '$sale_cost', '$customer_id', '$customer_type', '$customerName', '$customerPhone',
            '$discount_amount', '$discounted', '$discount_per', '$cash_amount', '$change_amount',
            '$orderId', '$r_order_id', '$outlet', '$user', '$role', '$address',
            '$date_time', '$desc_note', '$cutting', '$loading', '$vehicle_rent', '$ctn', '$bora',
            '$city', '$transport'
        )";

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

        // Update product quantity
        $updateSql = "UPDATE products SET quantity = 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 = 'printtypep.php?order_id=$orderId';</script>";
}

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

    $productData = json_decode($_POST['productData'], true);
    if (!is_array($productData) || count($productData) === 0) {
        echo "<script>alert('No products to refund'); window.location.href='mainpos.php';</script>";
        exit;
    }

    $paidBy = $_POST["method"] ?? '';
    $status = 'Refund';
    $discount_amount = $_POST["bill_amount"] ?? '0';
    $discounted = $_POST["discount_amount"] ?? '0';
    $discount_per = $_POST["discount_percent"] ?? '0';
    $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"] ?? '';
    $pre_amount = $_POST["pre_amount"] ?? '0';
    $grand_amount = $_POST["grand_amount"] ?? '0';
    $date_time = date("Y-m-d");
    $desc_note = $_POST['desc_note'] ?? '';

    $cutting = 0;
    $loading = 0;
    $vehicle_rent = 0;
    $ctn = 0;
    $bora = 0;

    $city = $_POST["city"] ?? '';
    $transport = $_POST["transport"] ?? '';

    $outlet_name = $_SESSION['outlet_name'] ?? '';
    $outlet_address = $_SESSION['outlet_address'] ?? '';
    $login_user = $_SESSION['user_name'] ?? '';
    $user_role = $_SESSION['user_role'] ?? '';

    // Updated: 47 placeholders (added product_unit)
    $sql = "INSERT INTO log_user_sales (
        product_id, supplier_name, company, category, product_unit, product_name,
        product_price, trade_price, product_quantity, product_total,
        bonus, discount, disc_amount, tax, net_amount,
        tax_amount, total_amount, BillAmount, paid_by,
        pre_amount, grand_amount, 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,
        outlet_name, login_user, user_role, outlet_address, date_time, desc_note,
        cutting, loading, vehicle_rent, ctn, bora, city, transport
    ) VALUES (" . rtrim(str_repeat('?,', 47), ',') . ")";

    $stmt = $connection->prepare($sql);
    if (!$stmt) {
        die("Prepare failed: " . $connection->error);
    }

    $updateStockStmt = $connection->prepare("UPDATE products SET quantity = quantity + ?, total_amount = total_amount + ? WHERE product_id = ?");
    if (!$updateStockStmt) {
        die("Prepare failed (stock update): " . $connection->error);
    }

    $connection->begin_transaction();

    try {
        foreach ($productData as $product) {
            $productId = (string)($product['productId'] ?? '');
            $supplierName = (string)($product['supplier'] ?? '');
            $company = (string)($product['company'] ?? '');
            $category = (string)($product['category'] ?? '');
            $productUnit = (string)($product['productUnit'] ?? ''); // NEW
            $productName = (string)($product['description'] ?? '');
            $productPrice = (string)($product['pricePerUnit'] ?? '0');
            $tradePrice = (string)($product['tradePrice'] ?? '0');
            $productQty = (int)($product['quantity'] ?? 0);
            $productTotal = (string)($product['totalPrice'] ?? '0');
            $discount = (string)($product['discountPercentage'] ?? '0');
            $discAmount = (string)($product['discAmount'] ?? '0');
            $tax = (string)($product['tax'] ?? '0');
            $netAmount = (string)($product['netAmount'] ?? '0');

            $negQuantity = (string)(-1 * $productQty);
            $refundAmount = (float)$tradePrice * $productQty;
            $tax_amount = (string)$tax;
            $total_amount = (string)$productTotal;
            $BillAmount = (string)$discount_amount;
            $sale_cost = (string)($tradePrice * $productQty);

            // bind types: 47 strings
            $bindTypes = str_repeat('s', 47);
            $params = [
                $productId, $supplierName, $company, $category, $productUnit, $productName,
                $productPrice, $tradePrice, $negQuantity, $productTotal,
                '0', $discount, $discAmount, $tax, $netAmount,
                $tax_amount, $total_amount, $BillAmount, $paidBy,
                $pre_amount, $grand_amount, $sale_cost,
                $customer_id, $customer_type, $customerName, $customerPhone,
                $discount_amount, $discounted, $discount_per,
                $cash_amount, $change_amount, $r_order_id ?: $r_order_id, $r_order_id, $status,
                $outlet_name, $login_user, $user_role, $outlet_address, $date_time, $desc_note,
                $cutting, $loading, $vehicle_rent, $ctn, $bora,
                $city, $transport
            ];

            $refs = [];
            $refs[] = &$bindTypes;
            for ($i = 0; $i < count($params); $i++) {
                $refs[] = &$params[$i];
            }
            call_user_func_array([$stmt, 'bind_param'], $refs);

            if (!$stmt->execute()) {
                throw new Exception("Insert failed: " . $stmt->error);
            }

            $updateStockStmt->bind_param('dds', $productQty, $refundAmount, $productId);
            if (!$updateStockStmt->execute()) {
                throw new Exception("Stock update failed: " . $updateStockStmt->error);
            }
        }

        $connection->commit();
        $stmt->close();
        $updateStockStmt->close();

        ob_end_clean();
        echo "<script>window.location.href = 'mainpos.php';</script>";
        exit;

    } catch (Exception $e) {
        $connection->rollback();
        die("Refund transaction failed: " . htmlspecialchars($e->getMessage()));
    }
}

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: 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; }
        .dropdown-menu { max-height: 200px; overflow-y: auto; position: absolute; z-index: 1000; font-weight:700; 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; height: 32px; }
        .btn-group .btn { margin-right: 5px; }
        .btn-group .btn:last-child { margin-right: 0; }
        .btn-primary { background:#0A4657; color:#fff; border:1px solid #0A4657; }
        .btn-primary:hover { background:#fff; color:#0A4657; border:1px solid #0A4657; }
        .btn { font-weight:700; }
    </style>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
<div class="container-fluid">
    <div class="row bg align-items-center">
        <div class="col-sm-3">
            <img src="../img/logo231.png" style="margin-top:5px;" width="56" height="56">
        </div>
        <div class="col-sm-6">
            <h3 style="color:#fff; font-weight:700; text-align:center; text-transform:uppercase;"><?php echo $tx; ?></h3>
        </div>
        <div class="col-sm-3">
            <div class="d-flex justify-content-end gap-2">
                <a href="order_detail_v.php" class="btn btn-primary">View Sales</a>
                <a href="addproduct.php" class="btn btn-light">Back</a>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid">
    <form action="mainpos.php" method="post" enctype="multipart/form-data">
        <!-- Customer Row -->
        <div class="row" style="background:#F0F0F0; padding:10px; border:1px solid #CCC;">
            <div class=""><input type="hidden" name="customer_type" value="walkin"></div>
            <div class="col-sm-3">
                <div class="form-group">
                    <label>Customer Name</label>
                    <input type="text" id="customer_name" name="customer_name" class="form-control in_form" autocomplete="off">
                    <div class="dropdown-menu" id="customer_suggestions"></div>
                </div>
            </div>
            <div class="col-sm-3">
                <div class="form-group">
                    <label>Customer Phone</label>
                    <input type="text" id="customer_phone" name="customer_phone" class="form-control in_form">
                </div>
            </div>
            <div class="col-sm-3">
                <div class="form-group">
                    <label>City</label>
                    <input type="text" id="city" name="city" class="form-control in_form">
                </div>
            </div>
            <div class="col-sm-3">
                <div class="form-group">
                    <label>Transport</label>
                    <input type="text" id="transport" name="transport" class="form-control in_form">
                </div>
            </div>
            <div class=""><input type="hidden" id="customer_id" name="customer_id"></div>
            <div class="col-sm-3">
                <div class="">
                    <input type="hidden" 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>

        <!-- Product Entry Row -->
        <div class="row">
            <div class="col-sm-12" style="background:#F0F0F0; padding:10px; border:1px solid #CCC;">
                <h6>Product Entry</h6>
                <div class="row">
                    <div class="col-sm-2">
                        <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="Search product..." autocomplete="off">
                            <div class="dropdown-menu" id="suggestions"></div>
                        </div>
                    </div>
                    <div class=""><input type="hidden" id="p_price" name="p_price"></div>
                    <div class=""><input type="hidden" id="remain_quantity" name="remain_quantity"></div>

                    <div class="col-sm-2">
                        <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">
                        </div>
                    </div>
                    <div class="col-sm-2">
                        <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">
                        </div>
                    </div>
                    <div class="col-sm-2">
                        <div class="input-group mb-3">
                            <div class="input-group-prepend"><span class="input-group-text bg-dark text-white">Unit</span></div>
                            <!-- Visible editable product unit field -->
                            <input type="text" id="product_unit" name="product_unit" class="form-control">
                        </div>
                    </div>
                    <div class=""><input type="hidden" id="total_amount" name="total_amount" class="form-control" readonly></div>
                    <div class=""><input type="hidden" id="percentage" name="percentage"></div>
                    <div class=""><input type="hidden" id="disc_amount" name="disc_amount"></div>
                    <div class="col-sm-2">
                        <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" readonly>
                        </div>
                    </div>
                    <div class="col-sm-2">
                        <button type="button" class="btn btn-dark btn-block" id="makeEntry">Make Entry</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Cart Table -->
        <div class="row mt-2">
            <div class="col-sm-12">
                <div class="row" style="background:#F0F0F0; padding:10px; border:1px solid #CCC;">
                    <div class="col-sm-12" style="height:400px;" id="table-container-wrapper">
                        <table class="table table-borderless table-sm text-center" id="productsTable">
                            <tr class="text-white text-center" style="background:#0A4657;">
                                <td>Item Code</td>
                                <td>Description</td>
                                <td>Unit</td>   <!-- NEW column -->
                                <td>Qty</td>
                                <td>Unit Price</td>
                                <td>Amount</td>
                                <td style="display:none;">Dis%</td>
                                <td style="display:none;">Dis PKR</td>
                                <td style="display:none;">Tax</td>
                                <td>Net Amount</td>
                                <td>Action</td>
                                <td>Edit</td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Totals and Additional Charges -->
        <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="text" id="total-input" name="total_input" step="0.01" 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>Cutting</label><input type="number" id="cutting" name="cutting" step="0.01" class="form-control in_form input-height" value="0"></div>
                    </div>
                    <div class="col-sm-2">
                        <div class="form-group"><label>Loading</label><input type="number" id="loading" name="loading" step="0.01" class="form-control in_form input-height" value="0"></div>
                    </div>
                    <div class="col-sm-2">
                        <div class="form-group"><label>Vehicle Rent</label><input type="number" id="vehicle_rent" name="vehicle_rent" step="0.01" class="form-control in_form input-height" value="0"></div>
                    </div>
                    <div class="col-sm-2">
                        <div class="form-group"><label>CTN</label><input type="number" id="ctn" name="ctn" step="0.01" class="form-control in_form input-height" value="0"></div>
                    </div>
                    <div class="col-sm-2">
                        <div class="form-group"><label>Bora</label><input type="number" id="bora" name="bora" step="0.01" class="form-control in_form input-height" value="0"></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" readonly></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" step="0.01" 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 Received</label><input type="number" id="cash_received" name="cash_received" step="0.01" 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" 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 font-weight-bold">
                                <option style="font-weight:700;" value="cash">Cash</option>
                                <option style="font-weight:700;" value="credit">Credit</option>
                                <option style="font-weight:700;" value="bank1">Bank Al-Habib</option>
                                <option style="font-weight:700;" value="bank2">UBL Bank</option>
                                <option style="font-weight:700;" value="bank3">Meezan Bank</option>
                                <option style="font-weight:700;" value="others">Others</option>
                            </select>
                        </div>
                    </div>
                    <!-- NEW: Visible desc_note field placed right after Method -->
                    <div class="">
                        <div class="">
                          
                            <textarea style="display:none;" class="form-control in_form" name="desc_note" id="desc_note" style="height:30px;"></textarea>
                        </div>
                    </div>
                    <input type="hidden" id="productData" name="productData">
                    <div class="col-sm-6">
                        <hr>
                        <div class="btn-group w-100" role="group">
                            <button type="submit" name="bill" class="btn btn-dark btn-sm font-weight-bold w-100">Generate Invoice</button>
                            <a href="mainpos.php" class="btn btn-primary btn-sm font-weight-bold w-100" target="_blank">New Sale</a>
                            <button type="submit" name="refund" class="btn btn-danger btn-sm font-weight-bold w-100" style="display:none;">Refund</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
// Method change – disable cash input for credit
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;
    }
});

// Prevent submission if required fields missing
document.querySelector("button[name='bill']").addEventListener("click", function(event) {
    const method = document.getElementById("method").value;
    const customerName = document.getElementById("customer_name").value.trim();
    if (method === "credit" && customerName === "") {
        event.preventDefault();
        alert("Please fill in the Customer Name for Credit method.");
    }
});
document.querySelector("button[name='refund']").addEventListener("click", function(event) {
    const refundId = document.getElementById("r_order_id").value.trim();
    if (refundId === "") {
        event.preventDefault();
        alert("Please enter a Refund ID.");
    }
});

// ========== AJAX search for order ID ==========
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);
        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 && items[currentFocus]) selectOrder(items[currentFocus]); }
    }
});
function selectOrder(item) {
    document.getElementById("r_order_id").value = item.getAttribute('data-order-id');
    document.getElementById("order_suggestions").style.display = 'none';
}

// Customer search
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 && items[currentFocus]) selectCustomer(items[currentFocus]); }
    }
});
function selectCustomer(item) {
    document.getElementById("customer_name").value = item.getAttribute('data-customer-name');
    document.getElementById("customer_phone").value = item.getAttribute('data-customer-phone');
    document.getElementById("customer_id").value = item.getAttribute('data-customer-id');
    document.getElementById("city").value = item.getAttribute('data-city');
    document.getElementById("transport").value = item.getAttribute('data-transport');
    document.getElementById("pre_amount").value = item.getAttribute('data-remain-balance');
    document.getElementById("customer_suggestions").style.display = 'none';
}

// Product search and entry
let currentFocus = -1;
document.getElementById("productInput").addEventListener("input", function() {
    var query = this.value;
    if (query.length > 0) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "?query=" + query, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var suggestions = document.getElementById("suggestions");
                suggestions.innerHTML = xhr.responseText;
                suggestions.style.display = 'block';
            }
        };
        xhr.send();
    } else {
        document.getElementById("suggestions").style.display = 'none';
    }
});
document.getElementById("productInput").addEventListener("keydown", function(e) {
    if (e.key === "Enter") { e.preventDefault(); document.getElementById("makeEntry").click(); }
    var suggestions = document.getElementById("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 && items[currentFocus]) selectProduct(items[currentFocus]); }
    }
});
document.getElementById("suggestions").addEventListener("click", function(e) {
    if (e.target && e.target.classList.contains("dropdown-item")) selectProduct(e.target);
});
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 selectProduct(item) {
    document.getElementById("productInput").value = item.textContent;
    document.getElementById("productInput").setAttribute('data-product-id', item.getAttribute('data-product-id'));
    document.getElementById("productInput").setAttribute('data-product-quantity', item.getAttribute('data-product-quantity'));
    document.getElementById("productInput").setAttribute('data-supplier', item.getAttribute('data-supplier'));
    document.getElementById("productInput").setAttribute('data-company', item.getAttribute('data-company'));
    document.getElementById("productInput").setAttribute('data-category', item.getAttribute('data-category'));
    document.getElementById("productInput").setAttribute('data-trade-price', item.getAttribute('data-trade-price'));
    document.getElementById("productInput").setAttribute('data-product-unit', item.getAttribute('data-product-unit'));

    document.getElementById("remain_quantity").value = item.getAttribute('data-product-quantity');
    document.getElementById("p_price").value = item.getAttribute('data-trade-price');
    document.getElementById("retail_price").value = item.getAttribute('data-retail-price');
    // Populate the visible product_unit input
    document.getElementById("product_unit").value = item.getAttribute('data-product-unit') || '';

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

// Discount calculation
function calculateTotalPrice(triggeredBy = null) {
    let quantity = parseFloat(document.getElementById("quantity").value) || 0;
    let pricePerUnit = parseFloat(document.getElementById("retail_price").value) || 0;
    let totalPrice = quantity * pricePerUnit;
    let discountPercent = parseFloat(document.getElementById("percentage").value) || 0;
    let discountAmount = parseFloat(document.getElementById("disc_amount").value) || 0;
    if (triggeredBy === "percentage") {
        discountAmount = (totalPrice * discountPercent) / 100;
        document.getElementById("disc_amount").value = discountAmount.toFixed(0);
    }
    if (triggeredBy === "disc_amount") {
        discountPercent = (discountAmount * 100) / totalPrice;
        if (!isFinite(discountPercent)) discountPercent = 0;
        document.getElementById("percentage").value = discountPercent.toFixed(2);
    }
    let finalPrice = totalPrice - discountAmount;
    if (finalPrice < 0) finalPrice = 0;
    document.getElementById("total_amount").value = totalPrice.toFixed(2);
    document.getElementById("trade_price").value = finalPrice.toFixed(2);
}
document.getElementById("quantity").addEventListener("input", calculateTotalPrice);
document.getElementById("retail_price").addEventListener("input", calculateTotalPrice);
document.getElementById("percentage").addEventListener("input", () => calculateTotalPrice("percentage"));
document.getElementById("disc_amount").addEventListener("input", () => calculateTotalPrice("disc_amount"));

// Make Entry
document.getElementById("makeEntry").addEventListener("click", function () {
    const productInput = document.getElementById("productInput");
    const productId = productInput.getAttribute('data-product-id');
    const supplier = productInput.getAttribute('data-supplier');
    const company = productInput.getAttribute('data-company');
    const category = productInput.getAttribute('data-category');
    const tradePrice = productInput.getAttribute('data-trade-price');
    const productUnit = document.getElementById("product_unit").value;  // get value from visible input
    const description = productInput.value;
    const quantity = parseFloat(document.getElementById("quantity").value) || 0;
    const pricePerUnit = parseFloat(document.getElementById("retail_price").value) || 0;
    const totalPrice = parseFloat(document.getElementById("total_amount").value) || 0;
    const discountPercentage = parseFloat(document.getElementById("percentage").value) || 0;
    const discAmount = parseFloat(document.getElementById("disc_amount").value) || 0;
    const netAmount = parseFloat(document.getElementById("trade_price").value) || 0;

    if (productId && description && quantity && pricePerUnit && totalPrice && netAmount) {
        const table = document.getElementById("productsTable");
        const row = table.insertRow();
        // Row structure: hidden quantity, then visible: Item Code, Description, Unit, Qty, Unit Price, Amount, (hidden) Dis%, Dis PKR, Tax, Net Amount, (hidden) supplier, company, tradePrice, category, productUnit, Action, Edit
        row.innerHTML = `
            <td style="display:none;">${quantity}</td>
            <td>${productId}</td>
            <td style="color:#0A5064;font-weight:700;">${description}</td>
            <td>${productUnit}</td>
            <td>${quantity}</td>
            <td>${pricePerUnit}</td>
            <td>${totalPrice}</td>
            <td style="display:none;">${discountPercentage.toFixed(2)}</td>
            <td style="display:none;">${discAmount.toFixed(2)}</td>
            <td style="display:none;">0</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 style="display:none;">${productUnit}</td>
            <td><button class="btn btn-danger btn-sm delete-row">X</button></td>
            <td><button class="btn btn-danger btn-sm edit-row">+</button></td>
        `;
        row.querySelector(".delete-row").addEventListener("click", function () { row.remove(); calculateTotalAmount(); updateProductData(); });
        row.querySelector(".edit-row").addEventListener("click", function () {
            const cells = row.querySelectorAll("td");
            productInput.value = cells[2].innerText;
            productInput.setAttribute('data-product-id', cells[1].innerText);
            productInput.setAttribute('data-supplier', cells[11].innerText);
            productInput.setAttribute('data-company', cells[12].innerText);
            productInput.setAttribute('data-trade-price', cells[13].innerText);
            productInput.setAttribute('data-category', cells[14].innerText);
            productInput.setAttribute('data-product-unit', cells[15].innerText);
            document.getElementById("product_unit").value = cells[15].innerText; // set unit field from hidden cell
            document.getElementById("quantity").value = cells[4].innerText;
            document.getElementById("retail_price").value = cells[5].innerText;
            document.getElementById("total_amount").value = cells[6].innerText;
            document.getElementById("percentage").value = cells[7].innerText;
            document.getElementById("disc_amount").value = cells[8].innerText;
            document.getElementById("trade_price").value = cells[10].innerText;
            row.remove();
            calculateTotalAmount();
            updateProductData();
            productInput.focus();
        });
        calculateTotalAmount();
        updateProductData();   // This will no longer affect desc_note
        resetProductFields();
        productInput.focus();
    }
});

// Reset product fields
function resetProductFields() {
    document.getElementById("productInput").value = '';
    document.getElementById("remain_quantity").value = '';
    document.getElementById("quantity").value = '';
    document.getElementById("retail_price").value = '';
    document.getElementById("total_amount").value = '';
    document.getElementById("percentage").value = '';
    document.getElementById("disc_amount").value = '';
    document.getElementById("trade_price").value = '';
    document.getElementById("p_price").value = '';
    document.getElementById("product_unit").value = '';  // clear visible unit field
    document.getElementById("productInput").removeAttribute('data-category');
    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');
}

// Calculate totals including new charges
function calculateTotalAmount() {
    var rows = document.querySelectorAll("#productsTable tr:not(:first-child)");
    var total = 0;
    rows.forEach(function(row) {
        var netAmountCell = row.querySelectorAll("td")[10]; // index 10 = net amount
        if (netAmountCell) {
            var val = parseFloat(netAmountCell.textContent.trim());
            if (!isNaN(val)) total += val;
        }
    });
    document.getElementById("total-input").value = total.toFixed(2);
    document.getElementById("bill-amount").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 discountAmount = total - billAmount;
    document.getElementById("discount_amount").value = Math.round(discountAmount);
    var discountPercent = (total > 0) ? (discountAmount / total) * 100 : 0;
    document.getElementById("discount_percent").value = discountPercent.toFixed(2);
}

function updateGrandAmount() {
    var billAmount = parseFloat(document.getElementById("bill-amount").value) || 0;
    var preAmount = parseFloat(document.getElementById("pre_amount").value) || 0;
    var cutting = parseFloat(document.getElementById("cutting").value) || 0;
    var loading = parseFloat(document.getElementById("loading").value) || 0;
    var vehicleRent = parseFloat(document.getElementById("vehicle_rent").value) || 0;
    var ctn = parseFloat(document.getElementById("ctn").value) || 0;
    var bora = parseFloat(document.getElementById("bora").value) || 0;
    var grand = billAmount + preAmount + cutting + loading + vehicleRent + ctn + bora;
    document.getElementById("grand_amount").value = grand.toFixed(2);
    calculateCashReturn();
}

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

// Attach listeners to new charge inputs and existing ones
["cutting","loading","vehicle_rent","ctn","bora","bill-amount","pre_amount","cash_received"].forEach(function(id) {
    var el = document.getElementById(id);
    if (el) el.addEventListener("input", updateGrandAmount);
});

// Update product data hidden field (NO LONGER touches desc_note)
function updateProductData() {
    var rows = document.querySelectorAll("#productsTable tr:not(:first-child)");
    var products = [];
    rows.forEach(function(row) {
        var cells = row.querySelectorAll("td");
        if (cells.length >= 16) {
            products.push({
                productId: cells[1].innerText,
                description: cells[2].innerText,
                productUnit: cells[15].innerText, // from hidden cell storing unit
                quantity: cells[4].innerText,
                pricePerUnit: cells[5].innerText,
                totalPrice: cells[6].innerText,
                discountPercentage: cells[7].innerText,
                discAmount: cells[8].innerText,
                tax: cells[9].innerText,
                netAmount: cells[10].innerText,
                supplier: cells[11].innerText,
                company: cells[12].innerText,
                tradePrice: cells[13].innerText,
                category: cells[14].innerText
            });
        }
    });
    document.getElementById("productData").value = JSON.stringify(products);
}

// Watch for pre_amount changes dynamically
(function watchPreAmount() {
    var el = document.getElementById("pre_amount");
    var lastValue = el ? el.value : null;
    setInterval(function () {
        if (el && el.value !== lastValue) { lastValue = el.value; updateGrandAmount(); }
    }, 300);
})();

// Initial load
window.addEventListener("DOMContentLoaded", function () {
    calculateTotalAmount();
    updateGrandAmount();
});
</script>

    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>
</html>