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

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

// Ambil tanggal saat ini  
$current_date = date('Y-m-d');

function get_scan_count($db, $type, $location = null)
{
  global $current_date;
  $location_condition = ($location === 'null') ? "loc IS NULL" : "loc = '{$location}'";
  $sql = "SELECT COUNT(DISTINCT resi) as total_scan FROM awb WHERE {$location_condition} AND DATE({$type}) = '{$current_date}'";
  $result = $db->query($sql);
  return ($row = $result->fetch_assoc()) ? $row['total_scan'] : 0;
}

// Mengambil total jumlah scan in dan scan status secara keseluruhan  
$total_scan_in = get_scan_count($db, 'scan_in');
$total_scan_status = get_scan_count($db, 'scan_status');

// Mengambil total jumlah scan in dan scan status untuk Surabaya, Jakarta, Makassar, Bali, dan Semarang  
$locations = ['null' => 'Surabaya', 'jakarta' => 'Jakarta', 'makassar' => 'Makassar', 'bali' => 'Bali', 'semarang' => 'Semarang', 'bandung' => 'Bandung'];
$scan_data = [];
foreach ($locations as $location_key => $location_name) {
  $scan_data[$location_name] = [
    'scan_in' => get_scan_count($db, 'scan_in', $location_key),
    'scan_status' => get_scan_count($db, 'scan_status', $location_key)
  ];
}

// Menghitung persentase progres untuk keseluruhan  
$progress_percentage = ($total_scan_in > 0) ? ($total_scan_status / $total_scan_in) * 100 : 0;
?>

<!-- Container utama -->
<div class="scoreboard-container">
  <div class="scoreboard-title">Real-time Scan Results</div>
  <div id="realtimeResults">

    <!-- Hasil scan keseluruhan -->
    <div class="scan-section">
      <h3>Overall</h3>
      <table class="scoreboard-table">
        <thead>
          <tr>
            <th>Type</th>
            <th>Total AWB</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Scanned In</td>
            <td><?php echo $total_scan_in; ?></td>
          </tr>
          <tr>
            <td>Scan Out</td>
            <td><?php echo $total_scan_status; ?></td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Hasil scan per lokasi -->
    <div class="scan-section">
      <h3>Scan Results per Location</h3>
      <table class="scoreboard-table">
        <thead>
          <tr>
            <th>Location</th>
            <th>Scanned In</th>
            <th>Scan Out</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($scan_data as $location_name => $data): ?>
            <tr>
              <td><?php echo $location_name; ?></td>
              <td><?php echo $data['scan_in']; ?></td>
              <td><?php echo $data['scan_status']; ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <!-- Progress Bar -->
    <div class="progress-container">
      <div class="progress-bar" style="width: <?php echo round($progress_percentage, 2); ?>%;"></div>
    </div>
    <div class="progress-text">Progress: <?php echo round($progress_percentage, 2); ?>%</div>

  </div>
</div>

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

<!-- Script untuk real-time update -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>   -->

<script>
  $(document).ready(function() {
    function fetchRealtimeResults() {
      $.ajax({
        url: 'fetch_realtime_results.php',
        method: 'GET',
        dataType: 'json',
        success: function(data) {
          if (data) {
            // Update scan results for overall data  
            $('.scoreboard-table tbody tr:contains("Scanned In")').first().find('td:last').text(data
              .total_scan_in);
            $('.scoreboard-table tbody tr:contains("Scan Out")').first().find('td:last').text(data
              .total_scan_status);

            // Update location-specific results  
            $.each(data.locations, function(location, values) {
              $('h3:contains("' + location + '")').next('table').find(
                'tbody tr:contains("Scanned In") td:last').text(values.scan_in);
              $('h3:contains("' + location + '")').next('table').find(
                'tbody tr:contains("Scan Out") td:last').text(values.scan_status);
            });

            // Update progress bar  
            $('.progress-bar').css('width', data.progress_percentage + '%').text(data.progress_percentage +
              '%');
            $('.progress-text').text('Progress: ' + parseFloat(data.progress_percentage).toFixed(2) + '%');
          }
        },
        error: function(xhr, status, error) {
          console.error('Error fetching real-time results:', error);
        }
      });
    }
    setInterval(fetchRealtimeResults, 2000); // Update every 2 seconds  
  });
</script>

<!-- CSS Styling -->
<style>
  /* Overall container styling */
  .scoreboard-container {
    max-width: 800px;
    margin: 0 auto;
    text-align: center;
    background: linear-gradient(135deg, #3a3f58, #23293b);
    padding: 30px;
    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: 95%;
    }

    .scoreboard-table th,
    .scoreboard-table td {
      font-size: 14px;
    }
  }
</style>

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