<?php
$page_title = 'Form Bazzar';
require_once('includes/load.php');
page_require_level(1);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Get the data from the form
  $sales_man = $_POST['sales_man']; // Salesman
  $customer_name = $_POST['customer_name']; // Customer name
  $address = $_POST['address']; // Address
  $phone = $_POST['phone']; // Phone
  $kurir = $_POST['kurir']; // Courier
  $bazzar_sn = generateCode("BZ"); // Generate Bazaar order number
  $bazzar_sj = generateCode("SJ"); // Generate Bazaar order number

  $batas_kirim = $_POST['batas_kirim']; // Delivery Deadline
  $warehouse_id = $_POST['warehouse_id']; // Warehouse ID
  $keterangan = $_POST['keterangan']; // Description field
  $status = $_POST['status']; // Status field (e.g., Pending, Completed, Cancelled)

  // Insert into bazzar table
  $sql_order = "INSERT INTO bazzar (bazzar_sn, bazzar_sj, sales_man, customer_name, address, phone, kurir, batas_kirim, warehouse_id, keterangan, status) VALUES ('$bazzar_sn', '$bazzar_sj', '$sales_man', '$customer_name', '$address', '$phone', '$kurir', '$batas_kirim', '$warehouse_id', '$keterangan', '$status')";

  if ($db->query($sql_order) === TRUE) {
    // Get the inserted bazzar_id
    $bazzar_id = $db->insert_id();

    // Insert data into bazzar_detail table
    $product_names = $_POST['product_name']; // Array of product names
    $quantities = $_POST['quantity']; // Array of quantities
    $prices = $_POST['price']; // Array of prices

    for ($i = 0; $i < count($product_names); $i++) {
      $product_name = $product_names[$i];
      $quantity = (int)$quantities[$i];
      $price = (float)$prices[$i];
      $subtotal = $quantity * $price;

      $sql_detail = "INSERT INTO bazzar_detail (bazzar_id, product_name, quantity, price, subtotal) 
                           VALUES ('$bazzar_id', '$product_name', '$quantity', '$price', '$subtotal')";
      $db->query($sql_detail);
    }

    // Redirect or show a success message
    $session->msg('s', "Create Bazzar Order Successful!!");
  } else {
    // Error message in case of failure
    $session->msg('s', "Error: " . $sql_order . "<br>" . $db->error);
  }
  redirect('list_bazzar_orders.php', false);
}

include_once('layouts/header.php');
?>

<div class="row">
  <div class="col-md-12">
    <?php echo display_msg($msg); ?>
  </div>
  <div class="col-md-12">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">Form Bazzar</h3>
      </div>
      <div class="panel-body">
        <form method="post" action="create_bazzar.php" class="form-horizontal">
          <!-- Salesman -->
          <div class="form-group">
            <label for="sales_man" class="col-sm-3 control-label">Sales Man:</label>
            <div class="col-sm-9">
              <input type="text" id="sales_man" name="sales_man" class="form-control" placeholder="Enter Sales Man Name"
                required>
            </div>
          </div>
          <!-- Customer Name -->
          <div class="form-group">
            <label for="customer_name" class="col-sm-3 control-label">Customer Name:</label>
            <div class="col-sm-9">
              <input type="text" name="customer_name" class="form-control" style="width: 100%;" required>
            </div>
          </div>

          <!-- Address -->
          <div class="form-group">
            <label for="address" class="col-sm-3 control-label">Customer Address:</label>
            <div class="col-sm-9">
              <textarea id="address" name="address" class="form-control" placeholder="Enter Customer Address" rows="4"
                required></textarea>
            </div>
          </div>

          <!-- Phone Number -->
          <div class="form-group">
            <label for="phone" class="col-sm-3 control-label">Phone Number:</label>
            <div class="col-sm-9">
              <input type="tel" id="phone" name="phone" class="form-control" placeholder="Enter Phone Number" required>
            </div>
          </div>

          <!-- Courier -->
          <div class="form-group">
            <label for="kurir" class="col-sm-3 control-label">Courier:</label>
            <div class="col-sm-9">
              <input type="text" id="kurir" name="kurir" class="form-control" placeholder="Enter Courier Name" required>
            </div>
          </div>

          <!-- Delivery Deadline -->
          <div class="form-group">
            <label for="batas_kirim" class="col-sm-3 control-label">Delivery Deadline:</label>
            <div class="col-sm-9">
              <input type="date" id="batas_kirim" name="batas_kirim" class="form-control"
                placeholder="Enter Delivery Deadline" required>
            </div>
          </div>

          <!-- Warehouse -->
          <div class="form-group">
            <label for="warehouse_id" class="col-sm-3 control-label">Warehouse:</label>
            <div class="col-sm-9">
              <select name="warehouse_id" class="form-control" required>
                <option value="">Select Warehouse</option>
                <?php
                $query = "SELECT warehouse_id, warehouse_name FROM warehouse";
                $result = $db->query($query);
                while ($row = $result->fetch_assoc()) {
                  echo "<option value='{$row['warehouse_id']}'>{$row['warehouse_name']}</option>";
                }
                ?>
              </select>
            </div>
          </div>

          <!-- Description -->
          <div class="form-group">
            <label for="keterangan" class="col-sm-3 control-label">Description:</label>
            <div class="col-sm-9">
              <textarea id="keterangan" name="keterangan" class="form-control" placeholder="Enter Description" rows="4"
                required></textarea>
            </div>
          </div>

          <!-- Order Status -->
          <div class="form-group">
            <label for="status" class="col-sm-3 control-label">Status:</label>
            <div class="col-sm-9">
              <select name="status" class="form-control" required>
                <option value="Pending" selected>Pending</option>
                <!-- <option value="Completed">Completed</option>
                <option value="Cancelled">Cancelled</option>
                <option value="Returned">Returned</option> -->
              </select>
            </div>
          </div>

          <!-- Add Product Button -->
          <div class="form-group">
            <div class="col-sm-12">
              <button type="button" id="add-product" class="btn btn-primary"><i class="fa-solid fa-plus"></i> Add
                Product</button>
            </div>
          </div>

          <!-- Product List -->
          <div id="product-list">
            <table class="table table-bordered">
              <thead>
                <tr>
                  <th style="width: 200px;">Part Number</th>
                  <th>Quantity</th>
                  <th>Price</th>
                  <th>Subtotal</th>
                  <th style="width: 20px;">Action</th>
                </tr>
              </thead>
              <tbody>
                <tr class="product-item">
                  <td>
                    <select name="product_name[]" class="form-control product_name box" required>
                    </select>
                  </td>
                  <td>
                    <input type="number" name="quantity[]" class="form-control quantity" placeholder="Quantity"
                      required>
                  </td>
                  <td>
                    <input type="number" name="price[]" class="form-control price" placeholder="Price" required>
                  </td>
                  <td class="subtotal text-right">0</td>
                  <td class="text-center">
                    <button type="button" class="btn btn-danger remove-product">
                      <i class="fa-solid fa-trash"></i>
                    </button>
                  </td>
                </tr>
              </tbody>
              <tfoot>
                <tr>
                  <td colspan="3" class="text-right"><strong>Total:</strong></td>
                  <td id="total" class="text-right">0</td>
                  <td></td>
                </tr>
              </tfoot>
            </table>
          </div>

          <!-- Submit Button -->
          <div class="form-group">
            <div class="col-sm-offset-5 col-sm-7">
              <button type="submit" class="btn btn-success">Save Bazaar Order</button>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
$(document).ready(function() {

  // Initialize Select2 for Product Names and Customers
  initializeDinamisSelect2($('.product_name'), {
    placeholder: 'Select a Product',
    url: 'api-product-all.php', // Endpoint to fetch products
    idField: 'part_number',
    textField: 'part_number',
  });

  // Calculate totals function
  function calculateTotals() {
    let total = 0;
    // Loop through each product row and calculate subtotal and total
    $('#product-list tbody tr').each(function() {
      const quantity = parseInt($(this).find('.quantity').val()) || 0;
      const price = parseFloat($(this).find('.price').val()) || 0;
      const subtotal = quantity * price;

      // Display the subtotal for this row
      $(this).find('.subtotal').text(formatRupiah(subtotal));

      // Add the subtotal to the overall total
      total += subtotal;
    });

    // Display the overall total
    $('#total').text(formatRupiah(total));
  }

  // Format numbers into currency (Rupiah format)
  function formatRupiah(amount) {
    return amount.toLocaleString('id-ID', {
      style: 'currency',
      currency: 'IDR',
    });
  }

  // Add product row dynamically
  $('#add-product').click(function() {
    // Clone the options from the existing type_box
    const options = $("tr.product-item:first .type_box option").clone();

    // Create a new row for the product
    const newRow = `
            <tr class="product-item">
                <td>
                    <select name="product_name[]" class="form-control product_name box" required>
                    </select>
                </td>
                <td>
                    <input type="number" name="quantity[]" class="form-control quantity" placeholder="Quantity" required>
                </td>
                <td>
                    <input type="number" name="price[]" class="form-control price" placeholder="Price" required>
                </td>
                <td class="subtotal text-right">0</td>
                <td class="text-center">
                    <button type="button" class="btn btn-danger remove-product">
                        <i class="fa-solid fa-trash"></i>
                    </button>
                </td>
            </tr>`;

    // Append the new row to the product list
    $('#product-list tbody').append(newRow);

    // Initialize Select2 for the new product row
    initializeDinamisSelect2($('#product-list tbody .product_name').last(), {
      placeholder: 'Select a Product',
      url: 'api-product-all.php', // Endpoint for products
      idField: 'part_number',
      textField: 'part_number',
    });
  });

  // Remove product row when the trash button is clicked
  $(document).on('click', '.remove-product', function() {
    // Ensure there is at least one product row remaining
    if ($('.product-item').length > 1) {
      $(this).closest('tr').remove();
      calculateTotals(); // Recalculate totals after removing a product row
    } else {
      alert('There must be at least one product.');
    }
  });

  // Update totals when quantity, price, or box is changed
  $(document).on('input', '.quantity, .price', function() {
    calculateTotals(); // Recalculate totals whenever input values change
  });
});
</script>

<?php include_once('layouts/footer.php'); ?>