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

// AKTIFKAN INI UNTUK MELIHAT PESAN ERROR JIKA HALAMAN PUTIH MASIH MUNCUL
// ini_set('display_errors', 1);
// error_reporting(E_ALL);

$user = current_user();
$is_user_level_1 = ($user['user_level'] == 1);

// Pastikan order_id ada dan valid
if (!isset($_GET['order_id']) || !(int)$_GET['order_id']) {
    $session->msg('d', "Invalid Order ID.");
    redirect('list_order_offline.php');
}
$order_id = (int)$_GET['order_id'];

// Proses form HANYA jika metode adalah POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Pastikan user memiliki izin untuk mengedit
    if (!$is_user_level_1) {
        $session->msg('d', 'Anda tidak memiliki izin untuk mengubah pesanan.');
        redirect('list_order_offline.php');
    }

    // Ambil data dari POST
    $sales_man = $_POST['sales_man'] ?? '';
    $customer_name = $_POST['customer_name'] ?? '';
    $po = $_POST['po'] ?? '';
    $address = $_POST['address'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $kurir = $_POST['kurir'] ?? '';
    $type_pembayaran = $_POST['type_pembayaran'] ?? '';
    $batas_kirim = $_POST['batas_kirim'] ?? '';
    $warehouse_id = (int)($_POST['warehouse_id'] ?? 0);
    $order_sn = $_POST['order_sn'] ?? ''; // Untuk pesan sukses

    // Mulai Transaksi Database
    $db->begin_transaction();

    try {
        // Query UPDATE utama dengan prepared statement yang sudah diperbaiki
        $sql_update_order = "UPDATE orders_offline SET 
                                sales_man = ?, customer_name = ?, address = ?, phone = ?, kurir = ?, 
                                type_pembayaran = ?, batas_kirim = ?, warehouse_id = ?, order_sn = ?, 
                                updated_at = NOW(), edited_at = NOW() 
                            WHERE id = ?";
        
        $stmt_order = $db->prepare($sql_update_order);
        // Tipe data untuk 'id' di akhir adalah integer 'i', bukan 's'
        $stmt_order->bind_param('sssssssisi', $sales_man, $customer_name, $address, $phone, $kurir, $type_pembayaran, $batas_kirim, $warehouse_id, $po, $order_id);
        
        if (!$stmt_order->execute()) {
            throw new Exception("Gagal mengupdate data order utama: " . $stmt_order->error);
        }
        $stmt_order->close();


        // Proses update/insert untuk detail produk
        $product_names = $_POST['product_name'] ?? [];
        $id_details = $_POST['id_detail'] ?? [];
        $type_boxes = $_POST['type_box'] ?? [];
        $boxes = $_POST['box'] ?? [];
        $quantities = $_POST['quantity'] ?? [];
        $prices = $_POST['price'] ?? [];
        
        // Prepare statements untuk detail (lebih efisien)
        $sql_insert_detail = "INSERT INTO orders_offline_detail (order_id, product_name, type_box, box, quantity, price, subtotal) VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmt_insert = $db->prepare($sql_insert_detail);

        $sql_update_detail = "UPDATE orders_offline_detail SET product_name = ?, type_box = ?, box = ?, quantity = ?, price = ?, subtotal = ? WHERE id = ? AND order_id = ?";
        $stmt_update = $db->prepare($sql_update_detail);

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

            if ($id_detail === 0) { // Item baru, lakukan INSERT
                $stmt_insert->bind_param('isiiidd', $order_id, $product_name, $type_box, $box, $quantity, $price, $subtotal);
                if(!$stmt_insert->execute()) throw new Exception("Gagal menambah detail produk: " . $stmt_insert->error);
            } else { // Item lama, lakukan UPDATE
                $stmt_update->bind_param('siiiddii', $product_name, $type_box, $box, $quantity, $price, $subtotal, $id_detail, $order_id);
                if(!$stmt_update->execute()) throw new Exception("Gagal mengupdate detail produk: " . $stmt_update->error);
            }
        }
        $stmt_insert->close();
        $stmt_update->close();
        
        // Jika semua query berhasil, commit transaksi
        $db->commit();
        $session->msg('s', "Sukses perbarui data order " . htmlspecialchars($order_sn));

    } catch (Exception $e) {
        // Jika ada error, batalkan semua perubahan
        $db->rollback();
        $session->msg('d', "Terjadi kesalahan: " . $e->getMessage());
    }

    redirect('list_order_offline.php', false);
}

// --- Bagian untuk menampilkan data (GET request) ---

// Retrieve the order details from the database
$sql = "SELECT * FROM orders_offline WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param('i', $order_id);
$stmt->execute();
$result = $stmt->get_result();
$order = $result->fetch_assoc();
$stmt->close();

// Jika order tidak ditemukan setelah form handling
if (!$order) {
    $session->msg('d', "Order not found!");
    redirect('list_order_offline.php');
}

// Retrieve the order's product details
$sql_details = "SELECT * FROM orders_offline_detail WHERE order_id = ?";
$stmt_details = $db->prepare($sql_details);
$stmt_details->bind_param('i', $order_id);
$stmt_details->execute();
$result_details = $stmt_details->get_result();
$order_details = [];
while ($row = $result_details->fetch_assoc()) {
    $order_details[] = $row;
}
$stmt_details->close();

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">Edit Order #<?php echo htmlspecialchars($order['order_sn']); ?></h3>
      </div>
      <div class="panel-body">
        <form method="POST" action="edit_order.php?order_id=<?php echo (int)$order['id']; ?>" class="form-horizontal">
          <input type="hidden" name="order_sn" value="<?php echo htmlspecialchars($order['order_sn']); ?>">
          
          <!-- 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"
                     value="<?php echo htmlspecialchars($order['sales_man']); ?>" required>
            </div>
          </div>

          <!-- Customer Name -->
          <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" style="width: 100%;" required>
                <option value="<?php echo htmlspecialchars($order['customer_name']); ?>" selected><?php echo htmlspecialchars($order['customer_name']); ?></option>
              </select>
            </div>
          </div>

          <!-- PO Number -->
          <div class="form-group">
            <label for="po" class="col-sm-3 control-label">No PO:</label>
            <div class="col-sm-9">
              <input type="text" id="po" name="po" value="<?php echo htmlspecialchars($order['order_sn']); ?>" class="form-control"
                     placeholder="Masukkan no po">
            </div>
          </div>

          <!-- Address -->
          <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" rows="4"
                        required><?php echo htmlspecialchars($order['address']); ?></textarea>
            </div>
          </div>
          
          <!-- Form fields lainnya... (phone, kurir, etc.) -->
          <!-- ... pastikan semua value di dalam form menggunakan htmlspecialchars() ... -->

          <!-- Phone -->
          <div class="form-group">
            <label for="phone" class="col-sm-3 control-label">No Telp:</label>
            <div class="col-sm-9">
              <input type="tel" id="phone" name="phone" class="form-control" value="<?php echo htmlspecialchars($order['phone']); ?>" required>
            </div>
          </div>

          <!-- Courier -->
          <div class="form-group">
            <label for="kurir" class="col-sm-3 control-label">Kurir:</label>
            <div class="col-sm-9">
              <input type="text" id="kurir" name="kurir" class="form-control" value="<?php echo htmlspecialchars($order['kurir']); ?>" required>
            </div>
          </div>

          <!-- Payment Type -->
          <div class="form-group">
            <label for="type_pembayaran" 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" value="<?php echo htmlspecialchars($order['type_pembayaran']); ?>" required>
            </div>
          </div>

          <!-- Delivery Date -->
          <div class="form-group">
            <label for="batas_kirim" class="col-sm-3 control-label">Batas Pengiriman:</label>
            <div class="col-sm-9">
              <input type="date" id="batas_kirim" name="batas_kirim" class="form-control" value="<?php echo htmlspecialchars($order['batas_kirim']); ?>" 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" id="warehouse_id" class="form-control" required>
                <option value="">Pilih Warehouse</option>
                <?php
                  $query_wh = "SELECT warehouse_id, warehouse_name FROM warehouse";
                  $result_wh = $db->query($query_wh);
                  while ($row_wh = $result_wh->fetch_assoc()) {
                      $selected = ($order['warehouse_id'] == $row_wh['warehouse_id']) ? 'selected' : '';
                      echo "<option value='{$row_wh['warehouse_id']}' {$selected}>" . htmlspecialchars($row_wh['warehouse_name']) . "</option>";
                  }
                ?>
              </select>
            </div>
          </div>

          <hr>

          <!-- Product Details Table -->
          <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> Tambah Produk</button>
            </div>
          </div>
          <div id="product-list">
            <table class="table table-bordered">
              <thead>
                <tr>
                  <th>Batch Product</th>
                  <th style="width: 25%;">Product Name</th>
                  <th>Box Type</th>
                  <th>Box</th>
                  <th>Quantity</th>
                  <th>Price</th>
                  <th>Subtotal</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                <?php
                  $total = 0;
                  if (!empty($order_details)):
                    foreach ($order_details as $item) :
                      $total += $item['subtotal'];
                ?>
                  <tr class="product-item">
                    <input type="hidden" value="<?php echo (int)$item['id']; ?>" name="id_detail[]">
                    <td>
                      <input type="text" value="<?php echo htmlspecialchars($item['code_batch_product']); ?>" name="batch_product[]" class="form-control batch_product" placeholder="Batch Product">
                    </td>
                    <td>
                      <select name="product_name[]" class="form-control product_name" required>
                        <option value="<?php echo htmlspecialchars($item['product_name']); ?>" selected><?php echo htmlspecialchars($item['product_name']); ?></option>
                      </select>
                    </td>
                    <td>
                      <select name="type_box[]" class="form-control type_box" required>
                        <?php
                          $query_box = "SELECT id, name FROM type_box";
                          $result_box = $db->query($query_box);
                          while ($row_box = $result_box->fetch_assoc()) {
                            $selected = ($item['type_box'] == $row_box['id']) ? 'selected' : '';
                            echo "<option value='{$row_box['id']}' {$selected}>" . htmlspecialchars($row_box['name']) . "</option>";
                          }
                        ?>
                      </select>
                    </td>
                    <td><input type="number" name="box[]" class="form-control box qty_box" value="<?php echo (int)$item['box']; ?>" required></td>
                    <td><input type="number" name="quantity[]" class="form-control quantity" value="<?php echo (int)$item['quantity']; ?>" required></td>
                    <td><input type="number" name="price[]" class="form-control price" value="<?php echo (float)$item['price']; ?>" required></td>
                    <td class="subtotal text-right"><?php echo number_format($item['subtotal']); ?></td>
                    <td class="text-center"><button type="button" class="btn btn-danger btn-sm remove-product"><i class="fa fa-trash"></i></button></td>
                  </tr>
                <?php endforeach; endif; ?>
              </tbody>
              <tfoot>
                <tr>
                  <td colspan="6" class="text-right"><strong>Total:</strong></td>
                  <td id="total" class="text-right"><?php echo number_format($total); ?></td>
                  <td></td>
                </tr>
              </tfoot>
            </table>
          </div>

          <!-- Submit Button -->
          <div class="form-group">
            <div class="col-sm-offset-3 col-sm-9">
              <button type="submit" class="btn btn-success">Update Order</button>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
<!-- SCRIPTS (PASTIKAN SEMUA LIBRARY SEPERTI JQUERY, SELECT2, BOOTBOX SUDAH TER-LOAD DARI FOOTER) -->
<script>
  // Fungsi untuk memformat angka menjadi format Rupiah
  function formatRupiah(angka) {
      return new Intl.NumberFormat('id-ID').format(angka);
  }

  // Fungsi inisialisasi Select2
  function initializeDinamisSelect2(element, options = {}) {
      const config = {
          placeholder: 'Select an option',
          url: '',
          idField: 'id',
          textField: 'text',
          delay: 250,
          onSelect: null,
          ...options
      };

      element.select2({
          placeholder: config.placeholder,
          ajax: {
              url: config.url,
              dataType: 'json',
              delay: config.delay,
              data: params => ({ q: params.term, page: params.page || 1 }),
              processResults: (data, params) => ({
                  results: data.map(item => ({
                      id: item[config.idField],
                      text: item[config.textField],
                      item: item,
                  })),
                  pagination: { more: data.length > 9 }
              }),
          },
      }).on('select2:select', e => {
          if (typeof config.onSelect === 'function') {
              config.onSelect(e.params.data);
          }
      });
  }

  $(document).ready(function() {
      // Inisialisasi untuk item yang sudah ada
      $('.product_name').each(function() {
          const selectElement = $(this);
          const initialValue = selectElement.val();
          const initialText = selectElement.find('option:selected').text();

          initializeDinamisSelect2(selectElement, {
              placeholder: 'Select a Part Number',
              url: 'api-product.php',
              idField: 'part_number',
              textField: 'part_number',
          });
          
          // Set initial value jika ada
          if (initialValue) {
              const option = new Option(initialText, initialValue, true, true);
              selectElement.append(option).trigger('change');
          }
      });

      // Inisialisasi untuk customer
      const customerSelect = $('#customer_name');
      const initialCustomerValue = customerSelect.val();
      const initialCustomerText = customerSelect.find('option:selected').text();
      initializeDinamisSelect2(customerSelect, {
          placeholder: 'Select a Pelanggan',
          url: 'api_get_pelanggan.php',
          idField: 'nama',
          textField: 'nama',
          onSelect: function(data) {
              $('#address').val(data.item.alamat);
              $('#phone').val(data.item.nomor_telp);
          },
      });
      if (initialCustomerValue) {
        const option = new Option(initialCustomerText, initialCustomerValue, true, true);
        customerSelect.append(option).trigger('change');
      }

      function calculateTotals() {
          let total = 0;
          $('#product-list tbody tr').each(function() {
              const quantity = parseFloat($(this).find('.quantity').val()) || 0;
              const price = parseFloat($(this).find('.price').val()) || 0;
              const subtotal = quantity * price;
              $(this).find('.subtotal').text(formatRupiah(subtotal));
              total += subtotal;
          });
          $('#total').text(formatRupiah(total));
      }

      $('#add-product').click(function() {
          const options = $("tr.product-item:first .type_box option").clone();
          const newRow = `
            <tr class="product-item">
              <td>
                <input type="hidden" value="0" name="id_detail[]" required>
                <input type="text" name="batch_product[]" class="form-control batch_product" placeholder="Masukkan Batch Product">
              </td>
              <td><select name="product_name[]" class="form-control product_name" style="width:100%;" required></select></td>
              <td><select name="type_box[]" class="form-control type_box" required>${options.get().map(o => o.outerHTML).join('')}</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" placeholder="Jumlah" required></td>
              <td><input type="number" name="price[]" class="form-control price" 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>`;
          
          $('#product-list tbody').append(newRow);

          const newSelect = $('#product-list tbody tr:last .product_name');
          initializeDinamisSelect2(newSelect, {
              placeholder: 'Select a Part Number',
              url: 'api-product.php',
              idField: 'part_number',
              textField: 'part_number',
          });
      });

      $(document).on('click', '.remove-product', function() {
          const row = $(this).closest('tr');
          if ($('.product-item').length <= 1) {
              bootbox.alert('Harus ada setidaknya satu produk dalam pesanan.');
              return;
          }
          const productName = row.find("select[name='product_name[]']").val() || 'produk baru';
          const detailId = row.find("input[name='id_detail[]']").val();

          bootbox.confirm(`Anda yakin ingin menghapus ${productName}?`, function(result) {
              if (result) {
                  if (detailId == 0) { // Jika item baru yg belum disimpan ke DB
                      row.remove();
                      calculateTotals();
                      return;
                  }
                  
                  $.ajax({
                      url: "api_remove_orders_detail.php",
                      type: "POST",
                      data: { detail_id: detailId },
                      dataType: 'json',
                      success: function(res) {
                          if (res.success) {
                              row.remove();
                              calculateTotals();
                              bootbox.alert('Item berhasil dihapus.');
                          } else {
                              bootbox.alert('Gagal menghapus item: ' + res.message);
                          }
                      },
                      error: function() {
                          bootbox.alert('Terjadi kesalahan saat menghubungi server.');
                      }
                  });
              }
          });
      });

      $(document).on('input', '.quantity, .price', 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, type_box_id, 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 {
                          // Tidak perlu alert agar tidak mengganggu, cukup log di console
                          console.warn(response.message);
                      }
                  }
              });
          }
      });
  });
</script>
<?php include_once('layouts/footer.php'); ?>