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

$order_id = $_GET['id'];  // Get the order ID from the URL

// Fetch the order and details
$sql_order = "SELECT * FROM bazzar WHERE id = '$order_id'";
$order = $db->query($sql_order)->fetch_assoc();

// Fetch the products in the order
$sql_details = "SELECT * FROM bazzar_detail WHERE bazzar_id = '$order_id'";
$details = $db->query($sql_details);

// Handle the return form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $products = $_POST['product_name'];
  $quantities = $_POST['quantity'];
  $reason = $_POST['reason'];

  // Insert each returned product
  for ($i = 0; $i < count($products); $i++) {
    $product_name = $products[$i];
    $quantity = $quantities[$i];

    // Validation: Make sure the return quantity is valid (not more than the available quantity)
    if ($quantity <= 0) {
      $session->msg('d', "Invalid quantity for product: " . $product_name);
      redirect('retur_bazzar.php?id=' . $order_id, false);
      exit();
    }

    // Insert return record
    $sql_return = "INSERT INTO bazzar_return (bazzar_id, product_name, quantity, reason) 
                   VALUES ('$order_id', '$product_name', '$quantity', '$reason')";

    if (!$db->query($sql_return)) {
      $session->msg('d', "Failed to return product: " . $product_name);
      redirect('retur_bazzar.php?id=' . $order_id, false);
      exit();
    }
  }

  $session->msg('s', "Products returned successfully.");
  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">Return Bazzar Products</h3>
      </div>
      <div class="panel-body">
        <!-- Order Info Section -->
        <div class="row">
          <div class="col-sm-6">
            <h4><strong>Order Number:</strong> <?php echo htmlspecialchars($order['bazzar_sn']); ?></h4>
            <p><strong>Salesman:</strong> <?php echo htmlspecialchars($order['sales_man']); ?></p>
            <p><strong>Customer Name:</strong> <?php echo htmlspecialchars($order['customer_name']); ?></p>
            <p><strong>Address:</strong> <?php echo htmlspecialchars($order['address']); ?></p>
            <p><strong>Status:</strong> <?php echo htmlspecialchars($order['status']); ?></p>
            <p><strong>Delivery Deadline:</strong> <?php echo htmlspecialchars($order['batas_kirim']); ?></p>
          </div>
        </div>

        <!-- Return Product Form -->
        <form method="POST" action="retur_bazzar.php?id=<?php echo $order_id; ?>" class="" id="return-form">
          <p><strong>Return Reason (For all products):</strong></p>
          <textarea name="reason" class="form-control" rows="4" placeholder="Enter reason for the return"
            required></textarea>

          <h4>Products:</h4>
          <table class="table table-striped table-bordered table-hover">
            <thead>
              <tr>
                <th>Product Name</th>
                <th>Original Quantity</th>
                <th>Returned Quantity</th>
              </tr>
            </thead>
            <tbody>
              <?php while ($detail = $details->fetch_assoc()) : ?>
                <tr>
                  <td>
                    <input type="hidden" name="product_name[]" value="<?php echo $detail['product_name']; ?>">
                    <?php echo $detail['product_name']; ?>
                  </td>
                  <td><?php echo $detail['quantity']; ?></td>
                  <td>
                    <input type="number" name="quantity[]" class="form-control" min="1"
                      max="<?php echo $detail['quantity']; ?>" required>
                  </td>
                </tr>
              <?php endwhile; ?>
            </tbody>
          </table>

          <div class="form-group text-center">
            <button type="submit" class="btn btn-danger btn-sm">Return Products</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

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

<script>
  $(document).ready(function() {
    // Optional: You can add dynamic row removal or adding rows functionality here
  });
</script>