<?php
$page_title = 'Form Endorse';
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']; // Sales man
  $customer_name = $_POST['customer_name']; // Customer name
  $address = $_POST['address']; // Address
  $phone = $_POST['phone']; // Phone
  $kurir = $_POST['kurir']; // Kurir
  $warehouse_id = $_POST['warehouse_id']; // Warehouse ID
  $endorse_sn = generateCode("EN");
  $endorse_sj = generateCode("SJ");

  // Insert into endorse table
  $keterangan = $_POST['keterangan']; // Keterangan (Description)
  $brand = $_POST['brand']; // Brand (Wiselie or Bacuya)

  // SQL query to insert into endorse table
  $sql_order = "INSERT INTO endorse (endorse_sn, endorse_sj, sales_man, customer_name, address, phone, kurir, keterangan, brand, warehouse_id) VALUES ('$endorse_sn', '$endorse_sj', '$sales_man', '$customer_name', '$address', '$phone', '$kurir', '$keterangan', '$brand', '$warehouse_id')";

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

    // Now handle the details (part_number, quantity, price, subtotal)
    $part_numbers = $_POST['part_number']; // Array of part numbers
    $quantities = $_POST['quantity']; // Array of quantities
    $prices = $_POST['price']; // Array of prices

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

      // Insert into endorse_detail table
      $sql_detail = "INSERT INTO endorse_detail (endorse_id, part_number, quantity, price, subtotal) 
                     VALUES ('$order_id', '$part_number', '$quantity', '$price', '$subtotal')";
      $db->query($sql_detail);
    }

    // Redirect or show a success message
    $session->msg('s', "Create Endorsement Successful!!");
  } else {
    // Error message in case of failure
    $session->msg('s', "Error: " . $sql_order . "<br>" . $db->error);
  }
  redirect('list_endors.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 Endorse</h3>
      </div>
      <div class="panel-body">
        <form method="post" action="" class="form-horizontal">
          <!-- Nama Sales Man -->
          <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>

          <!-- Nama Pelanggan -->
          <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>

          <!-- Alamat Pelanggan -->
          <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>

          <!-- Nomor Telepon -->
          <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>

          <!-- Kurir -->
          <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>

          <!-- Keterangan -->
          <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>

          <!-- Brand -->
          <div class="form-group">
            <label for="brand" class="col-sm-3 control-label">Brand:</label>
            <div class="col-sm-9">
              <select name="brand" id="brand" class="form-control" required>
                <option value="Wiselie">Wiselie</option>
                <option value="Bacuya">Bacuya</option>
              </select>
            </div>
          </div>

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

          <!-- Product Details -->
          <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>

          <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="part_number[]" style="width: 200px;" class="form-control part_number 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 Endorsement</button>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
$(document).ready(function() {
  initializeDinamisSelect2($('#customer_name'), {
    placeholder: 'Select a Customer',
    url: 'api_get_customer.php', // Endpoint for customers
    idField: 'id',
    textField: 'name',
  });
  initializeDinamisSelect2($('.part_number'), {
    placeholder: 'Select a Part Number',
    url: 'api-product-all.php', // Endpoint untuk produk
    idField: 'part_number', // Field ID dari data API
    textField: 'part_number', // Field teks dari data API
  })

  $('#add-product').click(function() {
    const newRow = `
        <tr class="product-item">
          <td>
           <select name="part_number[]" class="form-control part_number 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>
      `;
    $('#product-list tbody').append(newRow);

    initializeDinamisSelect2($('#product-list tbody .part_number').last(), {
      placeholder: 'Select a Part Number',
      url: 'api-product-all.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() {
    $(this).closest('tr').remove();
    calculateTotals();
  });

  $(document).on('input', '.quantity, .price', function() {
    const row = $(this).closest('tr');
    const quantity = parseInt(row.find('.quantity').val()) || 0;
    const price = parseFloat(row.find('.price').val()) || 0;
    const subtotal = quantity * price;

    // Update the subtotal for this row
    row.find('.subtotal').text(subtotal.toFixed(2));

    // Calculate the total price of all products
    calculateTotals();
  });

  function calculateTotals() {
    let total = 0;
    // Loop through each product row
    $('#product-list tbody tr').each(function() {
      const subtotal = parseFloat($(this).find('.subtotal').text()) || 0;
      total += subtotal;
    });

    // Display the overall total
    $('#total').text(total.toFixed(2));
  }
});
</script>

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