<?php
include 'includes/config.php';
session_start();

if (!$_SESSION['email']) {
  header('location:login.php');
}
?>
<?php
include 'includes/config.php';

if (!$_SESSION['email']) {
    header('location:login.php');
    exit();
}

if (isset($_POST['submit'])) {
    $bank_id  = $_POST['bank_id'] ?? '';
    $stock_category = $_POST['stock_category'] ?? '';

    if ($stock_category === 'Return' && empty($bank_id)) {
        die("<script>alert('Please select a bank before submitting.'); window.history.back();</script>");
    }

    $customer_ids = $_POST['customer_id'];
    $user_ids = $_POST['user_id'] ?? [];
    $product_codes = $_POST['product_code'];
    $product_ids = $_POST['product_id'];
    $product_names = $_POST['product_name'];
    $sale_taxs = $_POST['sale_tax'];
    $categorys = $_POST['category'];
    $date_sales = $_POST['date_sale'];
    $units = $_POST['unit'];
    $prices = $_POST['price'];
    $sale_qtys = $_POST['sale_qty'];
    $total_amounts = $_POST['total_amount'];
    $net_cashs = $_POST['net_cash'];
    $discounts = $_POST['discount'];
    $order_taxs = $_POST['order_tax'];

    try {
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

       $table_for_invoice = ($stock_category === 'Defective') ? 'defective_sale' : 'return_sale';
$stmt_max_invoice = $conn->prepare("SELECT MAX(invoice) AS max_invoice FROM $table_for_invoice;");
$stmt_max_invoice->execute();
$row_max_invoice = $stmt_max_invoice->fetch(PDO::FETCH_ASSOC);
$max_invoice = $row_max_invoice['max_invoice'];

$next_invoice = empty($max_invoice) ? "0000000001" : str_pad($max_invoice + 1, 10, "0", STR_PAD_LEFT);


        // Choose table based on category
        $target_table = ($stock_category === 'Defective') ? 'defective_sale' : 'return_sale';

        $stmt_insert = $conn->prepare("INSERT INTO $target_table (
            invoice, customer_id, user_id, product_code, product_id, product_name, sale_tax, category,
            date_sale, unit, price, sale_qty, total_amount, net_cash, discount, order_tax
        ) VALUES (
            :invoice, :customer_id, :user_id, :product_code, :product_id, :product_name, :sale_tax, :category,
            :date_sale, :unit, :price, :sale_qty, :total_amount, :net_cash, :discount, :order_tax
        )");

        // Prepare bank debit only for 'Return'
        if ($stock_category === 'Return') {
            $stmt_bank_debit = $conn->prepare("INSERT INTO bank_debit_amount (
                bank_id, user_id, invoice, amount, date, status
            ) VALUES (
                :bank_id, :user_id, :invoice, :amount, :date, :status
            )");
        }

        $num_rows = count($product_codes);
        $total_sum = 0;

        for ($i = 0; $i < $num_rows; $i++) {
            $invoice = $next_invoice;
            $customer_id = $customer_ids[0];
             $user_id = $user_ids[0] ?? 0; 
            $date_sale = $date_sales[0];
            $product_code = $product_codes[$i];
            $product_id = $product_ids[$i];
            $product_name = $product_names[$i];
            $sale_tax = $sale_taxs[$i];
            $category = $categorys[$i];
            $unit = $units[$i];
            $price = $prices[$i];
            $sale_qty = $sale_qtys[$i];
            $total_amount = $total_amounts[$i];
            $total_sum += $total_amount;

            $net_cash = ($i == 0) ? $net_cashs[0] : 0;
            $discount = ($i == 0) ? $discounts[0] : 0;
            $order_tax = ($i == 0) ? $order_taxs[0] : 0;

            $stmt_insert->bindParam(':invoice', $invoice);
            $stmt_insert->bindParam(':customer_id', $customer_id);
           $stmt_insert->bindParam(':user_id', $user_id);
            $stmt_insert->bindParam(':product_code', $product_code);
            $stmt_insert->bindParam(':product_id', $product_id);
            $stmt_insert->bindParam(':product_name', $product_name);
            $stmt_insert->bindParam(':sale_tax', $sale_tax);
            $stmt_insert->bindParam(':category', $category);
            $stmt_insert->bindParam(':date_sale', $date_sale);
            $stmt_insert->bindParam(':unit', $unit);
            $stmt_insert->bindParam(':price', $price);
            $stmt_insert->bindParam(':sale_qty', $sale_qty);
            $stmt_insert->bindParam(':total_amount', $total_amount);
            $stmt_insert->bindParam(':net_cash', $net_cash);
            $stmt_insert->bindParam(':discount', $discount);
            $stmt_insert->bindParam(':order_tax', $order_tax);

            $stmt_insert->execute();
        }

        // Insert bank debit only for 'Return'
        if ($stock_category === 'Return' && $total_sum > 0) {
            $user_id = $customer_ids[0];
            $status = 'customer';

            $stmt_bank_debit->bindParam(':bank_id', $bank_id);
            $stmt_bank_debit->bindParam(':user_id', $user_id);
            $stmt_bank_debit->bindParam(':invoice', $invoice);
            $stmt_bank_debit->bindParam(':amount', $total_sum);
            $stmt_bank_debit->bindParam(':date', $date_sale);
            $stmt_bank_debit->bindParam(':status', $status);

            $stmt_bank_debit->execute();
        }

if ($stock_category === 'Return') {
    echo "<script>window.location.href='print/return_customer_bill.php?invoice_no={$invoice}';</script>";
} else {
    echo "<script>window.location.href='print/replace_customer_bill.php?invoice_no={$invoice}';</script>";
}
        exit();

    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }

    $conn = null;
}
?>


<!--get customer name or id-->
<?php
function get_brand()
{
  require("include/config.php");
  $output = '';
  $sql = "SELECT * FROM contacts ORDER BY id DESC";
  $stmt = $conn->prepare($sql);
  $stmt->execute();
  $rows = $stmt->fetchAll();
  if (count($rows) > 0) {
    foreach ($rows as $row) {
      $output .= '<option value="' . $row["id"] . '">' . $row["name"] . '</option>';
    }
  }
  return $output;
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Add To Cart</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
  <script type="module" src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js"></script>
  <script nomodule src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js"></script>
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <!-- Typography CSS -->
  <link rel="stylesheet" href="css/typography.css">
  <!-- Style CSS -->
  <link rel="stylesheet" href="css/style.css">
  <!-- Responsive CSS -->
  <link rel="stylesheet" href="css/responsive.css">

  <style>
    main {
      height: 458px;
      overflow: auto;
      /* background-color: white; */
    }

    th {
      background-color: rgb(210 214 223);
    }

    .mein {
      height: 283px;
      overflow-y: auto;
      border-bottom: 1px solid green;
      margin-left: -12px;
    }

    .mein table {
      width: 100%;
      margin-left: -0px;
    }

    .mein input[type="number"] {
      width: 100px;
    }

    table {
      margin-left: -12px;
    }

    .select2-container--default .select2-selection--single {
      border: none;
      /* Remove border */
      background-color: transparent;
      /* Make background transparent */
      box-shadow: none;
      /* Remove any shadow */
    }

    .select2-container--default .select2-selection--single .select2-selection__rendered {
      color: #000;
      /* Text color */
    }

    .select2-container--default .select2-selection--single .select2-selection__arrow {
      display: none;
      /* Optionally hide the arrow */
    }

    /* Optional: Add focus styles */
    .select2-container--default .select2-selection--single:focus {
      outline: none;
      /* Remove focus outline */
    }

    #productCardsContainer {
      max-height: 440px;
      /* Set your desired height */
      overflow-y: auto;
    }

    .navbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 20px;
      background-color: #f8f8f8;
      border-bottom: 1px solid #ccc;
    }

    .location {
      font-size: 18px;
      font-weight: bold;
    }

    .datetime {
      font-size: 14px;
      color: #555;
    }


    .back-button button {
      background-color: #007BFF;
      /* Primary color */
      color: white;
      border: none;
      padding: 10px 15px;
      border-radius: 5px;
      font-size: 14px;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }

    .back-button button:hover {
      background-color: #0056b3;
      /* Darker shade on hover */
    }

    .back-button button:focus {
      outline: none;
      /* Remove outline on focus */
    }

    .modal {
      display: none;
      /* Hidden by default */
      position: fixed;
      /* Stay in place */
      z-index: 1;
      /* Sit on top */
      left: 0;
      top: 0;
      width: 100%;
      /* Full width */
      height: 100%;
      /* Full height */
      overflow: auto;
      /* Enable scroll if needed */
      background-color: rgb(0, 0, 0);
      /* Fallback color */
      background-color: rgba(0, 0, 0, 0.4);
      /* Black w/ opacity */
    }

    .modal-content {
      background-color: #fefefe;
      margin: 15% auto;
      /* 15% from the top and centered */
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
      /* Could be more or less, depending on screen size */
    }

    .close {
      color: #aaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
    }

    .close:hover,
    .close:focus {
      color: black;
      text-decoration: none;
      cursor: pointer;
    }

    .form-group {
      margin-bottom: 15px;
    }

    .form-control {
      width: 100%;
      padding: 8px;
      box-sizing: border-box;
    }

    .btn {
      background-color: rgb(243, 156, 17);
      color: white;
      border: none;
      padding: 10px 15px;
      cursor: pointer;
    }

    .btn:hover {
      background-color: darkorange;
    }
  </style>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      document.getElementById('openModalButton').addEventListener('click', function() {
        document.getElementById('addUnitModal').style.display = 'block';
      });

      document.querySelectorAll('#closeModalButton, #closeModalButtonFooter').forEach(function(button) {
        button.addEventListener('click', function() {
          document.getElementById('addUnitModal').style.display = 'none';
        });
      });

      // Close modal if user clicks outside of the modal
      window.addEventListener('click', function(event) {
        const modal = document.getElementById('addUnitModal');
        if (event.target === modal) {
          modal.style.display = 'none';
        }
      });
    });
  </script>
</head>

<body>
  <!-- Modal -->
  <!-- Modal -->
  <div class="modal" id="addUnitModal">
    <div class="modal-content">
      <div class="modal-header">
        <h4>Add Customer</h4>
        <span class="close" id="closeModalButton">&times;</span>
      </div>
      <form method="POST" action="submit_contact_customer_pos.php">
        <div class="modal-body">
          <div class="row">
            <div class="form-group col">
              <label for="name">Name:*</label>
              <input type="text" class="form-control" name="name" placeholder="Enter Name" required>
            </div>
            <div class="form-group col">
              <label for="contact_id">Contact ID:</label>
              <input type="number" class="form-control" name="contact_id" placeholder="Contact ID">
            </div>
            <div class="form-group col">
              <label for="tax_number">Tax number:</label>
              <input type="number" class="form-control" name="tax_number" placeholder="Tax number">
            </div>
          </div>
          <div class="row">
            <div class="form-group col">
              <label for="opening_balance">Opening Balance:</label>
              <input type="number" class="form-control" name="opening_balance" placeholder="0">
            </div>
            <div class="form-group col">
              <label for="pay_term_type">Pay term:</label>
              <input type="number" class="form-control" name="pay_term_type" placeholder="Pay term">
            </div>
            <div class="form-group col">
              <label for="credit_limit">Credit Limit:</label>
              <input type="number" class="form-control" name="credit_limit" placeholder="Credit Limit">
            </div>
          </div>
          <div class="row">
            <div class="form-group col">
              <label for="email">Email:</label>
              <input type="email" class="form-control" name="email" placeholder="Email">
            </div>
            <div class="form-group col">
              <label for="mobile">Mobile:*</label>
              <input type="text" class="form-control" name="mobile" placeholder="Mobile Number:*" required>
            </div>
            <div class="form-group col">
              <label for="alternate_number">Alternate contact number:</label>
              <input type="text" class="form-control" name="alternate_number" placeholder="Alternate contact number">
            </div>
          </div>
          <div class="row">
            <div class="form-group col">
              <label for="landline">Landline:</label>
              <input type="text" class="form-control" name="landline" placeholder="Landline">
            </div>
            <div class="form-group col">
              <label for="city">City:</label>
              <input type="text" class="form-control" name="city" placeholder="City">
            </div>
            <div class="form-group col">
              <label for="state">State:</label>
              <input type="text" class="form-control" name="state" placeholder="State">
            </div>
          </div>
          <div class="row">
            <div class="form-group col">
              <label for="country">Country:</label>
              <input type="text" class="form-control" name="country" placeholder="Country">
            </div>
            <div class="form-group col">
              <label for="landmark">Landmark:</label>
              <input type="text" class="form-control" name="landmark" placeholder="Landmark">
            </div>
          </div>
          <div class="row">
            <div class="form-group col">
              <label for="" class="label-control">Custom Field 1:</label>
              <input type="text" class="form-control" name="custom_field1" placeholder="Custom Field 1">
            </div>
            <div class="form-group col">
              <label for="" class="label-control">Custom Field 2:</label>
              <input type="text" class="form-control" name="custom_field2" placeholder="Custom Field 2">
            </div>
            <div class="form-group col">
              <label for="" class="label-control">Custom Field 3:</label>
              <input type="text" class="form-control" name="custom_field3" placeholder="Custom Field 3">
            </div>
          </div>
          <div class="row">
            <div class="form-group col">
              <label for="" class="label-control">Custom Field 4:</label>
              <input type="text" class="form-control" name="custom_field4" placeholder="Custom Field 4">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn" name="submit_popup">Submit</button>
          <button type="button" class="btn" id="closeModalButtonFooter">Close</button>
        </div>
      </form>
    </div>
  </div>

  <?php
  // Fetch categories with business_id = 3


  // Fetch brands for filters
  try {
    $brandQuery = 'SELECT DISTINCT name FROM brands ORDER BY name';
    $brandStmt = $conn->query($brandQuery);
    $brands = $brandStmt->fetchAll(PDO::FETCH_ASSOC);
  } catch (PDOException $e) {
    echo "Error fetching brands: " . htmlspecialchars($e->getMessage());
    $brands = [];
  }

  // Fetch customers for filters
  try {
    $customerQuery = 'SELECT id, name FROM contacts ORDER BY id';
    $customerStmt = $conn->query($customerQuery);
    $customers = $customerStmt->fetchAll(PDO::FETCH_ASSOC);
  } catch (PDOException $e) {
    echo "Error fetching customers: " . htmlspecialchars($e->getMessage());
    $customers = [];
  }


  ?>
  <nav class="navbar">
    <div class="location"></div>
    <div class="datetime">
      <span id="dateTime"></span>
    </div>
    <div class="back-button">
      <button onclick="location.href='list_return_sale.php'">&lt; Back</button>
    </div>

  </nav>

  <script>
    const updateDateTime = () => {
      const now = new Date();
      const options = {
        weekday: 'long',
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      };
      document.getElementById('dateTime').textContent = now.toLocaleDateString(undefined, options);
    };
    updateDateTime();
  </script>
  <div class="container-fluid">
    <div class="row">
      <div class="col-lg-7 col-md-7">
        <header
          class="p-1"
          style="
              background-color: rgb(244 244 244);
              box-shadow: 5px 0px 20px rgba(211, 211, 211, 0.445);
            ">
          <div class="row">
            <div class="col-lg-6 col-md-6 col-sm-6 col-6">
              <span style="margin-top: 5px"><ion-icon
                  name="search-outline"
                  style="
                      position: absolute;
                      margin-top: 1%;
                      font-size: 20px;
                      margin-left: 10px;
                    "></ion-icon></span>
              <p style="margin-left: 30px; margin-top: 12px" class="search-bar">
                <input type="text" id="product-search" class="form-control" style="border:none; background:transparent;" placeholder="Search/Scan Bar">
              </p>
            </div>
            <div class="col-lg-6 col-md-6 col-sm-6 col-6"><!-- Include jQuery (required for Select2) -->
              <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
              <!-- Include Select2 CSS and JS -->
              <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
              <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>

              <?php
              // Fetch categories with business_id = 3
              try {
                $categoryQuery = 'SELECT id, name FROM categories WHERE business_id = 3 ORDER BY name';
                $categoryStmt = $conn->query($categoryQuery);
                $categories = $categoryStmt->fetchAll(PDO::FETCH_ASSOC);
              } catch (PDOException $e) {
                echo "Error fetching categories: " . htmlspecialchars($e->getMessage());
                $categories = [];
              }

              // Create options string
              $options = '<option value="">View All</option>'; // Default option
              foreach ($categories as $category) {
                $options .= '<option value="' . htmlspecialchars($category['id']) . '">';
                $options .= htmlspecialchars($category['name']);
                $options .= '</option>';
              }
              ?>
              <select
                name="category"
                class="form-control" id="category-filter"
                style="
        width: 70%;
        margin-top: 5px;
        border-radius: 50px;
    ">
                <?php echo $options; ?>
              </select>

              <!-- Initialize Select2 -->
              <script>
                $(document).ready(function() {
                  $('.select2').select2({
                    placeholder: 'Select Customer',
                    allowClear: true
                  });
                });
              </script>

            </div>
          </div>
        </header>

        <main>

          <div class="row" style="margin: 0px; padding: 0px" id="productCardsContainer">
            <?php
            $limit = 30;
            $offset = 0;

            $sql = "SELECT 
            pl.product_id,
            pl.quantity,
            pl.sell_price,
            p.name AS product_name,
            p.image AS product_image,
            c.id AS category_id,
            c.name AS category_name,
            b.name AS brand_name,
            p.sku
        FROM 
            purchase_lines AS pl
        JOIN 
            products AS p 
        ON 
            pl.product_id = p.id
        LEFT JOIN 
            categories AS c 
        ON 
            p.category_id = c.id
        LEFT JOIN 
            brands AS b 
        ON 
            p.brand_id = b.id
            Group BY pl.product_id
        ORDER BY 
            pl.product_id DESC
        LIMIT :limit OFFSET :offset
        ";

            $stmt = $conn->prepare($sql);
            $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
            $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
            $stmt->execute();
            $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

            foreach ($products as $rows) {
              $productImage = !empty($rows["product_image"]) ? htmlspecialchars($rows["product_image"]) : 'dumy_image.png';
            ?>
              <div class="col-lg-2 col-md-2 col-sm-2 col-2 mt-2 product-card" style="background-color: white; border: 1px solid green; display: none;"
                data-product-name="<?php echo htmlspecialchars($rows["product_name"]); ?>"
                data-product-category="<?php echo htmlspecialchars($rows["category_id"]); ?>"
                data-product-brand="<?php echo htmlspecialchars($rows["brand_name"]); ?>"
                data-product-code="<?php echo htmlspecialchars($rows["product_id"]); ?>"> 
                <div style="margin: 10px 0;">
                  <img src="img/<?php echo $productImage; ?>" class="card-img-top img-fluid" alt="<?php echo htmlspecialchars($rows["product_name"]); ?>" style="height: 100px; width: 150px; object-fit: cover;" />
                </div>
                <h6 class="text-center"><?php echo htmlspecialchars($rows["product_name"]); ?><br> (<?php echo htmlspecialchars($rows["sku"]); ?>)</h6>
                <button class="butn add-to-cart" data-product-code="<?php echo htmlspecialchars($rows["product_id"]); ?>"
                  style="background-color: black; height: 55px; width: 125px; margin-top: 23%; margin-left: -14px; color: white;">
                  Add To Cart
                </button>
              </div>


            <?php } ?>
          </div>


        </main>

      </div>

      <div class="col-lg-5 col-md-5 col-sm-5 col-5" style="padding: 0px">
        <form action="" method="POST" <?php echo $_SERVER['PHP_SELF']; ?>>

          <div class="row">
            <div
              class="img-hd col-lg-10 col-md-8 col-sm-8 col-8"
              style="background-color: rgb(253 221 170)">
              <span style="margin-top: 5px"><ion-icon
                  name="person-circle-outline"
                  style="position: absolute; margin-top: 19px; font-size: 25px"></ion-icon></span>
              <p style="margin-left: 26px; margin-top: 20px">
            <select id="brand" name="customer_id[]" class="form-control select2" required>
    <option value="">Select Customer</option>
    <?php foreach ($customers as $customer): ?>
        <option value="<?php echo htmlspecialchars($customer['id']); ?>"
            <?php echo (strcasecmp($customer['name'], "walking customer") === 0) ? "selected" : ""; ?>>
            <?php echo htmlspecialchars($customer['name']); ?>
        </option>
    <?php endforeach; ?>
</select>
              </p>
                  <input type="hidden" name="user_id[]" value="<?php echo $_SESSION['id']; ?>">

            </div>
            <input type="date" style="display: none;" class="form-control" name="date_sale[]" id="date">

            <script>
              // Get today's date in YYYY-MM-DD format
              const today = new Date().toISOString().split('T')[0];

              // Set the value of the date input to today's date
              document.getElementById('date').value = today;
            </script>

            <!-- <div
              class="butn-hd col-lg-2 col-md-2 col-sm-2 col-2"
              style="background-color: green">
              <h6
                class="text-center"
                style="color: white; font-size: 13px; margin-top: 5px">
                DUE
              </h6>
              <button
                class="butn"
                style="
                  background-color: rgb(215 81 47);
                  border-radius: 10px;
                  width: 70px;
                  border-color: lightpink;
                ">
                0.00
              </button>
            </div> -->
            <div
              class="col-lg-2 col-md-2 col-sm-2 col-2"
              style="background-color: rgb(243 156 17)">
              <!-- <button class="butn" id="openModalButton" style="background-color: rgb(243 156 17); border-color: transparent; width: 70px; height: 60px;">

                <ion-icon
                  name="add-outline"
                  style="font-size: 40px; color: white"></ion-icon>
              </button> -->
            </div>
          </div>
          <div class="mein">
            <table class="table" id="tb">
              <thead
                class="table-secondary"
                style="font-family: 'Arial', 'sans-serif'">
                <tr
                  style="
                    background-color: rgb(210 214 223);
                    font-family: 'Arial', 'sans-serif';">
                  <th>Product</th>
                  <th>Quantity</th>
                  <th>Price</th>
                  <th>Subtotal</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                <!-- Rows will be dynamically added here -->

              </tbody>
            </table>
          </div>
          <div class="tbl">
            <table class="table">
              <thead class="table-secondary">
                <tr style="background-color: rgb(210 214 223)">
                  <th>Total Items</th>
                  <th><input id="total-qty" type="text" style="width: 8em; height:2.4em; border:none; background:transparent;" placeholder="0.00" readonly></th>
                  <th>Total</th>
                  <th><input type="text" id="main_total" class="main_total" style="width: 8em; height:2.4em; border:none; background:transparent;  border-radius:10px;" name="" placeholder="0.00">
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr style="display:none;">
                  <td style="text-align: right;">DISCOUNT</td>
                  <td> <input type="text" id="discount" name="discount[]" style="width: 8em; height:2.4em;  background-color: rgb(66 66 66);
                        border-color: transparent;
                        width: 90px;
                        border-radius: 10px;
                        color: white; border-radius:10px;" class="net_sale" placeholder="0.00">
                  </td>
                  <td style="text-align: right; display:none;">Order Tax(%)</td>
                  <td>
                    <input type="text" id="order_tax" name="order_tax[]" style="width: 8em; height:2.4em;  background-color: rgb(66 66 66);
                        border-color: transparent; display:none;
                        width: 90px;
                        border-radius: 10px;
                        color: white; border-radius:10px;" class="net_sale" placeholder="0.00">

                  </td>
                  <!-- <input type="hidden" id="net_cash" name="net_cash[]" style="width: 8em; height:2.4em; border:2px solid #000;  border-radius:10px;" class="net_sale" placeholder="Net Sale"> -->

                </tr>

                <thead class="table-secondary">
                  <tr>
                    <td>
                      <?php

                      // Fetch data from the 'banks' table
                      $stmt = $conn->prepare("SELECT id, bank_name FROM banks");
                      $stmt->execute();
                      $banks = $stmt->fetchAll(PDO::FETCH_ASSOC);
                      ?>

                      <select class="form-control" name="bank_id" id="bankSelect" required>
                        <?php foreach ($banks as $bank): ?>
                          <option value="<?= htmlspecialchars($bank['id']) ?>">
                            <?= htmlspecialchars($bank['bank_name']) ?>
                          </option>
                        <?php endforeach; ?>
                      </select>
                    </td>
                     <td>
                     

                      <select class="form-control" name="stock_category" required>
                        <option value="Return">Return</option>
                        <!-- <option value="Defective">Damage</option> -->
                      </select>
                    </td>
                  </tr>
                  
                  <tr style="background-color: rgb(210 214 223); display:none;">
                    <th>Cash</th>
                    <th> <input type="" id="net_cash" name="net_cash[]" style="width: 8em; height:2.4em; border:2px solid #000;  border-radius:10px;" class="net_sale" placeholder="Net Cash">

                    <th>Total PAYABLE</th>
                    <th><input type="text" id="remaining_amount" style="border: none; background:transparent; width:57px;" placeholder="0.00" class="remaining_amount"> </th>
                  </tr>
                </thead>
              </tbody>
            </table>
            <div class="row text-center" style="margin-top: -16px; margin-left: -6px;">
              <div class="row">
                <!-- <button
                  type="button"
                  class="btn btn-warning btn-sm text-center"
                  style="font-size: 15px; all: unset; background-color: #ffad46;padding: 5px 10px;color: white;">
                  <strong>Quotation</strong>
                </button>
                <button
                  class="text-center"
                  style="color: white; font-size: 15px; all: unset;background-color: #f5365c;padding: 5px 10px;color: white;">
                  <strong>Suspend</strong>
                </button> -->
                <button
                  class="text-center" id="holdButton" name="submit"
                  style="color: white; font-size: 15px; all: unset;background-color: #605ca8;padding: 5px 50px;color: white;">
                  <strong>Add Return</strong>
                </button>
                <!-- <button
                  class="text-center"
                  style="color: white; font-size: 12px; all: unset;background-color: #001f3f;padding: 5px 10px;color: white;">
                  <strong>Multiple Sale</strong>
                </button> -->
                <!-- <button
                  class="text-center"
                  id="submitBtn"
                  name="submit"
                  style="color: white; font-size: 15px; all: unset; background-color: #2dce89; padding: 5px 10px; color: white;"
                  disabled>
                  <strong>Cash</strong>
                </button> -->

                <script>
                  // JavaScript to enable/disable button based on dropdown selection
                  const selectElement = document.getElementById('bankSelect');
                  const submitButton = document.getElementById('submitBtn');

                  // Event listener for dropdown change
                  selectElement.addEventListener('change', function() {
                    // Enable the button if a valid option is selected
                    if (selectElement.value) {
                      submitButton.removeAttribute('disabled');
                    } else {
                      submitButton.setAttribute('disabled', true);
                    }
                  });
                </script>
                <!-- <button
                  class="text-center"
                  style="color: white; font-size: 15px; all: unset;background-color: #ffad46;padding: 5px 10px;color: white;">
                  <strong>Total: 0.00</strong>
                </button> -->
              </div>
            </div>
          </div>
      </div>
    </div>
  </div>
  </form>

  <!-- <script>
    document.getElementById('submitBtn').addEventListener('click', function() {
      var total = parseFloat(document.getElementById('main_total').value);
      var discount = parseFloat(document.getElementById('discount').value) || 0;
      var orderTax = parseFloat(document.getElementById('order_tax').value) || 0;
      var netCash = (total + orderTax) - discount;

      document.getElementById('net_cash').value = netCash.toFixed(2); /
    });

    document.getElementById('holdButton').addEventListener('click', function() {
      document.getElementById('net_cash').value = "0"; 
    });
  </script> -->

  <audio id="beep-add" src="beep/scanner-beeps.wav" preload="auto"></audio>
  <audio id="beep-remove" src="beep/beep-remove.mp3" preload="auto"></audio>
  <audio id="beep-error" src="beep/beep-error.mp3" preload="auto"></audio>
  <script>
    $(document).ready(function() {
      let loading = false;
      let offset = 0;
      const limit = 20;

      function loadProducts() {
        if (loading) return;
        loading = true;

        $.ajax({
          url: 'load_products.php',
          type: 'GET',
          data: {
            offset: offset,
            limit: limit,
            category: $('#category-filter').val(),
            brand: $('#brand-filter').val(),
            search: $('#product-search').val()
          },
          dataType: 'html',
          success: function(response) {
            $('#productCardsContainer').append(response);
            offset += limit;
            loading = false;

            attachTooltip();
          },
          error: function(jqXHR, textStatus, errorThrown) {
            console.log('AJAX Error:', textStatus, errorThrown);
            loading = false;
          }
        });
      }

      function attachTooltip() {
        $('.product-card').hover(function() {
          const productName = $(this).data('product-name');

          $.ajax({
            url: 'getProductrecord_stock.php',
            type: 'GET',
            data: {
              product_name: productName
            }, 
            dataType: 'json',
            success: function(productData) {
              if (productData && !productData.error) {
                const tooltipText = productData.tooltip;
                $(this).attr('title', tooltipText);
              } else {
                $(this).attr('title', 'Stock data not available');
              }
            }.bind(this),
            error: function(jqXHR, textStatus, errorThrown) {
              console.log('AJAX Error:', textStatus, errorThrown);
              $(this).attr('title', 'Error fetching stock data');
            }.bind(this)
          });
        });
      }

      loadProducts();
      attachTooltip(); 

      function debounce(func, wait) {
        let timeout;
        return function() {
          clearTimeout(timeout);
          timeout = setTimeout(func, wait);
        };
      }

      // Load more products on scroll
      $('#productCardsContainer').on('scroll', debounce(function() {
        if ($('#productCardsContainer').scrollTop() + $('#productCardsContainer').height() >= $(document).height() - 100) {
          loadProducts();
        }
      }, 200));

      $('#product-search').on('input', debounce(function() {
        $('#productCardsContainer').empty();
        offset = 0; 
        loadProducts(); 
      }, 300)); 

      $('#category-filter, #brand-filter').on('change', function() {
        $('#productCardsContainer').empty();
        offset = 0; 
        loadProducts(); 
      });

      $(document).on('click', '.add-to-cart', function() {
        var productId = $(this).data('product-code');
        console.log('Add to Cart Button Clicked');
        console.log('Product ID:', productId);

        var beepAdd = document.getElementById('beep-add');
        beepAdd.play();

        $.ajax({
  url: 'getProductrecord.php',
  type: 'GET',
  data: {
    product_id: productId
  },
  dataType: 'json',
  success: function(productData) {
    console.log('AJAX Success:', productData);
    if (productData && !productData.error) {
      var productCode = productData.product_id;
      var availableStock = parseInt(productData.current_stock_qty, 10); 

      if (availableStock <= 0) {
        var beepError = document.getElementById('beep-error');
        beepError.play();
        alert('Stock is unavailable! ❌');
        return;
      }

      var existingRow = $('#tb').find(`.productCode[value="${productCode}"]`).closest('tr');

      if (existingRow.length > 0) {
        var qtyField = existingRow.find('.sale_qty');
        var currentQty = parseInt(qtyField.val(), 10) || 0;

        if (currentQty + 1 > availableStock) {
          var beepError = document.getElementById('beep-error');
          beepError.play();
          alert('Quantity exceeds available stock! ❌');
          return;
        }

        qtyField.val(currentQty + 1);
        calculateRowTotal(existingRow);
      } else {
        var newRow = `
                    <tr style="background-color:#daede5;">
                        <td><input type="text" class="form-control productName" name="product_name[]" value="${productData.product_name}" readonly></td>
                        <td style="display:none;"><input type="text" class="form-control availableStock" value="${productData.current_stock_qty}" readonly></td>
                        <td><input type="text" name="sale_qty[]" class="form-control sale_qty" value="1" required></td>
                        <td><input type="text" class="form-control saleprice" name="price[]" value="${productData.sale_price}" required></td>
                        <td><input type="text" name="total_amount[]" class="form-control total_amount" placeholder="Total" readonly></td>
                        <td style="display:none;"><input type="text" class="form-control productCategory" name="category[]" value="${productData.category_id}" readonly></td>
                        <td style="display:none;"><input type="text" class="form-control productUnit" name="unit[]" value="${productData.actual_name}" readonly></td>
                        <td style="display:none;"><input type="text" class="form-control productCode" name="product_code[]" value="${productData.product_id}" readonly></td>
                        <td style="display:none;"><input type="text" class="form-control productId" name="product_id[]" value="${productData.product_id}" readonly></td>
                        <td style="display:none;"><input type="text" class="form-control saleTax" name="sale_tax[]" value="${productData.sale_tax}" readonly></td>
                        <td><a href='javascript:void(0);' class='remove'><ion-icon name="trash-outline"></ion-icon></a></td>
                    </tr>`;
        $('#tb').append(newRow);
        var addedRow = $('#tb').find(`.productCode[value="${productCode}"]`).closest('tr');
        calculateRowTotal(addedRow);
      }

      calculateTotals();
    } else {
      var beepError = document.getElementById('beep-error');
      beepError.play();
      alert('Product not found or error occurred.');
    }
  },
  error: function(jqXHR, textStatus, errorThrown) {
    console.log('AJAX Error:', textStatus, errorThrown);
    console.log('Response Text:', jqXHR.responseText);
  }
});
});

      $(document).on('keyup', '.sale_qty', function() {
        var row = $(this).closest('tr');
        var qtyField = $(this);
        var availableStock = parseInt(row.find('.availableStock').val(), 10);
        var saleQty = parseInt(qtyField.val(), 10) || 0;

        if (saleQty > availableStock) {
          var beepError = document.getElementById('beep-error');
          beepError.play();
          alert('Quantity exceeds available stock! ❌');
          qtyField.val(availableStock);
        }

        calculateRowTotal(row);
        calculateTotals();
      });

      $(document).on('click', '.remove', function() {
        var row = $(this).closest('tr');
        row.remove();
        calculateTotals();
        var beepRemove = document.getElementById('beep-remove');
        beepRemove.play();
      });

      $(document).on('keyup', '.saleprice, #net_cash, #discount', function() {
        var row = $(this).closest('tr');
        calculateRowTotal(row);
      });

      $(document).on('click', '.remove', function() {
        $(this).closest('tr').remove();
        calculateTotals();

        var beepRemove = document.getElementById('beep-remove');
        beepRemove.play();
      });

      $('.cancel-button').on('click', function() {
        $('#tb').empty();
        calculateTotals(); 

        // Play remove sound
        var beepRemove = document.getElementById('beep-remove');
        beepRemove.play();
      });

      $('input[name="order_tax[]"]').on('input', function() {
        calculateTotals();
      });

      function calculateRowTotal(row) {
        var saleQty = parseFloat(row.find('.sale_qty').val()) || 0;
        var price = parseFloat(row.find('.saleprice').val()) || 0;
        var total = saleQty * price;
        row.find('.total_amount').val(total.toFixed(2)); 
        calculateTotals();
      }

      function calculateTotals() {
        var mainTotal = 0;
        var totalQty = 0; 
        $('.total_amount').each(function() {
          var row = $(this).closest('tr');
          var saleQty = parseFloat(row.find('.sale_qty').val()) || 0;
          var price = parseFloat(row.find('.saleprice').val()) || 0;
          var total = saleQty * price;
          $(this).val(total.toFixed(2));
          mainTotal += total;
          totalQty += saleQty; 
        });

        $('.main_total').val(mainTotal.toFixed(2));

        $('#total-qty').val(totalQty);

        var discount = parseFloat($('#discount').val()) || 0;
        var orderTax = parseFloat($('input[name="order_tax[]"]').val()) || 0;
        mainTotal -= discount;
        mainTotal += orderTax; // Add order tax

        var paidAmount = parseFloat($('#net_cash').val()) || 0;
        var remainingAmount = mainTotal - paidAmount;
        $('.remaining_amount').val(remainingAmount.toFixed(2));
      }
    });
  </script>

  <script
    src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
    crossorigin="anonymous"></script>
</body>

</html>