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

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

$user = $_SESSION['user'] ?? null;
$role = $user['role'] ?? 'viewer';
if ($role !== 'admin') {
    die("You do not have permission to view this page.");
}

// Load last DB logs related to Keyence listener (connection + barcodes)
$res = $mysqli->query("
    SELECT id, level, message, created_at
    FROM keyence_logs
    WHERE message LIKE 'BARCODE%%'
       OR message LIKE 'Connection from%%'
       OR message LIKE 'Starting PHP TCP listener%%'
    ORDER BY id DESC
    LIMIT 200
");
$dbLogs = [];
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $dbLogs[] = $row;
    }
}

// Load tail of file log
$logFile = __DIR__ . '/../keyence_service/keyence_listener.log';
$fileLines = [];
if (is_file($logFile)) {
    $all = file($logFile, FILE_IGNORE_NEW_LINES);
    $fileLines = array_slice($all, -200);
}
?>
<?php include('../includes/header.php'); ?>
<?php include('../includes/sidebar.php'); ?>

<div class="container-fluid mt-3">
  <div class="row">
    <div class="col-lg-6">
      <div class="card shadow-sm mb-3">
        <div class="card-header">
          Listener DB Logs (last <?= count($dbLogs) ?>)
        </div>
        <div class="card-body table-responsive">
          <table class="table table-sm table-striped align-middle mb-0">
            <thead>
              <tr>
                <th>ID</th>
                <th>Level</th>
                <th>Message</th>
                <th>Time</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($dbLogs as $log): ?>
              <tr>
                <td><?= (int)$log['id'] ?></td>
                <td><span class="badge bg-<?=
                    $log['level']==='ERROR' ? 'danger' :
                    ($log['level']==='WARN' ? 'warning' : 'secondary')
                ?>"><?= htmlspecialchars($log['level']) ?></span></td>
                <td><?= htmlspecialchars($log['message']) ?></td>
                <td><?= htmlspecialchars($log['created_at']) ?></td>
              </tr>
              <?php endforeach; ?>
              <?php if (empty($dbLogs)): ?>
              <tr><td colspan="4" class="text-muted">No DB logs yet.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <div class="col-lg-6">
      <div class="card shadow-sm mb-3">
        <div class="card-header">
          Listener File Log Tail (last <?= count($fileLines) ?> lines)
        </div>
        <div class="card-body">
          <?php if ($fileLines): ?>
            <pre class="small mb-0"><?php echo htmlspecialchars(implode("\n", $fileLines)); ?></pre>
          <?php else: ?>
            <p class="text-muted mb-0">Log file not found or empty.</p>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>

