<?php
$page_title = 'Scan Surat Jalan';
require_once('includes/load.php');
function insert_history($table, $product_id, $part_number, $quantity, $categorie_id, $remark, $loc)
{
  global $db;
  $date = date("Y-m-d");

  $sql = "INSERT INTO {$table} (product_id, part_number, qty, date, categorie_id, remark, loc) 
            VALUES ('{$product_id}', '{$part_number}', '{$quantity}', '{$date}', '{$categorie_id}', '{$remark}', '{$loc}')";
  return $db->query($sql);
}
function find_product_by_part_number_table($table, $part_number)
{
  global $db;
  $part_number = $db->escape($part_number); // Escape input to prevent SQL injection
  $sql = "SELECT * FROM {$table} WHERE part_number = '{$part_number}' LIMIT 1";
  $result = $db->query($sql);

  if ($result) {
    return $result->fetch_assoc(); // Fetch single result as associative array
  } else {
    return null; // Return null if no product found
  }
}

function update_product_qty_by_warehouse(
  $id_warehouse,
  $part_number,
  $quantity,
  $product_id,
  $categorie_id,
  $remark,
  $loc
) {
  global $db;
  $table = "";
  $table_history = "";
  if ($id_warehouse == 1) {
    $table = "products";
    $table_history = "sales";
    $location = "Sidoarjo";
  } elseif ($id_warehouse == 2) {
    $table = "wh_jakarta";
    $table_history = "sales_jakarta";
    $location = "Tangerang";
  } elseif ($id_warehouse == 3) {
    $table = "wh_makassar";
    $table_history = "sales_makassar";
    $location = "Makassar";
  } elseif ($id_warehouse == 4) {
    $table = "wh_bali";
    $table_history = "sales_bali";
    $location = "Bali";
  } elseif ($id_warehouse == 5) {
    $table = "wh_semarang";
    $table_history = "sales_semarang";
    $location = "Semarang";
  } elseif ($id_warehouse == 6) {
    $table = "wh_bandung";
    $table_history = "sales_bandung";
    $location = "Bandung";
  }
  // Update the stock in the warehouse table based on the warehouse ID
  $sql = "UPDATE {$table} SET quantity = quantity - '{$quantity}' WHERE part_number = '{$part_number}'";

  insertStockHistory($part_number, $location,  'OUT', $quantity, $remark, $id_warehouse, $table, 'SALE');
  insert_history(
    $table_history,
    $product_id,
    $part_number,
    $quantity,
    $categorie_id,
    $remark,
    $loc
  );

  return $db->query($sql);
}

if (isset($_POST['scan_type'])) {
  // Retrieve form data
  $no_sj = isset($_POST['no_sj']) ? trim($_POST['no_sj']) : '';
  $scan_type = isset($_POST['scan_type']) ? trim($_POST['scan_type']) : '';

  // Validate inputs
  if (empty($no_sj)) {
    $error = 'No SJ is required.';
    $session->msg('d', $error);
  } elseif (empty($scan_type)) {
    $error = 'Scan Type is required.';
    $session->msg('d', $error);
  } else {
    // Determine which field to update based on scan_type
    if ($scan_type == 'scan_in') {
      $query = "UPDATE orders_offline SET scan_in = NOW() WHERE kode_js = '$no_sj'";
    } else {
      // Fetch the order details from orders_offline
      $orderQuery = "SELECT orders_offline.warehouse_id, orders_offline_detail.product_name, orders_offline_detail.quantity FROM orders_offline_detail join orders_offline on orders_offline.id = orders_offline_detail.order_id WHERE kode_js = '$no_sj'";
      $orderResult = $db->query($orderQuery);

      if ($orderResult && $db->num_rows($orderResult) > 0) {
        while ($order = $db->fetch_assoc($orderResult)) {
          // Extract details
          $id_warehouse = $order['warehouse_id'];
          $part_number = $order['product_name'];
          $quantity = $order['quantity'];
          $table = "products";
          // Find the product in the corresponding table
          $online_product = find_product_by_part_number_table($table, $part_number);

          if ($online_product) {
            $product_id = $online_product['id'];
            $categorie_id = $online_product['categorie_id'];
            $part_number_new = find_part_number_new($part_number);
            if ($part_number_new !== "") {
              $part_number = $part_number_new;
            }
            $loc = "WH";
            $remark = "Scan {$no_sj}";
            // Update the stock in the corresponding warehouse
            if (!update_product_qty_by_warehouse($id_warehouse, $part_number, $quantity, $product_id, $categorie_id, $remark, $loc)) {
              $error = "Failed to update stock for warehouse ID: $id_warehouse, Part Number: $part_number.";
              $session->msg('d', $error);
              redirect('order_offline_scan.php', false);
              exit();
            }
          }
        }

        // Update the scan_out field in orders_offline
        $query = "UPDATE orders_offline SET scan_out = NOW() WHERE kode_js = '$no_sj'";
      } else {
        $error = "Order not found for No SJ: $no_sj.";
        $session->msg('d', $error);
        redirect('order_offline_scan.php', false);
        exit();
      }
    }

    // Execute the query
    if (!$db->query($query)) {
      $error = "Failed to record the scan. No SJ: $no_sj, Scan Type: $scan_type";
      $session->msg('d', $error);
    } else {
      $message = "Scan recorded successfully! No SJ: $no_sj, Scan Type: $scan_type";
      $session->msg('s', $message);
    }

    // Redirect back to the same page
    redirect('order_offline_scan.php', false);
    exit(); // Exit to ensure no further code is executed
  }
}
include_once('layouts/header.php');

// Initialize variables for feedback messages
$message = '';
$error = '';

?>

<div class="row">
  <div class="col-md-12">
    <!-- Display Messages -->
    <div class="large-message">
      <?php echo display_msg($msg); ?>
    </div>
  </div>
  <div class="col-md-12">
    <!-- Scan AWB Form Section -->
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">Scan Order Offline Barcode</h3>
      </div>
      <div class="panel-body">
        <!-- Scan AWB Form -->
        <form id="scanForm" method="post" action="" class="form-horizontal">
          <div class="form-group">
            <label for="awb_resi" class="col-sm-3 control-label">Surat Jalan Scan</label>
            <div class="col-sm-9">
              <input type="text" class="form-control input-lg" name="no_sj" id="awb_resi" placeholder="No SJ" autofocus>
            </div>
          </div>
          <!-- New Field for Scan Type -->
          <div class="form-group">
            <label for="scan_type" class="col-sm-3 control-label">Scan Type</label>
            <div class="col-sm-9">
              <select class="form-control input-lg" name="scan_type" id="scan_type">
                <option value="scan_in">Scan In</option>
                <option value="scan_out">Scan Out</option>
              </select>
            </div>
          </div>
          <div class="form-group">
            <div class="col-sm-offset-3 col-sm-9">
              <button type="submit" name="scan" id="scanBtn" class="btn btn-primary btn-lg">Scan</button>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
<?php include_once('layouts/footer.php'); ?>