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

session_start();
require_once __DIR__ . '/../config/db_remote.php';
require_once __DIR__ . '/../includes/lang.php';

$user = $_SESSION['user'] ?? null;
$role = $user['role'] ?? 'viewer';
if ($role !== 'admin') { die("Not allowed."); }

// Logs
$res = $mysqli->query("SELECT id, level, message, created_at FROM keyence_logs ORDER BY id DESC LIMIT 200");
$logs = [];
if ($res) {
    while ($r = $res->fetch_assoc()) {
        $logs[] = $r;
    }
}

// Status
$res2 = $mysqli->query("SELECT last_heartbeat, last_error FROM keyence_status WHERE id = 1");
$status = $res2 ? $res2->fetch_assoc() : null;

$badge = 'secondary';
$statusLabel = 'OFFLINE';
if ($status && $status['last_heartbeat']) {
    $badge = 'success';
    $statusLabel = 'ONLINE';
    if (!empty($status['last_error'])) {
        $badge = 'danger';
        $statusLabel = 'ERROR';
    }
}

// Last produced box from boxes_produced
$lastBox = null;
$res3 = $mysqli->query("
    SELECT serial, variety, packaging, size, grower, harvested_at, read_at
    FROM boxes_produced
    ORDER BY read_at DESC
    LIMIT 1
");
if ($res3) {
    $lastBox = $res3->fetch_assoc();
}

// Daily production (boxes_produced)
$prodData = [];
$res4 = $mysqli->query("
    SELECT HOUR(read_at) AS h, COUNT(*) AS c
    FROM boxes_produced
    WHERE DATE(read_at) = CURDATE()
    GROUP BY HOUR(read_at)
    ORDER BY h
");
if ($res4) {
    while ($r = $res4->fetch_assoc()) {
        $prodData[] = $r;
    }
}

$prodLabels = [];
$prodCounts = [];
foreach ($prodData as $row) {
    $prodLabels[] = str_pad((string)$row['h'], 2, '0', STR_PAD_LEFT) . ':00';
    $prodCounts[] = (int)$row['c'];
}
$prodLabelsJson = json_encode($prodLabels);
$prodCountsJson = json_encode($prodCounts);
?>
<?php include __DIR__ . '/../includes/header.php'; ?>
<?php include __DIR__ . '/../includes/sidebar.php'; ?>

<div class="container-fluid mt-3">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="mb-0">Keyence Monitor</h3>
    <div>
      <span class="badge bg-<?= $badge ?> me-2"><?= htmlspecialchars($statusLabel) ?></span>
      <?php if ($status && $status['last_heartbeat']): ?>
        <span class="small text-muted">Last heartbeat: <?= htmlspecialchars($status['last_heartbeat']) ?></span>
      <?php endif; ?>
      <?php if ($status && $status['last_error']): ?>
        <div class="small text-danger mt-1"><?= htmlspecialchars($status['last_error']) ?></div>
      <?php endif; ?>
    </div>
  </div>

  <div class="row mb-3">
    <div class="col-lg-6">
      <div class="card shadow-sm">
        <div class="card-header">
          <strong>Ultima lettura Keyence</strong>
        </div>
        <div class="card-body">
          <?php if ($lastBox): ?>
            <dl class="row mb-0">
              <dt class="col-sm-3">Serial</dt>
              <dd class="col-sm-9"><code><?= htmlspecialchars($lastBox['serial']) ?></code></dd>

              <dt class="col-sm-3">Variety</dt>
              <dd class="col-sm-9"><?= htmlspecialchars($lastBox['variety'] ?? '') ?></dd>

              <dt class="col-sm-3">Packaging</dt>
              <dd class="col-sm-9"><?= htmlspecialchars($lastBox['packaging'] ?? '') ?></dd>

              <dt class="col-sm-3">Size</dt>
              <dd class="col-sm-9"><?= htmlspecialchars($lastBox['size'] ?? '') ?></dd>

              <dt class="col-sm-3">Grower</dt>
              <dd class="col-sm-9"><?= htmlspecialchars($lastBox['grower'] ?? '') ?></dd>

              <dt class="col-sm-3">DateTime</dt>
              <dd class="col-sm-9">
                <?php
                  $dt = $lastBox['harvested_at'] ?? $lastBox['read_at'] ?? null;
                  echo $dt ? htmlspecialchars($dt) : '<span class="text-muted">n/a</span>';
                ?>
              </dd>
            </dl>
          <?php else: ?>
            <p class="text-muted mb-0">Nessuna lettura ancora registrata in boxes_produced.</p>
          <?php endif; ?>
        </div>
      </div>
    </div>

    <div class="col-lg-6">
      <div class="card shadow-sm">
        <div class="card-header">
          <strong>Produzione giornaliera (oggi)</strong>
        </div>
        <div class="card-body">
          <?php if (!empty($prodLabels)): ?>
            <canvas id="prodChart" height="160"></canvas>
          <?php else: ?>
            <p class="text-muted mb-0">Nessun dato di produzione per oggi.</p>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>

  <div class="card shadow-sm">
    <div class="card-header d-flex justify-content-between">
      <span>Latest events</span>
      <span class="small text-muted">Auto refresh 5s · showing <?= count($logs) ?> rows</span>
    </div>
    <div class="card-body table-responsive" style="max-height:650px;overflow:auto;">
      <table class="table table-sm table-striped table-hover align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th>ID</th>
            <th>Level</th>
            <th>Message</th>
            <th>Time</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($logs as $log): ?>
          <tr>
            <td><?= (int)$log['id'] ?></td>
            <td>
              <?php if ($log['level'] === 'ERROR'): ?>
                <span class="badge bg-danger">ERROR</span>
              <?php elseif ($log['level'] === 'WARN'): ?>
                <span class="badge bg-warning text-dark">WARN</span>
              <?php else: ?>
                <span class="badge bg-secondary">INFO</span>
              <?php endif; ?>
            </td>
            <td><code class="small"><?= htmlspecialchars($log['message']) ?></code></td>
            <td><?= htmlspecialchars($log['created_at']) ?></td>
          </tr>
          <?php endforeach; ?>
          <?php if (empty($logs)): ?>
          <tr><td colspan="4" class="text-muted">No logs yet.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php if (!empty($prodLabels)): ?>
<script>
(function() {
  const labels = <?= $prodLabelsJson ?>;
  const counts = <?= $prodCountsJson ?>;
  const ctx = document.getElementById('prodChart').getContext('2d');
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: labels,
      datasets: [{
        label: 'Boxes per hour (today)',
        data: counts
      }]
    },
    options: {
      scales: {
        x: { title: { display: true, text: 'Hour' } },
        y: { title: { display: true, text: 'Count' }, beginAtZero: true }
      }
    }
  });
})();
</script>
<?php endif; ?>

