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

 // Check if the user is logged in
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>alert('!!!!Session Destry Please Login again!!!!'); location.href='logout.php;</script>";
}
$products = [];
$query = '';
$status = "";

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["vfd_send"])) {
    $product_name = substr(trim($_POST["product_name"]), 0, 16);
    $product_price = $_POST["product_price"];

    $comPort = "COM3"; // Change if your VFD is on COM1, COM4, etc.

    $combined = str_pad($product_name, 16) . substr("Rs." . $product_price, 0, 4);

    exec("mode $comPort: BAUD=9600 PARITY=n DATA=8 STOP=1 xon=off");
    $fp = @fopen($comPort, "w+");

    if ($fp) {
        fwrite($fp, chr(12)); // Clear screen
        usleep(50000);
        fwrite($fp, $combined);
        fclose($fp);
        echo json_encode(["status" => "success", "message" => $combined]);
    } else {
        echo json_encode(["status" => "error", "message" => "❌ Could not open $comPort"]);
    }
    exit;
}
if (isset($_GET['product_input'])) {
    $term = mysqli_real_escape_string($connection, $_GET['product_input']);
    $res = mysqli_query($connection, "SELECT * FROM products WHERE product_id LIKE '%$term%' OR product_name LIKE '%$term%'");
    
    $data = [];
    while ($row = mysqli_fetch_assoc($res)) {
       $data[] = [
                  'product_id' => $row['product_id'],
                  'product_name' => $row['product_name'],
                  'retail_price' => $row['retail_price'],
                  'trade_price' => $row['trade_price'],
                  'wholesale_price' => $row['wholesale_price'],
                  'price' => $row['retail_price'],
                  'wh_percentage' => $row['wh_percentage'] 
                ];
    }
    echo json_encode($data);
    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'];
        // 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 = htmlspecialchars($remainRow['remain_balance']);
        }
        $suggestions .= "<div class='dropdown-item' data-customer-name='$crName' 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; // End the PHP processing for AJAX request here
}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_sale'])) {
    $orderId = "OR" . str_pad(rand(0, 99999), 5, "0", STR_PAD_LEFT);
    $customer_name = $_POST['customer_name'] ?? '';
    $customer_type = $_POST['customer_type'] ?? '';
    $discount = $_POST['discount'] ?? 0;
    $tax = $_POST['tax'] ?? 0;
    $cart = json_decode($_POST['cart'], true);
    $date_time = date("d-m-Y");
    $d_date = $_POST['d_date'];
    $paid_by = $_POST["paid_by"];
    foreach ($cart as $item) {
        $product_id = $item['id'];
        $product_name = $item['name'];
        $product_price = $item['price'];
        $trade_price = $item['trade'];
        $qty = $item['qty'];
        $wh_percentage = $item['wh_percentage'];
        $product_total = $product_price * $qty;
        $sale_cost = $trade_price * $qty;
        $net = $product_total;
        $discount_amount = $_POST['discount_amount'] ?? 0; // from total field
        $pre_amount = $_POST['pre_amount'] ?? 0; // from total field
        $grand_amount = $_POST['grand_amount'] ?? 0; // from total field
        $cash_recieved = $_POST['cash_recieved'] ?? 0; // from total field
        $cash_return = $_POST['cash_return'] ?? 0; // from total field
        $tax_amount = $tax;
        $total_amount = ((int)$net + (int)$tax_amount) - (int)$discount_amount;
        $sql = "INSERT INTO log_user_sales (
            product_id, supplier_name, company, product_name, product_price, trade_price,
            product_quantity, product_total, wh_percentage, bonus, discount, tax, net_amount, tax_amount,
            total_amount, paid_by, sale_cost, customer_id, customer_type, customer_name,
            customer_phone, discount_amount, discounted, discount_per, cash_amount,
            change_amount, pre_amount, grand_amount, order_id, r_order_id, status, cash_recieved, cash_return, outlet_name, login_user, user_role,
            outlet_address, date_time, d_date
        ) VALUES (
            '$product_id', '', '', '$product_name', '$product_price', '$trade_price',
            '$qty', '$product_total', '$wh_percentage', 0, '$discount', '$tax', '$net', '$tax_amount',
            '$total_amount', '$paid_by', '$sale_cost', '', '$customer_type', '$customer_name', '',
            '$discount_amount', '$discount', '$discount', 0, 0, '$pre_amount', '$grand_amount', '$orderId', '', '', '$cash_recieved', '$cash_return', '$outlet_name', '$userName', '$userRole', '$outlet_address', '$date_time', '$d_date'
        )";
        mysqli_query($connection, $sql);
        
         $updateSql = "UPDATE products SET quantity = quantity - $qty, total_amount = total_amount - $sale_cost  WHERE product_id = '$product_id'";
          
            if ($connection->query($updateSql) !== TRUE) {
                throw new Exception("Error updating product quantity: " . $connection->error);
            }
    }
    header("Location: printtype.php?order_id=$orderId");
exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['refund_sale'])) {
    $orderId = $_POST['r_order_id'];
    $r_orderId = $orderId;
    $customer_name = $_POST['customer_name'] ?? '';
    $customer_type = $_POST['customer_type'] ?? '';
    $discount = $_POST['discount'] ?? 0;
    $tax = $_POST['tax'] ?? 0;
    $cart = json_decode($_POST['cart'], true);
    $date_time = date("Y-m-d");
    $status = 'refund';
    $paid_by = $_POST["paid_by"];
    foreach ($cart as $item) {
        $product_id = $item['id'];
        $product_name = $item['name'];
        $product_price = $item['price'];
        $trade_price = $item['trade'];
        $qty = $item['qty'];
        $wh_percentage = $item['wh_percentage'];
        $product_total = $product_price * $qty;
        $sale_cost = $trade_price * $qty;
        $net = $product_total;
        $discount_amount = $_POST['discount_amount'] ?? 0; // from total field
        $pre_amount = $_POST['pre_amount'] ?? 0; // from total field
        $grand_amount = $_POST['grand_amount'] ?? 0; // from total field
        $tax_amount = $tax;
        $total_amount = ((int)$net + (int)$tax_amount) - (int)$discount_amount;
        $sql = "INSERT INTO log_user_sales (
            product_id, supplier_name, company, product_name, product_price, trade_price,
            product_quantity, product_total, wh_percentage, bonus, discount, tax, net_amount, tax_amount,
            total_amount, paid_by, sale_cost, customer_id, customer_type, customer_name,
            customer_phone, discount_amount, discounted, discount_per, cash_amount,
            change_amount, pre_amount, grand_amount, order_id, r_order_id, status, outlet_name, login_user, user_role,
            outlet_address, date_time
        ) VALUES (
            '$product_id', '', '', '$product_name', '$product_price', '$trade_price',
            '$qty', '$product_total', '$wh_percentage', 0, '$discount', '$tax', '$net', '$tax_amount',
            '$total_amount', '$paid_by', '$sale_cost', '', '$customer_type', '$customer_name', '',
            '$discount_amount', '$discount', '$discount', 0, 0, '$pre_amount', '$grand_amount', '$orderId', '$r_orderId', '$status', '$outlet_name', '$userName', '$userRole', '$outlet_address', '$date_time'
        )";
        mysqli_query($connection, $sql);
        
         $updateSql = "UPDATE products SET quantity = quantity + $qty, total_amount = total_amount + $sale_cost  WHERE product_id = '$product_id'";
          
            if ($connection->query($updateSql) !== TRUE) {
                throw new Exception("Error updating product quantity: " . $connection->error);
            }
    }
    echo "<script>alert('Sale is Refunded with Order ID: $orderId'); location.href='mainpos.php';</script>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Kashmir Bazaar</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet" />
  <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
  <!-- Font Awesome CDN -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"  />
  <style>
   #table-container-single {
    max-height: 390px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}
   #table-container {
    max-height: 790px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}
    body {
      background-color: #f6f8fb;
      font-family: 'Quicksand', sans-serif;
    }
    .product-card {
      border: 1px solid #dedede;
      border-radius: 12px;
      padding: 6px;
      text-align: center;
      margin-bottom: 15px;
      font-size: 13px;
      position: relative;
      background: #fff;
      transition: box-shadow 0.2s, transform 0.1s;
      height: 200px;
    }
    .product-card:hover {
      box-shadow: 0 0 12px rgba(0,0,0,0.1);
      transform: translateY(-1px);
      cursor: pointer;
    }
    .product-image {
      height: 95px;
      width: 100%;
      object-fit: contain;
      margin-bottom: 5px;
    }
    .product-price,
    .product-qty {
      font-size: 11px;
      font-weight: 500;
      padding: 2px 8px;
      border-radius: 50px;
      position: absolute;
      z-index: 1;
    }
    .product-price {
      top: 6px;
      left: 6px;
      background-color: #343a40;
      color: white;
    }
    .product-qty {
      top: 6px;
      right: 6px;
      background-color: #0d6efd;
      color: white;
    }
    .left-panel {
      height: calc(100vh - 60px);
      overflow-y: auto;
      border-right: 1px solid #ccc;
      background-color: #fff;
    }
    .product-list {
      max-height: 76vh;
      overflow-y: auto;
    }
    .top-icons i {
      font-size: 1.3rem;
      margin-left: 10px;
      color: white;
      background: #007bff;
      border-radius: 12px;
      padding: 6px;
      width: 34px;
      height: 34px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .form-check-label, .form-label {
      font-size: 12px;
    }
    .table thead th, .table tbody td {
      font-size: 12px;
      padding: 6px;
    }
    .btn-sm {
      font-size: 12px;
      padding: 3px 8px;
      font-weight:700;
    }
    .form-select-sm, .form-control-sm {
      font-size: 13px;
      font-weight:600;
      text-transform:capitalize;
    }
    .brand-filter input {
      width: 60px;
    }
    .btn-outline-primary, .btn-outline-dark {
      border-radius: 10px;
    }
    .form-control::placeholder {
      font-size: 12px;
    }
    .category-buttons, .brand-filter {
      white-space: nowrap;
      overflow-x: auto;
    }
    .form-control, label{
        font-weight:700;
    }
    .btn-primary{
        background:#0a4657;
        COLOR:#FFF;
        border:1px solid #0A4657;
    }
    .btn-primary:hover{
         background:#fff;
        COLOR:#0A4657;
        border:1px solid #0A4657;
    }
    option{
        font-weight:700;
    }
    .dropdown-menu {
    max-height: 200px;
    overflow-y: auto;
    position: absolute;
    z-index: 1000;
    width: 320px;
        }
        .input-group {
            position: relative;
        }
		.dropdown-item.active, .dropdown-item:active {
    color: #fff;
    text-decoration: none;
    background-color: #0A5064;
}
h6, .btn{
    font-weight:700;
}
#suggestions {
            max-height: 200px;
            overflow-y: auto;
        }
  </style>
</head>
<body>
  <div class="container-fluid">
<form method="post" onsubmit="return submitSale(event);">
  <input type="hidden" name="cart" id="cartData" />

    <input type="hidden" name="discount_amount" id="discountAmount" />
<input type="hidden" name="pre_amount" id="pre_amount_hidden" />
<input type="hidden" name="grand_amount" id="grand_amount_hidden" />
    <div class="row align-items-center p-2 bg-white border-bottom">
      <div class="col-md-3 d-flex align-items-center">
   
  <select class="form-select form-select-sm me-2" id="customerType" name="customer_type">
    <option value="retail">walk-in-customer </option>
    <option value="wholesale">WholeSale</option>
  </select>
        <button class="btn btn-primary btn-sm"><i class="bi bi-person-fill"></i></button>
      </div>
      <div class="col-md-3">
        <select class="form-select form-select-sm">
          <option>Kashmir Bazar</option>
        </select>
      </div>
      <div class="col-md-4">
          <div class="form-group">
          
            <input type="text" id="customer_history_input" name="customer_history" placeholder="Customer History" class="form-control w-50 d-inline-block me-2">

<button type="button" class="btn btn-dark" onclick="goToCustomerHistory()">Get</button>
          </div>
         <?php if (!empty($status)) echo "<div class='status'>$status</div>"; ?>
      </div>
      <div class="col-md-2 d-flex justify-content-end top-icons">
  <a href="credits.php" target="blank">
    <i style="background:#84BC2F; border-radius:7px;" class="fas fa-users fa-1x me-2"  data-bs-toggle="tooltip" title="Add Customer"></i>
  </a>
  <a href="mainpos.php">
    <i style="background:#84BC2F; border-radius:7px;" class="fas fa-sync fa-1x me-2" data-bs-toggle="tooltip" title="Refresh"></i>
  </a>
  <i id="fullscreenToggle" style="background:#84BC2F; border-radius:7px; cursor:pointer;" class="fas fa-arrows-up-down-left-right fa-1x me-2"
  data-bs-toggle="tooltip" title="FullScreen"></i>
  <a href="dashboard.php">
    <i style="background:#84BC2F; border-radius:7px;" class="fas fa-gauge fa-1x" data-bs-toggle="tooltip" title="Dashboard"></i>
  </a>
</div>
    </div>
    <div class="row">
      <!-- Left Panel -->
      <div class="col-md-4 p-3 left-panel">
         <div class="row">
          <div class="form-group col-6">
              <input type="text" name="customer_name" id="customer_name" class="form-control form-control-sm" placeholder=" Customer Name" >
              <div class="dropdown-menu" id="customer_suggestions"></div>
          </div>
          <div class="form-group col-6">
          <input type="text" id="productInput" class="form-control form-control-sm" placeholder="Scan / Product ID#" autocomplete="off" />
          <div id="suggestions" class="dropdown-menu " style="display: none; position: absolute; width:300px;"></div>
           </div>
          </div> 
       <hr>
       <div class="row">
            <div class="form-group col-6">
                <input type="text" id="r_order_id" name="order_id" class="form-control form-control-sm" placeholder="Refund ID#">
                <div id="order_suggestions" class="dropdown-menu" style="display: none;"></div>
            </div>
    <div class="form-group col-6">
  <input 
    type="text" 
    name="d_date" 
    id="d_date" 
    class="form-control form-control-sm" 
    data-bs-toggle="tooltip" 
    data-bs-placement="top" 
    title="Select the Delivery Challan Date"
    placeholder="dd-mm-yyyy">
    </div>
    </div>
          <hr>
          <div style="height:300px;" id="table-container-single">
          <table class="table stripped text-center">
              <thead class="table-light">
                <tr>
                  <th style="font-size:12px;">PRODUCT</th>
                  <th style="font-size:12px;">QTY</th>
                  <th style="font-size:12px;">PRICE</th>
                  <th style="font-size:12px;">WH %</th>
                  <th style="font-size:12px;">SUB TOTAL</th>
                  <th style="font-size:12px;"><i class="text-danger fas fa-trash fa-1x"></i></th>
                </tr>
               </thead>
               <tbody id="cart-body">
                <tr><td colspan="6" class="text-center" style="font-weight:700;">No Data Available</td></tr>
              </tbody>
            </table>
           </div>
        <div class=" row mb-2">
       <div class="form-group col-6">
          <input type="text" class="form-control form-control-sm mb-2" placeholder="Tax" />
       </div>
       <div class="col-6">
          <label class="form-label">Discount</label>
          <div class="form-check">
            <input class="form-check-input" type="radio" name="discountType" checked />
            <label class="form-check-label">Fixed</label>
          </div>
         
          <div class="form-check">
            <input class="form-check-input" type="radio" name="discountType" />
            <label class="form-check-label">Percentage</label>
          </div>
           </div>
           <div class="col-6">
             <input type="text" class="form-control form-control-sm mt-2" placeholder="Discount" />  
           </div>
          <div class="col-6">
          <input type="text" class="form-control form-control-sm mt-2" placeholder="Shipping" />
          </div>
          <div class="form-group">
          
              <select name="paid_by" class="form-control form-control-sm mt-2" required>
                  <!--<option value="">Zahlungsart</option>-->
                  <option value="cash">Bar</option>
                  <option value="credit">Kredit</option>
                  <option value="bank">EC.Karte</option>
              </select>
          </div>
        </div>
        <div class="d-flex justify-content-between ">
          <span class="qty-total" style="font-weight:600;">Total QTY : 0</span>
<span class="subtotal-amount">Sub Total : €0.00</span>
        </div>
        <h5 class="text-end total-amount" style="display:none;">Total : €0.00</h6>
        <h5 class="text-end">Previous : €<span id="pre_amount">0.00</span></h5>
<h5 class="text-end">Grand : €<span id="grand_amount">0.00</span></h5>
 <div class="row">
            <div class="col-6">
                <div class="form-group">
                    <input type="text" style="height:27px;" name="cash_recieved" id="cash_recieved" class="form-control" placeholder="Cash Recieved"  >
                </div>
            </div>
            <div class="col-6">
                <input type="text" style="height:27px;" name="cash_return" id="cash_return" class="form-control" placeholder="Cash Return" readonly >
            </div>
        </div>
        <div class="d-flex justify-content-between mt-3" >
         <button type="submit" name="refund_sale" value="1" class="btn btn-dark w-50" style="font-weight:700;">ReFund</button>&nbsp;
  <button type="submit" name="submit_sale" value="1" class="btn btn-success w-50" style="font-weight:700;">Pay Now</button>
</form>
        </div>
       
      </div>
      <!-- Right Product Panel -->
<div class="col-md-8 p-3" id="table-container">
  <div >

    <!-- Category Buttons -->
    <div class="mb-2 category-buttons">
      <?php $ca = mysqli_query($connection, "SELECT * FROM category"); ?>
      <button type="button" class="btn btn-primary  me-1">All Categories</button>
      <?php while ($cat = mysqli_fetch_assoc($ca)) : ?>
        <button type="button" class="btn btn-primary  me-1 text-capitalize">
          <?= htmlspecialchars($cat['category']) ?>
        </button>
      <?php endwhile; ?>
    </div>

    <!-- Product Cards Grid -->
    <div class="row row-cols-1 row-cols-md-4 g-3 product-list" id="product-list">
      <?php
      $pr = mysqli_query($connection, "SELECT * FROM products");
      while ($row = mysqli_fetch_assoc($pr)) :
      ?>
        <div class="col">
          <div
            class="product-card shadow-sm"
            tabindex="0"
            aria-label="Add <?= htmlspecialchars($row['product_name']) ?> to cart"
            data-id="<?= htmlspecialchars($row['product_id']) ?>"
            data-name="<?= htmlspecialchars($row['product_name']) ?>"
            data-price="<?= htmlspecialchars($row['retail_price']) ?>"
            data-trade="<?= htmlspecialchars($row['trade_price']) ?>"
            data-wholesale="<?= htmlspecialchars($row['wholesale_price']) ?>"
            data-category="<?= htmlspecialchars($row['category']) ?>"
            data-whpercentage="<?= htmlspecialchars($row['wh_percentage']) ?>"
          >
            <div class="product-price fw-bold" style="font-size:16px;">€<?= number_format(htmlspecialchars($row['retail_price']), 2) ?></div>
            <div class="product-qty fw-bold" style="background:#84BC2F;font-size:16px;">
              <?= htmlspecialchars($row['quantity']) ?>
            </div>
            <br><br>
            <img src="<?= htmlspecialchars($row['img_upload']) ?>" class="product-image" alt="<?= htmlspecialchars($row['product_name']) ?>" />
            <div class="fw-semibold text-truncate px-2" title="<?= htmlspecialchars($row['product_name']) ?>">
              <label style="font-size:16px;text-transform:capitalize;">
                <?= htmlspecialchars($row['product_name']) ?>
              </label>
            </div>
            <small class="text-muted d-block fw-bold">
              <?= htmlspecialchars($row['product_id']) ?>
            </small>
          </div>
        </div>
      <?php endwhile; ?>
    </div>

  </div> <!-- #table-container -->
</div>

  </div>
  <script>
document.getElementById("customerType").addEventListener("change", function() {
    let dateInput = document.getElementById("d_date");
    if (this.value === "wholesale") {
        dateInput.setAttribute("required", "required");
    } else {
        dateInput.removeAttribute("required");
    }
});
</script>
  <script>
document.addEventListener('DOMContentLoaded', function () {
  var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
  tooltipTriggerList.forEach(function (tooltipTriggerEl) {
    new bootstrap.Tooltip(tooltipTriggerEl)
  })
});
</script>

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

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

    // Add keyboard navigation for dropdown items
    document.getElementById("r_order_id").addEventListener("keydown", function(e) {
        var suggestions = document.getElementById("order_suggestions");
        if (suggestions.style.display === 'block') {
            var items = suggestions.getElementsByClassName("dropdown-item");
            if (e.key === "ArrowDown") {
                currentFocus++;
                addActive(items);
            } else if (e.key === "ArrowUp") {
                currentFocus--;
                addActive(items);
            } else if (e.key === "Enter") {
                e.preventDefault();
                if (currentFocus > -1) {
                    if (items[currentFocus]) {
                        selectOrder(items[currentFocus]);
                    }
                }
            }
        }
    });

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

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

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

document.querySelectorAll('.product-card').forEach(card => {
    card.addEventListener('click', function () {
        const productName = this.getAttribute('data-name');
        const productPrice = this.getAttribute('data-price');

        fetch(window.location.href, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `vfd_send=1&product_name=${encodeURIComponent(productName)}&product_price=${encodeURIComponent(productPrice)}`
        })
        .then(res => res.json())
        .then(data => {
            console.log("✅ VFD: " + data.message);
        })
        .catch(err => {
            console.error("❌ Error sending to VFD:", err);
        });
    });
});


function selectCustomer(item) {
    const customerName = item.getAttribute('data-customer-name');
    const remainBalance = parseFloat(item.getAttribute('data-remain-balance')) || 0;

    document.getElementById('customer_name').value = customerName;
    document.getElementById('pre_amount').textContent = remainBalance.toFixed(2);
    updateGrandAmount();

    const suggestions = document.getElementById("customer_suggestions");
    suggestions.style.display = 'none';
    suggestions.classList.remove('show');
}

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

</script>
<script>
let cart = [];

function getSubtotal() {
  return cart.reduce((sum, p) => sum + p.price * p.qty, 0);
}

function getTotalQty() {
  return cart.reduce((sum, p) => sum + p.qty, 0);
}

function getPrevious() {
  const preText = document.getElementById('pre_amount').textContent.replace(/[^\d.]/g, '');
  return parseFloat(preText) || 0;
}

function updateGrandAmount() {
  const subtotal = getSubtotal();
  const previous = getPrevious();
  const grand = subtotal + previous;

  document.querySelector('.subtotal-amount').textContent = 'Sub Total : €' + subtotal.toFixed(2);
  document.querySelector('.total-amount').textContent = 'Total : €' + subtotal.toFixed(2);
  document.querySelector('.qty-total').textContent = 'Total QTY : ' + getTotalQty();

  document.getElementById('grand_amount').textContent = grand.toFixed(2);
  document.getElementById('grand_amount_hidden').value = grand.toFixed(2);
  document.getElementById('pre_amount_hidden').value = previous.toFixed(2);

  // bind cash received input listener
  const cashInput = document.getElementById('cash_recieved');
  const cashReturn = document.getElementById('cash_return');

  cashInput.addEventListener('input', () => {
    const cashVal = parseFloat(cashInput.value);
    if (!isNaN(cashVal)) {
      const change = cashVal - grand;
      cashReturn.value = change >= 0 ? change.toFixed(2) : "0.00";
    } else {
      cashReturn.value = "";
    }
  });
}

function updateTable() {
  const tbody = document.getElementById("cart-body");
  tbody.innerHTML = '';

  if (cart.length === 0) {
    tbody.innerHTML = '<tr><td colspan="6" class="text-center">No Data Available</td></tr>';
    updateGrandAmount();
    return;
  }

  cart.forEach((product, index) => {
    const itemTotal = product.qty * product.price;
    const row = document.createElement("tr");
    row.innerHTML = `
      <td style="color:#84BC2F; font-weight:700;text-transform:uppercase;">
        ${product.name}<input type="hidden" value="${product.trade}" />
      </td>
      <td>
  <input type="number" min="0.01" step="0.01" value="${product.qty}" data-id="${product.id}" class="form-control form-control-sm qty-input">
</td>
<td>
  <input type="number" min="0" step="0.01" value="${product.price.toFixed(2)}" data-id="${product.id}" class="form-control form-control-sm price-input">
</td>

      <td style="font-weight:700;">${product.wh_percentage || 0}%</td>
      <td style="font-weight:700;">€${itemTotal.toFixed(2)}</td>
      <td>
        <button class="btn btn-sm remove-btn" data-index="${index}">
          <i class="text-danger fas fa-trash fa-1x"></i>
        </button>
      </td>
    `;
    tbody.appendChild(row);
  });

  document.querySelectorAll(".remove-btn").forEach(btn => {
    btn.addEventListener("click", e => {
      const index = parseInt(e.currentTarget.dataset.index);
      cart.splice(index, 1);
      updateTable();
    });
  });

document.querySelectorAll(".qty-input").forEach(input => {
  input.addEventListener("input", e => {
    // allow smooth typing, don’t update cart yet
  });

  input.addEventListener("blur", e => {
    const id = e.target.dataset.id;
    const qty = parseFloat(e.target.value);

    if (!isNaN(qty) && qty > 0) {
      const product = cart.find(p => p.id === id);
      if (product) product.qty = qty;
      updateTable();
    }
  });
});

document.querySelectorAll(".price-input").forEach(input => {
  input.addEventListener("input", e => {
    // allow smooth typing
  });

  input.addEventListener("blur", e => {
    const id = e.target.dataset.id;
    const price = parseFloat(e.target.value);

    if (!isNaN(price) && price >= 0) {
      const product = cart.find(p => p.id === id);
      if (product) product.price = price;
      updateTable();
    }
  });
});



  updateGrandAmount();
}

function selectCustomer(item) {
  const customerName = item.getAttribute('data-customer-name');
  const remainBalance = parseFloat(item.getAttribute('data-remain-balance')) || 0;

  document.getElementById('customer_name').value = customerName;
  document.getElementById('pre_amount').textContent = remainBalance.toFixed(2);
  updateGrandAmount();

  const suggestions = document.getElementById("customer_suggestions");
  suggestions.style.display = 'none';
  suggestions.classList.remove('show');
}

// DOM Ready
document.addEventListener('DOMContentLoaded', () => {
  updateGrandAmount();

  const customerSelect = document.querySelector('.form-select.form-select-sm.me-2');
  const productList = document.getElementById("product-list");

  if (customerSelect) {
    customerSelect.addEventListener('change', () => {
      const isWholesale = customerSelect.value.toLowerCase().includes('wholesale');
      document.querySelectorAll('.product-card').forEach(card => {
        const priceEl = card.querySelector('.product-price');
        const price = isWholesale ? card.dataset.wholesale : card.dataset.price;
        priceEl.textContent = '€' + parseFloat(price).toFixed(2);
      });
    });
  }

  if (productList) {
    productList.addEventListener('click', e => {
      const card = e.target.closest('.product-card');
      if (!card) return;
      const { id, name } = card.dataset;
      const price = parseFloat(card.dataset.price);
      const trade = parseFloat(card.dataset.trade);
      const wh_percentage = parseFloat(card.dataset.whpercentage);

      const existing = cart.find(p => p.id === id);
      if (existing) {
        existing.qty++;
      } else {
        cart.push({ id, name, price, trade, qty: 1, wh_percentage });
      }
      updateTable();
    });
  }

  const input = document.getElementById('productInput');
  const suggestions = document.getElementById('suggestions');
  let lastResults = [];

let scanLock = false; // prevent double add

function addProductRecordToCart(rec) {
  if (scanLock) {
    console.log("Blocked duplicate add for:", rec.product_id);
    return;
  }
  scanLock = true;
  setTimeout(() => (scanLock = false), 300); // unlock after 300ms

  const price = parseFloat(rec.retail_price || rec.price || rec.wholesale_price || 0) || 0;
  const trade = parseFloat(rec.trade_price || 0) || 0;
  const wh_percentage = parseFloat(rec.wh_percentage || 0) || 0;

  const recId = String(rec.product_id);
  const existing = cart.find(p => String(p.id) === recId);

  if (existing) {
    existing.qty++;
    console.log("Qty increased for:", recId);
  } else {
    cart.push({
      id: recId,
      name: rec.product_name,
      price,
      trade,
      qty: 1,
      wh_percentage
    });
    console.log("New product added:", recId);
  }

  updateTable();
}
  function clearScanUI() {
    input.value = '';
    suggestions.innerHTML = '';
    suggestions.style.display = 'none';
  }

function tryAutoAddFromResults(query, results) {
  const q = String(query || '').trim();
  console.log("tryAutoAddFromResults called with:", q, results);

  if (!q || !Array.isArray(results) || results.length === 0) return false;

  const exact = results.find(r =>
    String(r.product_id).toLowerCase() === q.toLowerCase() ||
    String(r.barcode || '').toLowerCase() === q.toLowerCase()
  );

  if (exact) {
    console.log("Exact match found:", exact.product_id);
    addProductRecordToCart(exact);
    clearScanUI();
    return true;
  }

  if (results.length === 1) {
    const only = results[0];
    if (
      String(only.product_id).toLowerCase() === q.toLowerCase() ||
      String(only.barcode || '').toLowerCase() === q.toLowerCase()
    ) {
      console.log("Single result auto-added:", only.product_id);
      addProductRecordToCart(only);
      clearScanUI();
      return true;
    }
  }

  console.log("No auto-add triggered");
  return false;
}

  function renderSuggestions(results) {
    suggestions.innerHTML = '';
    results.forEach(p => {
      const div = document.createElement('div');
      div.className = 'dropdown-item';
      div.textContent = `${p.product_id} - ${p.product_name}`;
      div.addEventListener('click', () => {
        addProductRecordToCart(p);
        clearScanUI();
      });
      suggestions.appendChild(div);
    });
    suggestions.style.display = results.length ? 'block' : 'none';
  }

  input?.addEventListener('input', () => {
    const query = input.value.trim();
    if (!query) {
      suggestions.innerHTML = '';
      suggestions.style.display = 'none';
      lastResults = [];
      return;
    }
    fetch(`?product_input=${encodeURIComponent(query)}`)
      .then(res => res.json())
      .then(products => {
        lastResults = Array.isArray(products) ? products : [];
        if (!tryAutoAddFromResults(query, lastResults)) {
          renderSuggestions(lastResults);
        }
      })
      .catch(() => {});
  });

  input?.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      const query = input.value.trim();
      if (tryAutoAddFromResults(query, lastResults)) return;
      if (query) {
        fetch(`?product_input=${encodeURIComponent(query)}`)
          .then(res => res.json())
          .then(products => {
            if (!tryAutoAddFromResults(query, products)) {
              renderSuggestions(products || []);
            }
          })
          .catch(() => {});
      }
    }
  });

  document.querySelectorAll("input[name='discountType']").forEach(radio => {
    radio.addEventListener("change", () => updateTable());
  });
});

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");
  }
}
</script>
<script>

document.querySelectorAll(".category-buttons .btn").forEach(btn => {
  btn.addEventListener("click", (event) => {
    event.preventDefault(); // ✅ Prevent default button action

    const label = btn.innerText.trim().toLowerCase();
    document.querySelectorAll(".product-card").forEach(card => {
      const cardCategory = card.dataset.category?.toLowerCase() || '';
      card.closest('.col').style.display =
        (label === "all categories" || label === cardCategory) ? '' : 'none';
    });
  });
});

function submitSale(event) {
  updateGrandAmount();

  document.getElementById('cartData').value = JSON.stringify(cart);

  const totalText = document.querySelector('h5.total-amount').innerText.replace('Total : €', '').trim();
  document.getElementById('discountAmount').value = parseFloat(totalText) || 0;

  const clickedButton = event.submitter?.name;

  // Optional: alert/debug
  // console.log("Button clicked:", clickedButton);

  if (clickedButton === 'refund_sale') {
    const refundId = document.getElementById('r_order_id').value.trim();
    if (!refundId) {
      alert("Please enter Refund Order ID before refund.");
      return false;
    }
  }

  return true;
}
</script>

  <script>
  document.addEventListener("DOMContentLoaded", function() {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.forEach(function (tooltipTriggerEl) {
      new bootstrap.Tooltip(tooltipTriggerEl);
    });
  });
</script>
<script>
  document.getElementById('fullscreenToggle').addEventListener('click', function () {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen().catch(err => {
        console.warn(`Error attempting fullscreen: ${err.message}`);
      });
    } else {
      document.exitFullscreen();
    }
  });
</script>


<script>
document.addEventListener("DOMContentLoaded", function () {
const input = document.getElementById("r_order_id");
const suggestions = document.getElementById("order_suggestions");

input.addEventListener("keydown", function (e) {
if (e.key === "Enter") {
e.preventDefault();
fetchSuggestions(input.value);
}
});


function fetchSuggestions(orderId) {
if (!orderId) return;


suggestions.style.display = "block";
suggestions.innerHTML = `
<a class="dropdown-item">Result for ${orderId}</a>
`;
}
});

</script>

<script>
  const dDate = document.getElementById("d_date");

  // When user picks date using a native datepicker
  dDate.addEventListener("focus", function() {
    this.type = "date"; // show date picker
  });

  dDate.addEventListener("blur", function() {
    if (this.value) {
      const date = new Date(this.value);
      const day = String(date.getDate()).padStart(2, '0');
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const year = date.getFullYear();
      this.type = "text"; // switch back to text field
      this.value = `${day}-${month}-${year}`; // format d-m-Y
    } else {
      this.type = "text"; 
    }
  });
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
