<?php
require_once __DIR__ . '/../config/user_functions.php';

session_start();
if (!isset($_SESSION['user'])) { header('Location: /smproduce/auth/login.php'); exit; }
require_once __DIR__ . '/../config/db_remote.php';
?>
<?php include('../includes/header.php'); ?>
<?php include('../includes/sidebar.php'); ?>

<div class="container-fluid">
  <div class="d-flex justify-content-between align-items-center mt-2">
    <h3>📦 Boxes Produced</h3>
    <div>
      <span id="keyence-status-dot" class="badge bg-danger">Keyence OFF</span>
      <small id="keyence-last-ts" class="text-muted ms-2">Last: -</small>
    </div>
  </div>

  <div class="row mt-3 g-3">
    <div class="col-md-3">
      <div class="card p-3">
        <h6>Today</h6>
        <?php
          $today = $mysqli->query("SELECT COUNT(*) AS c FROM boxes_produced WHERE DATE(read_at)=CURDATE()")->fetch_assoc();
        ?>
        <div class="display-6"><?= (int)$today['c'] ?></div>
      </div>
    </div>

    <div class="col-md-3">
      <div class="card p-3">
        <h6>Last hour</h6>
        <?php
          $lastHour = $mysqli->query("SELECT COUNT(*) AS c FROM boxes_produced WHERE read_at >= NOW() - INTERVAL 1 HOUR")->fetch_assoc();
        ?>
        <div class="display-6"><?= (int)$lastHour['c'] ?></div>
      </div>
    </div>
  </div>

  <hr>

  <table id="boxesTable" class="table table-striped table-hover">
    <thead>
      <tr>
        <th>ID</th>
        <th>Serial</th>
        <th>Variety</th>
        <th>Grower</th>
        <th>Lot</th>
        <th>Harvested at</th>
        <th>Line</th>
        <th>Read at</th>
      </tr>
    </thead>
  </table>
</div>

<audio id="beep-audio">
  <source src="/smproduce/assets/audio/beep.mp3" type="audio/mpeg">
</audio>

<script>
let lastMaxId = 0;

$(document).ready(function(){
  const table = $('#boxesTable').DataTable({
    ajax: '/smproduce/pages/boxes_produced_api.php',
    columns: [
      { data: 'id' },
      { data: 'serial' },
      { data: 'variety' },
      { data: 'grower' },
      { data: 'lot' },
      { data: 'harvested_at' },
      { data: 'production_line' },
      { data: 'read_at' }
    ],
    pageLength: 25,
    order: [[0, 'desc']]
  });

  function refresh() {
    $.getJSON('/smproduce/pages/boxes_produced_api.php', function(resp){
      table.clear().rows.add(resp.data).draw(false);

      if (resp.data.length > 0) {
        const maxId = resp.data[0].id;
        if (maxId > lastMaxId) {
          lastMaxId = maxId;

          const beep = document.getElementById('beep-audio');
          if (beep) { beep.play().catch(()=>{}); }

          $('#keyence-status-dot').removeClass('bg-danger').addClass('bg-success').text('Keyence OK');
          $('#keyence-last-ts').text('Last: ' + resp.data[0].read_at);

          setTimeout(() => {
            $('#keyence-status-dot').removeClass('bg-success').addClass('bg-danger').text('Keyence idle');
          }, 10000);
        }
      }
    });
  }

  refresh();
  setInterval(refresh, 5000);
});
</script>

