<?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 {
    // Redirect to login page or handle the error
       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);
}

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

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

    while ($row = $result->fetch_assoc()) {
        $crName = $row['cr_name'];
        $crId = $row['cr_id'];
        $phone = $row['phone_number'];

        // Fetch remain_balance from creditor_closing
        $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-remain-balance='$remainBalance'>$crName</div>";
    }

    echo $suggestions;
    exit;
}


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

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

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

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

        $stmt->close();
    }

    $connection->close();
    exit;
}

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

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

    $productData = json_decode($_POST['productData'], true);
    $orderId = 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");

    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'];
        $sale_cost = $tradePrice * $productQuantity;
		$tp = $sale_cost;
        $sql = "INSERT INTO log_user_sales (
            product_id,
            supplier_name,
            company,
            category,
            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
        ) VALUES (
            '$productId',
            '$supplierName',
            '$company',
            '$category',
            '$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'
        )";
        
        if ($connection->query($sql) !== TRUE) {
            echo "Error: " . $sql . "<br>" . $connection->error;
            ob_end_flush();
            exit;
        }
 // Update product quantity based on payment type
            
                $updateSql = "UPDATE products SET 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>";
}

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

    // Invoice/Customer Info (use posted values)
    $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'];
    $desc_note = $_POST['desc_note'];

    // session fields (ensure these exist)
    $outlet_name    = $_SESSION['outlet_name'] ?? '';
    $outlet_address = $_SESSION['outlet_address'] ?? '';
    $login_user     = $_SESSION['user_name'] ?? '';
    $user_role      = $_SESSION['user_role'] ?? '';

    // Prepare the insert (37 columns -> 37 placeholders)
    $sql = "INSERT INTO log_user_sales (
        product_id, supplier_name, company, category, 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
    ) VALUES (" . rtrim(str_repeat('?,', 39), ',') . ")";

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

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

    // Begin transaction
    $connection->begin_transaction();

    try {
        foreach ($productData as $product) {
            // normalize incoming product fields (use defaults if missing)
            $productId    = (string)($product['productId'] ?? '');
            $supplierName = (string)($product['supplier'] ?? '');
            $company      = (string)($product['company'] ?? '');
            $category      = (string)($product['category'] ?? '');
            $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');

            // Derived values for refund
            $negQuantity = (string)(-1 * $productQty); // stored in product_quantity column (as varchar)
            $refundAmount = (float)$tradePrice * $productQty; // numeric for stock update/total_amount
            $tax_amount = (string)$tax; // you can adjust if you compute separately
            $total_amount = (string)$productTotal; // keep same representation
            $BillAmount = (string)$discount_amount; // use posted bill_amount value for this refund row
            $sale_cost = (string)($tradePrice * $productQty);

            // Bind 37 string parameters (table uses varchar for most fields)
            // All params as strings to avoid type issues
            $bindTypes = str_repeat('s', 39);

            $params = [
                $productId, $supplierName, $company, $category, $productName,
                $productPrice, $tradePrice, $negQuantity, $productTotal,
                '0', /* bonus */
                $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
            ];

            // bind_param requires variables, so use call_user_func_array
            $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);
            }

            // update stock: increase quantity, increase total_amount
            // use numeric refundAmount for arithmetic
            $refundAmountNum = (float)$refundAmount;
            $updateStockStmt->bind_param('dds', $productQty, $refundAmountNum, $productId);
            if (!$updateStockStmt->execute()) {
                throw new Exception("Stock update failed: " . $updateStockStmt->error);
            }
        }

        // commit if all good
        $connection->commit();
        $stmt->close();
        $updateStockStmt->close();

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

    } catch (Exception $e) {
        $connection->rollback();
        // show safe error (you can log $e->getMessage())
        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;
            display:
        }
        .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; /* space between buttons */
  }
  .btn-group .btn:last-child {
    margin-right: 0; /* no space on last */
  }
.btn-primary{
    background:#0A4657;
    color:#fff;
    border:1px solid #0A4657;
}
.btn-primary:hover{
    background:#fff;
    color:#0A4657;
    border:1px solid #0A4657;
}
.form-control{
    font-size:15px;
}  
</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;" width="56" height="56">
        </div>
        <div class="col-sm-6">
        <h3 class="mb-4" style="color:#fff; font-weight:700; text-align:center; text-transform:uppercase;line-height:60px;"><?php echo $tx; ?></h3>
        
        </div>
        <div class="col-sm-3">
            <a href="addproduct.php" class="btn btn-light" style="margin-top:20px; float:right; font-weight:700" >Back</a>
                
        </div>
    </div>
</div>
<div class="container-fluid">
    <form action="mainpos.php" method="post" enctype="multipart/form-data">
        <div class="row">
            <div class="col-sm-3" style="background:#F0F0F0; padding:10px; border:1px solid #CCC;">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">Product</span>
                    </div>
                    <input type="text" class="form-control" id="productInput" placeholder="Start typing a product name..." autocomplete="off">
                    <div style="font-weight:700;" class="dropdown-menu" id="suggestions"></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">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">Price / Unit</span>
                    </div>
                    <input type="text" id="retail_price" name="retail_price" class="form-control" placeholder="">
                </div>
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">Total Price</span>
                    </div>
                    <input type="text" id="total_amount" name="total_amount" class="form-control" placeholder="" readonly>
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">-/ PKR</span>
                    </div>
                </div>
               <div class="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="">
                </div>
                <div class="input-group mb-3 col-6">
                    <input type="text" id="disc_amount" name="disc_amount" class="form-control"  placeholder="">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">Dis PKR</span>
                    </div>
                </div>
               </div>
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-dark text-white">Total Price</span>
                    </div>
                    <input type="text" id="trade_price" name="trade_price" class="form-control" placeholder="" readonly>
                </div>
                <br>
                <button type="button" class="form-control btn btn-dark" id="makeEntry">Make Entry</button>
                <hr>
                <div class="row">
                <div class="col-6">
                <button type="button" class="form-control btn btn-dark" onclick="location.reload();">Refresh</button>
                </div>
                <div class="col-6">
                    <a href="order_detail_v.php" class="btn btn-primary form-control">View Sales </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="">
                 
                        <input type="hidden"  name="customer_type" class="form-control" value="walkin">
                          
                      </div>
                    </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="">
                      <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>Refund ID</label>
                        <input type="text" id="r_order_id" name="r_order_id" class="form-control in_form">
                        <div id="order_suggestions" class="dropdown-menu" style="display: none;"></div>
                      </div>
                    </div>
                </div>
                <div class="row" style="background:#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>Qty</td>
                                <td>Unit Price</td>
                                <td>Amount</td>
                                <td>Dis%</td>
                                <td>Dis PKR</td>
                                <td>Tax</td>
                                <td>Net Amount</td>
                                <td>Action</td>
                                <td>Edit</td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div class="row" style="margin-top: -10px;">
                    <div class="col-sm-12" style="background:#F0F0F0; padding:10px; border:1px solid #CCC;">
                        <br>
                        <div class="row">
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Total</label>
                                    <input type="text" id="total-input" name="total_input" class="form-control in_form input-height" readonly>
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Bill Amount</label>
                                    <input type="text" id="bill-amount" name="bill_amount" class="form-control in_form input-height" required>
                                </div>
                            </div>
                            
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Previous</label>
                                    <input type="text" id="pre_amount" 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" 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" name="discount_amount" class="form-control in_form input-height">
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                   <label>Discount %</label>
                                    <input type="number" id="discount_percent" name="discount_percent" class="form-control in_form input-height" readonly>
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Cash Received</label>
                                    <input type="number" id="cash_received" name="cash_received" class="form-control in_form input-height">
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>Cash Remaining</label>
                                    <input type="number" id="cash_return" 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 style="font-weight:700;" value="bank1">Bank 1</option>
                                    <option style="font-weight:700;" value="bank2">Bank 2 </option>
                                    <option style="font-weight:700;" value="bank3">Bank 3</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>
                                <div class="btn-group w-30 " role="group">
                                  <button type="submit" name="bill" class="btn btn-dark btn-sm font-weight-bold">
                                    Generate Invoice
                                  </button>
                                  <a href="mainpos.php" class="btn btn-primary btn-sm font-weight-bold" target="_blank">
                                    New Sale
                                  </a>
                                  <button type="submit" name="refund" class="btn btn-danger btn-sm font-weight-bold">
                                    Refund
                                  </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
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>
document.addEventListener("DOMContentLoaded", function() {
    const generateInvoiceButton = document.querySelector("button[name='bill']");
    const refundButton = document.querySelector("button[name='refund']");

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

        if (method === "credit" && customerName === "") {
            event.preventDefault();
            alert("Please fill in the Customer Name for Credit method.");
        }
    });

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

        if (refundId === "") {
            event.preventDefault(); 
            alert("Please enter a Refund ID.");
        }
    });
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    let currentFocus = -1;

    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) {
                    if (items[currentFocus]) {
                        selectOrder(items[currentFocus]);
                    }
                }
            }
        }
    });

    function addActive(items) {
        if (!items) return false;
        removeActive(items);
        if (currentFocus >= items.length) currentFocus = 0;
        if (currentFocus < 0) currentFocus = items.length - 1;
        items[currentFocus].classList.add("active");
        items[currentFocus].scrollIntoView({ block: "nearest" });
    }

    function removeActive(items) {
        for (var i = 0; i < items.length; i++) {
            items[i].classList.remove("active");
        }
    }

    function selectOrder(item) {
        var orderId = item.getAttribute('data-order-id');
        document.getElementById("r_order_id").value = orderId;
        document.getElementById("order_suggestions").style.display = 'none';
    }

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

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

    document.getElementById("customer_name").addEventListener("keydown", function(e) {
        var suggestions = document.getElementById("customer_suggestions");
        if (suggestions.style.display === 'block') {
            var items = suggestions.getElementsByClassName("dropdown-item");
            if (e.key === "ArrowDown") {
                currentFocus++;
                addActive(items);
            } else if (e.key === "ArrowUp") {
                currentFocus--;
                addActive(items);
            } else if (e.key === "Enter") {
                e.preventDefault();
                if (currentFocus > -1) {
                    if (items[currentFocus]) {
                        selectCustomer(items[currentFocus]);
                    }
                }
            }
        }
    });

    function addActive(items) {
        if (!items) return false;
        removeActive(items);
        if (currentFocus >= items.length) currentFocus = 0;
        if (currentFocus < 0) currentFocus = items.length - 1;
        items[currentFocus].classList.add("active");
        items[currentFocus].scrollIntoView({ block: "nearest" });
    }

    function removeActive(items) {
        for (var i = 0; i < items.length; i++) {
            items[i].classList.remove("active");
        }
    }

function selectCustomer(item) {
    var customerName = item.getAttribute('data-customer-name');
    var customerId = item.getAttribute('data-customer-id');
    var customerPhone = item.getAttribute('data-customer-phone');
    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';
}


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


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

    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) {
        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) {
                    if (items[currentFocus]) {
                        selectProduct(items[currentFocus]);
                    }
                }
            }
        }
    });

    function addActive(items) {
        if (!items) return false;
        removeActive(items);
        if (currentFocus >= items.length) currentFocus = 0;
        if (currentFocus < 0) currentFocus = items.length - 1;
        items[currentFocus].classList.add("active");
        items[currentFocus].scrollIntoView({ block: "nearest" });
    }

    function removeActive(items) {
        for (var i = 0; i < items.length; i++) {
            items[i].classList.remove("active");
        }
    }

const productInput = document.getElementById("productInput");

productInput.addEventListener("keypress", function (e) {
    if (e.key === "Enter") {
        e.preventDefault(); 
        document.getElementById("makeEntry").click();
    }
});

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

    const input = document.getElementById("productInput");
    input.value = selectedProduct;
    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-category', category);
    input.setAttribute('data-trade-price', tradePrice);
    input.setAttribute('data-product-unit', productUnit);

    document.getElementById("remain_quantity").value = productQuantity;
    document.getElementById("p_price").value = tradePrice;
    document.getElementById("retail_price").value = retailPrice;
    document.getElementById("suggestions").style.display = 'none';

    calculateTotalPrice();
}


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 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.innerHTML = `
            <td style="display:none;">${quantity}</td>
            <td>${productId}</td>
            <td style="color:#0A5064;font-weight:700px;">${description}</td>
            <td>${quantity}</td>
            <td>${pricePerUnit}</td>
            <td>${totalPrice}</td>
            <td>${discountPercentage.toFixed(2)}</td>
            <td>${discAmount.toFixed(2)}</td>
            <td>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><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();
        });
        
        

        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[9].innerText);
            productInput.setAttribute('data-company', cells[10].innerText);
            productInput.setAttribute('data-trade-price', cells[11].innerText);

            document.getElementById("quantity").value = cells[3].innerText;
            document.getElementById("retail_price").value = cells[4].innerText;
            document.getElementById("total_amount").value = cells[5].innerText;
            document.getElementById("percentage").value = cells[6].innerText;
            document.getElementById("disc_amount").value = cells[7].innerText;
            document.getElementById("trade_price").value = cells[8].innerText;

            
            row.remove();
            calculateTotalAmount();

            productInput.focus();
        });

        calculateTotalAmount();

        const rows = document.querySelectorAll("#productsTable tr:not(:first-child)");
        const productData = [];
        rows.forEach(function (row) {
            const cells = row.querySelectorAll("td");
            const product = {
                productId: cells[1].innerText,
                description: cells[2].innerText,
                quantity: cells[3].innerText,
                pricePerUnit: cells[4].innerText,
                totalPrice: cells[5].innerText,
                discountPercentage: cells[6].innerText,
                discAmount: cells[7].innerText,
                tax: cells[8].innerText,
                netAmount: cells[9].innerText,
                supplier: cells[10].innerText,
                company: cells[11].innerText,
                tradePrice: cells[12].innerText,
                category: cells[13].innerText,
            };
            productData.push(product);
        });

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

        resetProductFields();
        productInput.focus();
    }
});

// document.querySelectorAll("#productInput, #quantity, #retail_price, #total_amount, #dis_percent, #percentage, #trade_price").forEach(function(input) {
//     input.addEventListener("keydown", function(e) {
//         if (e.key === "Enter") {
//             e.preventDefault(); 
//             document.getElementById("makeEntry").click(); 
//         }
//     });
// });
document.querySelector("form").addEventListener("keydown", function(e) {
    if (e.key === "Enter" && e.target.type !== "submit") {
        e.preventDefault();
    }
});


    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("remain_quantity").value = '';
        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');
    }

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[9];
        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");

    if (!isNaN(grandAmount) && !isNaN(cashReceived)) {
        var cashReturn = grandAmount - cashReceived;
        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);

(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();
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</body>
</html>