<?php  
$page_title = 'Multi Scan AWB';  
require_once('includes/load.php');  
page_require_level(3);  
  
// Set default timezone  
date_default_timezone_set('Asia/Jakarta');  
  
$cache_key_resi = 'monitoring:resi:sidoarjo:belum_scan_out';  
  
// Periksa apakah refresh diminta  
if (isset($_GET['refresh_resi']) && $_GET['refresh_resi'] === 'true') {  
  // Hapus cache jika ada  
  redisDelete($cache_key_resi);  
  redirect('multi_scan_out.php', false);  
}  
  
// Ambil data dari Redis jika ada  
$data_resi = redisGet($cache_key_resi);  
  
if (!$data_resi) {  
  // Jika data tidak ada di Redis, query database  
  $sql_resi = "  
    SELECT  
        DISTINCT awb.resi  
    FROM  
        awb  
    JOIN  
        orders o ON awb.invoice = o.order_sn  
    JOIN  
        packing_list pl ON o.id_packing_list = pl.id  
    WHERE  
        NOT awb.scan_in IS NULL   
        AND awb.scan_status IS NULL  
        AND DATE(pl.created_at) BETWEEN CURDATE() - INTERVAL 3 DAY AND CURDATE()  
        AND pl.zipcode = '61256';  
    ";  
  
  $stmt_resi = $db->prepare($sql_resi);  
  $stmt_resi->execute();  
  $result_resi = $stmt_resi->get_result();  
  
  // Format hasil query menjadi array  
  $data_resi = [];  
  while ($row = $result_resi->fetch_assoc()) {  
    $data_resi[] = $row;  
  }  
  
  // Simpan hasil query ke Redis dengan TTL 5 menit  
  redisSet($cache_key_resi, $data_resi, 5000);  
}  
  
$resi_list = array_map(function ($row) {  
  return $row['resi'];  
}, $data_resi);  
  
// Gabungkan array menjadi satu string dengan koma  
$resi_string = implode(", ", $resi_list);  
  
// Tambahkan kolom loc pada tabel awb jika belum ada  
function add_loc_column_to_awb()  
{  
  global $db;  
  // Cek apakah kolom loc sudah ada  
  $sql_check = "SHOW COLUMNS FROM awb LIKE 'loc'";  
  $result = $db->query($sql_check);  
  if ($result->num_rows === 0) {  
    // Tambahkan kolom loc jika belum ada  
    $sql_add = "ALTER TABLE awb ADD COLUMN loc VARCHAR(255) DEFAULT 'Surabaya'";  
    $db->query($sql_add);  
  }  
}  
  
// Pastikan kolom loc sudah ditambahkan sebelum proses scan  
add_loc_column_to_awb();  
  
// Function to check if AWB is already scanned  
function is_scan_completed($awb_resi)  
{  
  global $db;  
  $result = find_by_resi($awb_resi);  
  return !empty($result['scan_status']);  
}  
  
function find_product_by_part_number_online_sby($part_number)  
{  
  global $db;  
  $part_number = $db->escape($part_number); // Escape input to prevent SQL injection  
  $sql = "SELECT * FROM products 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  
  }  
}  
  
if (isset($_POST['scan'])) {  
  $resi_input = trim($_POST['awb_resi']);  
  $packer_no = $db->escape($_POST['packer_no']);  
  
  // Split the input by commas or newlines  
  $resi_numbers = preg_split('/[\s,]+/', $resi_input, -1, PREG_SPLIT_NO_EMPTY);  
  
  $success_count = 0;  
  $error_messages = [];  
  
  foreach ($resi_numbers as $awb_resi) {  
    $awb_resi = $db->escape($awb_resi);  
  
    // Fetch all part numbers and quantities for the given AWB resi  
    $awb_records = get_part_numbers_and_quantities_by_resi($awb_resi);  
  
    if ($awb_records) {  
      if (is_scan_completed($awb_resi)) {  
        $error_messages[] = "AWB {$awb_resi} DOUBLE SCAN!!";  
      } else {  
        $scan_status = date("Y-m-d H:i:s");  
        // Update the SQL statement to set loc to NULL  
        $sql = "UPDATE awb SET scan_status = '{$scan_status}', packer_no = '{$packer_no}', loc = NULL WHERE resi = '{$awb_resi}'";  
        if ($db->query($sql)) {  
          foreach ($awb_records as $awb) {  
            $part_number = $awb['part_number'];  
            $quantity = $awb['quantity'];  
            $online_product = find_product_by_part_number_online_sby($part_number);  
  
            if ($online_product) {  
              $product_id = $online_product['id'];  
              $categorie_id = $online_product['categorie_id'];  
              $remark = "Scan {$awb_resi}";  // Update remark with resi number and "Scan"  
              $loc = "Etalase Online";  // Adjust location as necessary  
  
              // Insert into sales table  
              if (insert_into_sales($product_id, $part_number, $quantity, $categorie_id, $remark, $loc)) {  
                // Update online_products table  
                if (!update_product_qty_online_products($part_number, $quantity)) {  
                  $error_messages[] = "Failed to update product quantity in online_products table for AWB {$awb_resi}.";  
                }  
              } else {  
                $error_messages[] = "Failed to insert into sales table for AWB {$awb_resi}.";  
              }  
            } else {  
              $error_messages[] = "Product with part number {$part_number} not found in online_products table for AWB {$awb_resi}.";  
            }  
          }  
          $success_count++;  
        } else {  
          $error_messages[] = "Failed to update scan status for AWB barcode {$awb_resi}.";  
        }  
      }  
    } else {  
      $error_messages[] = "AWB barcode {$awb_resi} Tidak ada!!";  
    }  
  }  
  
  if ($success_count > 0) {  
    $session->msg('s', "Berhasil memindai {$success_count} AWB!");  
  }  
  
  if (!empty($error_messages)) {  
    foreach ($error_messages as $error) {  
      $session->msg('d', $error);  
    }  
  }  
  
  $_SESSION['selected_packer_no'] = $packer_no;  
  redirect('multi_scan_out.php', false);  
}  
  
$today_scan_count = get_today_scan_count();  
$today_scan_in_count = get_today_scan_in_count();  
$selected_packer_no = isset($_SESSION['selected_packer_no']) ? $_SESSION['selected_packer_no'] : '';  
  
include_once('layouts/header.php');  
?>  
  
<div class="row">  
  <div class="col-md-8">  
    <div class="panel panel-default">  
      <div class="panel-heading">  
        <h3 class="panel-title">Multi Scan AWB Barcode</h3>  
      </div>  
      <div class="panel-body">  
        <form id="scanForm" method="post" action="multi_scan_out.php" class="form-horizontal">  
          <div class="form-group">  
            <label for="awb_resi" class="col-sm-3 control-label">AWB Resi</label>  
            <div class="col-sm-9">  
              <textarea class="form-control input-lg" name="awb_resi" id="awb_resi" placeholder="Masukkan AWB Resi, pisahkan dengan koma atau newline" rows="10" required></textarea>  
            </div>  
          </div>  
          <div class="form-group">  
            <label for="packer_no" class="col-sm-3 control-label">Packer No</label>  
            <div class="col-sm-9">  
              <select class="form-control input-lg" name="packer_no" id="packer_no">  
                <option value="">Pilih Packer No</option>  
                <?php for ($i = 1; $i <= 21; $i++): ?>  
                  <option value="<?php echo $i; ?>" <?php echo $i == $selected_packer_no ? 'selected' : ''; ?>>  
                    <?php echo $i; ?></option>  
                <?php endfor; ?>  
              </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 class="col-md-4">  
    <div class="scan-count-panel">  
      <div class="panel panel-default">  
        <div class="panel-heading">  
          <h3 class="panel-title">Total Scan Out</h3>  
        </div>  
        <div class="panel-body">  
          <div class="scan-count">  
            <p><?php echo $today_scan_count; ?></p>  
          </div>  
          <div class="scan-in-count">  
            <p>Scan In : <?php echo $today_scan_in_count; ?></p>  
          </div>  
          <div class="scan-difference">  
            <p>Selisih: <?php echo $today_scan_in_count - $today_scan_count; ?></p>  
          </div>  
        </div>  
      </div>  
    </div>  
  </div>  
  <div class="col-md-12">  
    <div class="large-message">  
      <?php echo display_msg($msg); ?>  
    </div>  
  </div>  
  <div class="col-md-12">  
    <!-- Display Data Table -->  
    <div class="panel panel-default">  
      <div class="panel-heading">  
        <h3 class="panel-title">Monitoring Resi Belum Scan Out Hari Ini</h3>  
        <a href="multi_scan_out.php?refresh_resi=true" class="btn btn-warning pull-right">Refresh Data</a>  
      </div>  
      <div class="panel-body">  
        <table class="table table-bordered table-striped">  
          <thead>  
            <tr>  
              <th>AWB Resi</th>  
            </tr>  
          </thead>  
          <tbody>  
            <tr>  
              <td><?php echo htmlspecialchars($resi_string); ?></td>  
            </tr>  
          </tbody>  
        </table>  
      </div>  
    </div>  
  </div>  
</div>  
  
<?php include_once('layouts/footer.php'); ?>  
  
<style>  
  /* Styling untuk memperbesar font tabel */  
  .table.table-bordered.table-striped {  
    font-size: 20px;  
    /* Ukuran font untuk teks dalam tabel */  
  }  
  
  .table.table-bordered.table-striped th {  
    font-size: 22px;  
    /* Ukuran font untuk header tabel */  
    font-weight: bold;  
    /* Menambahkan huruf tebal pada header */  
  }  
  
  .table.table-bordered.table-striped td {  
    vertical-align: middle;  
    /* Posisi teks di tengah secara vertikal */  
  }  
  
  * {  
    animation: none !important;  
    transition: none !important;  
  }  
  
  .form-control.input-lg {  
    font-size: 18px;  
    padding: 10px;  
  }  
  
  .form-horizontal .control-label {  
    font-size: 18px;  
  }  
  
  .form-horizontal .btn.btn-lg {  
    font-size: 18px;  
    padding: 10px 20px;  
  }  
  
  .large-message {  
    font-size: 50px;  
    font-weight: bold;  
    color: #ff0000;  
    text-align: center;  
    margin-top: 20px;  
  }  
  
  .scan-count-panel {  
    background-color: #f2f2f2;  
    padding: 20px;  
    text-align: center;  
    border: 1px solid #ccc;  
    border-radius: 5px;  
    margin-bottom: 20px;  
  }  
  
  .scan-count-panel .panel-title {  
    font-size: 20px;  
    font-weight: bold;  
  }  
  
  .scan-count {  
    font-size: 50px;  
    text-align: center;  
    font-weight: bold;  
    color: #4CAF50;  
  }  
  
  .scan-in-count {  
    font-size: 24px;  
    text-align: center;  
    font-weight: bold;  
    color: grey;  
  }  
  
  .scan-difference {  
    font-size: 24px;  
    text-align: center;  
    font-weight: bold;  
    color: #ff9900;  
  }  
</style>  
