<?php
$page_title = 'Scan Results';
require_once('includes/load.php');
page_require_level(10);

global $db;


$cache_key_resi = 'monitoring:resi';
$data = redisGet($cache_key_resi);
if (!$data) {
  $sql = "SELECT w.warehouse_name, w.zipcode, COUNT(DISTINCT opq.order_sn) AS total_orders, COUNT( DISTINCT CASE WHEN a.scan_status IS NOT NULL THEN opq.order_sn ELSE NULL END ) AS scanned_orders, GROUP_CONCAT( DISTINCT CASE WHEN a.scan_status IS NULL THEN opq.id ELSE NULL END SEPARATOR ',' ) AS order_sn_list, COALESCE(st.session_name, 'Lainnya') AS sesi FROM orders_packing_queue opq JOIN warehouse w ON w.zipcode = opq.zipcode LEFT JOIN awb a ON a.invoice = opq.order_sn JOIN session_times st ON ( ( TIME(opq.created_at) >= st.start_time AND TIME(opq.created_at) < st.end_time ) OR ( st.start_time > st.end_time AND ( TIME(opq.created_at) >= st.start_time OR TIME(opq.created_at) < st.end_time ) ) ) AND ( st.zipcode IS NULL OR st.zipcode = opq.zipcode ) WHERE opq.created_at >= ( CASE WHEN opq.zipcode = 90223 THEN DATE_SUB( DATE(NOW()), INTERVAL 1 DAY ) + INTERVAL 14 HOUR ELSE DATE_SUB( DATE(NOW()), INTERVAL 1 DAY ) + INTERVAL 15 HOUR END ) AND opq.created_at < ( CASE WHEN opq.zipcode = 90223 THEN DATE(NOW()) + INTERVAL 14 HOUR ELSE DATE(NOW()) + INTERVAL 15 HOUR END ) GROUP BY w.warehouse_name, w.zipcode, st.session_name;";

  $result = $db->query($sql);

  // Mengembalikan data dalam bentuk array

  $data = [];
  while ($row = $result->fetch_assoc()) {
    $data[] = $row;
  }
  redisSet($cache_key_resi, $data, 300);
}

// Mengambil header layout  
include_once('layouts/header.php');
?>

<!-- CSS Styling -->
<style>
  /* Progress bar styling - Berbeda warna berdasarkan persen */
  .progress-bar-low {
    background-color: #f0ad4e;
    /* Warna kuning untuk progress rendah */
  }

  .progress-bar-medium {
    background-color: #5bc0de;
    /* Warna biru untuk progress sedang */
  }

  .progress-bar-high {
    background-color: #5cb85c;
    /* Warna hijau untuk progress tinggi */
  }

  /* Loading spinner */
  #loadingSpinner {
    display: none;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    font-size: 30px;
    color: #fff;
  }

  /* Modal styling */
  #orderDetailsModal .modal-body {
    position: relative;
  }

  #loadingSpinnerModal {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    display: none;
  }

  /* Overall container styling */
  .scoreboard-container {
    max-width: 95%;
    margin: 0 auto;
    text-align: center;
    background: linear-gradient(135deg, #3a3f58, #23293b);
    padding: 10px;
    border-radius: 15px;
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
    color: #fff;
    font-family: 'Poppins', sans-serif;
  }

  /* Title Styling */
  .scoreboard-title {
    font-size: 30px;
    margin-bottom: 25px;
    font-weight: 700;
    color: #e0e0e0;
  }

  /* Table styling */
  .scoreboard-table {
    width: 100%;
    margin-bottom: 35px;
    border-collapse: collapse;
    background-color: #2e3b4e;
    border-radius: 10px;
    overflow: hidden;
  }

  .scoreboard-table th,
  .scoreboard-table td {
    padding: 15px;
    border: 1px solid #555;
    text-align: center;
    font-size: 16px;
    color: #f5f5f5;
  }

  .scoreboard-table th {
    background-color: #1f2a3a;
    font-weight: 600;
  }

  .scoreboard-table tbody tr:nth-child(even) {
    background-color: #3f4d63;
  }

  .scoreboard-table tbody tr:hover {
    background-color: #5a6b82;
    transition: background-color 0.3s;
  }

  /* Progress bar container styling */
  .progress-container {
    background-color: #6a7b8c;
    width: 100%;
    height: 25px;
    border-radius: 12px;
    margin: 25px 0;
    box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.3);
  }

  /* Progress bar styling */
  .progress-bar {
    background-color: #5cb85c;
    height: 100%;
    text-align: center;
    line-height: 25px;
    color: white;
    border-radius: 12px;
    transition: width 0.4s ease;
  }

  /* Progress text styling */
  .progress-text {
    margin-top: 12px;
    font-size: 18px;
    font-weight: 500;
    color: #d0d0d0;
  }

  /* Section styling */
  .scan-section {
    margin-bottom: 45px;
  }

  /* Ensure table and container fit inside screen */
  @media (max-width: 768px) {
    .scoreboard-container {
      width: 100%;
    }

    .scoreboard-table th,
    .scoreboard-table td {
      font-size: 14px;
    }
  }


  /* Styling for the scoreboard table */
  .scoreboard-table {
    width: 100%;
    margin-bottom: 35px;
    border-collapse: collapse;
    background-color: #2e3b4e;
    border-radius: 10px;
    overflow: hidden;
  }

  .scoreboard-table th,
  .scoreboard-table td {
    padding: 15px;
    border: 1px solid #555;
    text-align: center;
    font-size: 16px;
    color: #f5f5f5;
  }

  .scoreboard-table th {
    background-color: #1f2a3a;
    font-weight: 600;
  }

  .scoreboard-table tbody tr:nth-child(even) {
    background-color: #3f4d63;
  }


  .scoreboard-table tbody tr:hover {
    background-color: #5a6b82;
    transition: background-color 0.3s;
  }


  .progress-container {
    height: 25px;
    position: relative;
    background-color: #555;
    border-radius: 12px;
    overflow: hidden;
  }

  .progress-container span {
    display: block;
    height: 100%;
  }

  .progress {
    animation: progressBar 1s ease-in-out;
    animation-fill-mode: both;
  }

  @keyframes progressBar {
    0% {
      width: 0;
    }

    100% {
      width: 100%;
    }
  }

  .low-progress {
    background: linear-gradient(90deg, #ff7f50, #ff6347);
  }

  .medium-progress {
    background: linear-gradient(90deg, #ffeb3b, #fbc02d);
  }

  .high-progress {
    background: linear-gradient(90deg, #4caf50, #2e7d32);
  }


  /* styling modal */

  /* Styling for modal background and dialog */
  .modal-content {
    background-color: #1f2a3a;
    /* Dark blue-gray background */
    color: #fff;
    /* White text for contrast */
    border-radius: 10px;
  }

  /* Modal header styling */
  .modal-header {
    background-color: #3f4d63;
    /* Medium gray-blue background for header */
    color: #fff;
    /* White text */
    border-bottom: 2px solid #5a6b82;
    /* Light gray-blue border */
  }

  /* Modal title styling */
  .modal-title {
    font-size: 20px;
    font-weight: 600;
  }

  /* Close button styling */
  .modal-header .close {
    color: #fff;
    /* White close button */
    font-size: 30px;
    background: none;
    border: none;
    opacity: 1;
  }

  /* Modal body styling */
  .modal-body {
    background-color: #3f4d63;
    /* Same medium gray-blue for the body */
    color: #fff;
    padding: 20px;
  }

  /* Table styling */
  .table-bordered {
    background-color: #5a6b82;
    /* Light gray-blue for the table */
    color: #fff;
    border: 1px solid #fff;
  }

  /* Table header styling */
  .table th {
    background-color: #3f4d63;
    /* Darker gray-blue for table headers */
    color: #fff;
  }

  /* Table cell styling */
  .table td {
    background-color: #5a6b82;
    /* Lighter gray-blue for table cells */
    color: #fff;
  }

  /* Modal footer styling */
  .modal-footer {
    background-color: #3f4d63;
    /* Same medium gray-blue for footer */
    border-top: 2px solid #5a6b82;
    /* Light gray-blue border */
  }

  /* Button styling */
  .btn-secondary {
    background-color: #5a6b82;
    /* Same light gray-blue for buttons */
    border: none;
    color: #fff;
    font-weight: 600;
  }

  .btn-secondary:hover {
    background-color: #3f4d63;
    /* Darker shade on hover */
  }
</style>
<div class="scoreboard-container">
  <div class="scoreboard-title">Monitoring Order</div>
  <div id="realtimeResults">

    <div class="scan-section">
      <table class="scoreboard-table">
        <thead>
          <tr>
            <th>Warehouse</th>
            <th>Total Order</th>
            <th>Total Order Terproses</th>
            <th>Sesi</th>
            <th>Progress</th>
            <th>Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($data as $row): ?>
            <?php
            // Calculate progress percentage
            $progress_percentage = ($row['scanned_orders'] > 0) ? ($row['scanned_orders'] / $row['total_orders']) * 100 : 0;
            if ($progress_percentage < 40) {
              $progress_class = "low-progress";
            } elseif ($progress_percentage >= 40 && $progress_percentage < 80) {
              $progress_class = "medium-progress";
            } else {
              $progress_class = "high-progress";
            }
            ?>
            <tr>
              <td><?php echo htmlspecialchars($row['warehouse_name']); ?></td>
              <td><?php echo htmlspecialchars($row['total_orders']); ?></td>
              <td><?php echo htmlspecialchars($row['scanned_orders']); ?></td>
              <td><?php echo htmlspecialchars($row['sesi']); ?></td>
              <td>
                <div class="progress-container">
                  <span style="width:<?php echo round($progress_percentage, 2); ?>%;"><span
                      class="progress <?php echo $progress_class; ?>"></span></span>
                </div>
    </div>
    <div class="progress-text">Progress: <?php echo round($progress_percentage, 2); ?>%</div>
    </td>
    <td>
      <a href="#" data-toggle="modal" data-target="#orderDetailsModal"
        onclick="showOrderDetails('<?php echo htmlspecialchars($row['order_sn_list'], ENT_QUOTES); ?>','<?php echo htmlspecialchars($row['zipcode'], ENT_QUOTES); ?>');"
        class="btn btn-success btn-sm high-progress">Detail</a>
    </td>
    </tr>
  <?php endforeach; ?>
  </tbody>
  </table>
  </div>
</div>
</div>

<!-- Modal -->
<div class="modal fade" id="orderDetailsModal" tabindex="-1" aria-labelledby="orderDetailsModalLabel"
  aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="orderDetailsModalLabel">Order Details</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"
          style="right: 15px;top: 15px;position:absolute">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <button id="generatePackingListBtn" class="btn btn-primary">Generate Packing List</button>
        <input type="hidden" name="zipcode" id="zipcode">
        <table class="table table-bordered">
          <thead>
            <tr>
              <th class="text-center" style="width: 50px;">
                <input type="checkbox" id="checkAll">
              </th>
              <th>Created At</th>
              <th>Invoice</th>
              <th>Resi</th>
              <th>Scan In</th>
              <th>Scan Out</th>
              <th>SKU</th>
            </tr>
          </thead>
          <tbody id="orderDetailsTableBody">
          </tbody>
        </table>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>


<?php include_once('layouts/footer.php'); ?>
<script>
  function generatePackingList() {
    const selectedInvoices = [];
    $('.order-checkbox:checked').each(function() {
      selectedInvoices.push($(this).data('order_sn'));
    });

    // Ensure at least one order is selected
    if (selectedInvoices.length === 0) {
      alert('Please select at least one order to generate the packing list.');
      return;
    }

    // Collect the zipcode
    const zipcode = $('#zipcode').val();
    // Create a form and set method to POST
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = 'generate_packing_list.php'; // Replace with your actual endpoint

    // Create hidden inputs for order_sn and zipcode
    const orderSnInput = document.createElement('input');
    orderSnInput.type = 'hidden';
    orderSnInput.name = 'order';
    orderSnInput.value = selectedInvoices.join(','); // Join invoices with commas

    const zipcodeInput = document.createElement('input');
    zipcodeInput.type = 'hidden';
    zipcodeInput.name = 'zipcode';
    zipcodeInput.value = zipcode;

    // Append the inputs to the form
    form.appendChild(orderSnInput);
    form.appendChild(zipcodeInput);

    // Append the form to the body (but it won't be visible)
    document.body.appendChild(form);

    // Submit the form and open the result in a new tab
    form.target = '_blank'; // Open in a new tab
    form.submit();

    // Clean up by removing the form after submission
    document.body.removeChild(form);
  }

  // Add an event listener for the "Generate Packing List" button
  $('#generatePackingListBtn').on('click', function() {
    generatePackingList();
  });

  // Check/uncheck all checkboxes when the "Select All" checkbox is clicked
  $('#checkAll').on('change', function() {
    $('.order-checkbox').prop('checked', $(this).prop('checked'));
  });

  function showOrderDetails(orderSnList, zipcode) {
    $('#orderDetailsTableBody').html('');
    if (orderSnList == '') {
      alert('Tidak Ada List Order Yang Belum Terproses');
      return;
    }
    $('#zipcode').val(zipcode);
    $.ajax({
      url: 'api_monitoring_detail.php',
      type: 'POST',
      data: {
        order_sn_list: orderSnList
      },
      success: function(response) {
        $('#loadingSpinnerModal').hide();

        const data = JSON.parse(response);
        if (data.length > 0) {
          data.forEach(row => {
            $('#orderDetailsTableBody').append(
              `<tr>
              <td><input type="checkbox" class="order-checkbox" data-order_sn="${row.invoice}"></td>
              <td>${row.created_at}</td>
              <td>${row.invoice}</td>
              <td>${row.resi}</td>
              <td>${row.scan_in}</td>
              <td>${row.scan_status}</td>
              <td>${row.sku}</td>
            </tr>`
            );
          });
        } else {
          $('#orderDetailsTableBody').append('<tr><td colspan="4">No data found</td></tr>');
        }
      },
      error: function() {
        alert('Failed to fetch order details. Please try again.');
        $('#loadingSpinnerModal').hide();
      }
    });
  }
</script>


<!-- Link Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">