<?php
$page_title = 'Create Order';
require_once('includes/load.php');
error_reporting(E_ALL);
ini_set('display_errors', 'on');
page_require_level(1);


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Get the data from the form
  $sales_man = $_POST['sales_man']; // sales man
  $customer_name = $_POST['customer_name']; // customer name
  $address = $_POST['address']; // address
  $phone = $_POST['phone']; // phone
  $kurir = $_POST['kurir']; // kurir
  $po = $_POST['po']; // PO
  $order_sn = "";
  $ppn = isset($_POST['ppn']) ? 1 : 0;


  // Insert into orders_offline table
  if (empty($po)) {
    $order_sn = generateCode("PO");
  } else {
    $order_sn = $po;
  }

  $kode_js = generateCode("SJ");

  $batas_kirim = $_POST['batas_kirim'];
  $type_pembayaran = $_POST['type_pembayaran'];
  $warehouse_id = $_POST['warehouse_id'];
  $sql_order = "INSERT INTO orders_offline (order_sn, sales_man, customer_name, address, phone, kurir, batas_kirim, type_pembayaran, warehouse_id, kode_js, is_ppn) VALUES ('$order_sn', '$sales_man', '$customer_name', '$address', '$phone', '$kurir', '$batas_kirim', '$type_pembayaran', '$warehouse_id', '$kode_js', '$ppn')";

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

    // Insert data into orders_offline_detail table
    $product_names = $_POST['product_name'];
    $type_boxes = $_POST['type_box'];
    $batch_products = $_POST['batch_product'];
    $boxes = $_POST['box'];
    $quantities = $_POST['quantity'];
    $prices = $_POST['price'];

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

      $sql_detail = "INSERT INTO orders_offline_detail (order_id, product_name, type_box, box, quantity, price, subtotal, code_batch_product) VALUES ('$order_id', '$product_name', '$type_box', '$box', '$quantity', '$price', '$subtotal', '$batch_product')";
      $db->query($sql_detail);
    }

    // Redirect or show a success message
    $session->msg('s', "Create Order Berhasil !!");
  } else {
    // Error message in case of failure
    $session->msg('s', "Error: " . $sql_order . "<br>" . $db->error);
  }
  redirect('list_order_offline.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">Create Order</h3>
      </div>
      <div class="panel-body">
        <form method="post" action="create_order.php" class="form-horizontal">
          <!-- Nama Pelanggan -->
          <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="Masukkan nama sales man" required>
            </div>
          </div>
          <div class="form-group">
            <label for="customer_name" class="col-sm-3 control-label">Nama Pelanggan:</label>
            <div class="col-sm-9">
              <select name="customer_name" id="customer_name" class="form-control box" style="width: 100%;" required>
              </select>
            </div>
          </div>
          <div class="form-group">
            <label for="customer_name" class="col-sm-3 control-label">No PO:</label>
            <div class="col-sm-9">
              <input type="text" id="po" name="po" class="form-control" placeholder="Masukkan no po">
            </div>
          </div>
          <!-- Alamat Penerima -->
          <div class="form-group">
            <label for="address" class="col-sm-3 control-label">Alamat Pelanggan:</label>
            <div class="col-sm-9">
              <textarea id="address" name="address" class="form-control" placeholder="Masukkan alamat pelanggan"
                rows="4" required></textarea>
            </div>
          </div>

          <!-- Nomor Telepon -->
          <div class="form-group">
            <label for="phone" class="col-sm-3 control-label">Nomor Telepon:</label>
            <div class="col-sm-9">
              <input type="tel" id="phone" name="phone" class="form-control" placeholder="Masukkan nomor telepon"
                required>
            </div>
          </div>
          <div class="form-group">
            <label for="phone" class="col-sm-3 control-label">Keterangan:</label>
            <div class="col-sm-9">
              <input type="text" id="kurir" name="kurir" class="form-control" placeholder="Masukkan kurir" required>
            </div>
          </div>
          <div class="form-group">
            <label for="phone" class="col-sm-3 control-label">Type Pembayaran:</label>
            <div class="col-sm-9">
              <input type="text" id="type_pembayaran" name="type_pembayaran" class="form-control"
                placeholder="Masukkan Pembayaran" required>
            </div>
          </div>
          <div class="form-group">
            <label for="phone" class="col-sm-3 control-label">Batas Kirim:</label>
            <div class="col-sm-9">
              <input type="date" id="batas_kirim" name="batas_kirim" class="form-control"
                placeholder="Masukkan Batas Kirim" required>
            </div>
          </div>
          <div class="form-group">
            <label for="phone" class="col-sm-3 control-label">Warehouse:</label>
            <div class="col-sm-9">
              <select name="warehouse_id" class="form-control" required>
                <option value="">Pilih 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>
          <div class="form-group">
            <label class="col-sm-3 control-label"><strong>PPN</strong></label>
            <div class="col-sm-9">
              <input type="checkbox" id="ppn" name="ppn" value="1">
            </div>
          </div>
          <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></button>
            </div>
          </div>
          <!-- Produk -->
          <div id="product-list">
            <table class="table table-bordered">
              <thead>
                <tr>
                  <th>Batch Product</th>
                  <th style="width: 200px;">Nama Produk</th>
                  <th>Type Box</th>
                  <th>Box</th>
                  <th>Jumlah</th>
                  <th>Harga</th>
                  <th>Subtotal</th>
                  <th style="width: 20px;">Aksi</th>
                </tr>
              </thead>
              <tbody>
                <tr class="product-item">
                  <td>
                    <input type="text" name="batch_product[]" class="form-control batch_product"
                      placeholder="Masukkan Batch Product" required>
                  </td>
                  <td>
                    <select name="product_name[]" style="width: 200px;" class="form-control product_name box" required>
                    </select>
                  </td>
                  <td>
                    <select name="type_box[]" class="form-control type_box" required>
                      <option value="">Pilih Type Box</option>
                      <?php
                      $query = "SELECT * FROM type_box";
                      $result = $db->query($query);
                      while ($row = $result->fetch_assoc()) {
                        echo "<option value='{$row['id']}'>{$row['name']}</option>";
                      }
                      ?>
                    </select>
                  </td>
                  <td>
                    <input type="number" name="box[]" class="form-control box qty_box" placeholder="Jumlah Box"
                      required>
                  </td>
                  <td>
                    <input type="number" name="quantity[]" class="form-control quantity box" placeholder="Jumlah"
                      required>
                  </td>
                  <td>
                    <input type="number" name="price[]" class="form-control price box" placeholder="Harga" 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="5" class="text-right"><strong>Total:</strong></td>
                  <td id="total" class="text-right">0</td>
                  <td></td>
                </tr>
              </tfoot>
            </table>
          </div>
          <!-- Tombol Submit -->
          <div class="form-group">
            <div class="col-sm-offset-5 col-sm-7">
              <button type="submit" class="btn btn-success">Simpan Pesanan</button>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
<script>
  function initializeDinamisSelect2(element, options = {}) {
    const defaultOptions = {
      placeholder: 'Select an option', // Default placeholder
      url: '', // Default URL (should be provided in options)
      idField: 'id', // Default field for the ID
      textField: 'text', // Default field for the display text
      delay: 250, // Default delay for AJAX requests
      onSelect: null, // Callback function for select event
    };

    // Merge default options with user-provided options
    const config = {
      ...defaultOptions,
      ...options
    };

    element.select2({
      placeholder: config.placeholder,
      ajax: {
        url: config.url,
        dataType: 'json',
        delay: config.delay,
        data: function(params) {
          return {
            q: params.term, // Search term
            page: params.page || 1,
          };
        },
        processResults: function(data, params) {
          params.page = params.page || 1;

          return {
            results: data.map(function(item) {
              return {
                id: item[config.idField], // Dynamically use the ID field
                text: item[config.textField], // Dynamically use the text field
                item: item,
              };
            }),
            pagination: {
              more: data.length > 0, // Determine if more results are available
            },
          };
        },
      },
    });

    // Add event listener for select2:select
    element.on('select2:select', function(e) {
      const selectedData = e.params.data;

      // If a callback function is provided, call it with the selected data
      if (typeof config.onSelect === 'function') {
        config.onSelect(selectedData);
      }
    });
  }

  $(document).ready(function() {
    initializeDinamisSelect2($('.product_name'), {
      placeholder: 'Select a Part Number',
      url: 'api-product.php', // Endpoint untuk produk
      idField: 'part_number', // Field ID dari data API
      textField: 'part_number', // Field teks dari data API
    })
    initializeDinamisSelect2($('#customer_name'), {
      placeholder: 'Select a Pelanggan',
      url: 'api_get_pelanggan.php', // Endpoint untuk produk
      idField: 'nama', // Field ID dari data API
      textField: 'nama', // Field teks dari data API
      onSelect: function(selectedData) {
        // Fill other elements based on the selected data
        $('#address').val(selectedData.item.alamat); // Example: Fill product name
        $('#phone').val(selectedData.item.nomor_telp); // Example: Fill product ID
      },
    })

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

        // Display subtotal in the Subtotal column
        $(this).find('.subtotal').text(formatRupiah(subtotal));

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

      // Display the overall total
      $('#total').text(formatRupiah(total));
    }
    $('#add-product').click(function() {
      // Clone the options from the existing type_box
      const options = $("tr.product-item:first .type_box option")
        .clone(); // Clone options dari baris pertama


      // Create the new row
      const newRow = `
    <tr class="product-item">
    <td><input type="text" name="batch_product[]" class="form-control batch_product"
                      placeholder="Masukkan Batch Product" required> </td>
      <td>
        <select name="product_name[]" class="form-control product_name box" required>
        </select>
      </td>
      <td>
        <select name="type_box[]" class="form-control type_box" required>
          ${options.get().map(option => option.outerHTML).join('')}
        </select>
      </td>
      <td>
        <input type="number" name="box[]" class="form-control qty_box" placeholder="Jumlah Box" required>
      </td>
      <td>
        <input type="number" name="quantity[]" class="form-control quantity box" placeholder="Jumlah" required>
      </td>
      <td>
        <input type="number" name="price[]" class="form-control price box" placeholder="Harga" 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 table
      $('#product-list tbody').append(newRow);

      initializeDinamisSelect2($('#product-list tbody .product_name').last(), {
        placeholder: 'Select a Part Number',
        url: 'api-product.php', // Endpoint untuk produk
        idField: 'part_number', // Field ID dari data API
        textField: 'part_number', // Field teks dari data API
      })
    });

    $(document).on('click', '.remove-product', function() {
      // Remove product row
      if ($('.product-item').length > 1) {
        $(this).closest('tr').remove();
        calculateTotals();
      } else {
        alert('There must be at least one product.');
      }
    });

    $(document).on('input', '.quantity, .price, .qty_box', function() {
      calculateTotals();
    });
  });
  $(document).on("input", ".qty_box", function() {
    let row = $(this).closest("tr");
    let part_number = row.find(".product_name").val();
    let type_box_id = row.find(".type_box").val();
    let min_box = $(this).val();

    if (part_number && type_box_id && min_box > 0) {
      $.ajax({
        url: "api_get_pricing.php",
        type: "POST",
        data: {
          part_number: part_number,
          type_box_id: type_box_id,
          min_box: min_box
        },
        dataType: "json",
        success: function(response) {
          if (response.success) {
            row.find(".quantity").val(response.qty_per_box * min_box);
            row.find(".price").val(parseInt(response.price));
            calculateTotals();
          } else {
            alert(response.message);
          }
        }
      });
    }
  });
</script>
<?php include_once('layouts/footer.php'); ?>