<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

$PANEL_PASS = "1234"; // bunu değiştir

try {
  require __DIR__ . "/db.php";
} catch (Throwable $e) {
  echo "<pre>DB INCLUDE ERROR:\n" . htmlspecialchars($e->getMessage()) . "</pre>";
  exit;
}

if (isset($_POST["pass"])) {
  if ($_POST["pass"] === $PANEL_PASS) $_SESSION["ok"] = 1;
}

if (!($_SESSION["ok"] ?? 0)) {
  ?>
  <!doctype html>
  <html><head><meta charset="utf-8"><title>Login</title></head>
  <body style="font-family:Arial;padding:30px">
    <h2>RiseWatcher Panel Login</h2>
    <form method="post">
      <input name="pass" type="password" autofocus>
      <button>Giriş</button>
    </form>
  </body></html>
  <?php
  exit;
}

$hours = intval($_GET["hours"] ?? 24);
if ($hours <= 0) $hours = 24;
if ($hours > 24*30) $hours = 24*30;

$stmt = $conn->prepare("
  SELECT id, pc, ev_type, ev_code, val_int, val_text, payload_json, created_at
  FROM rw_events
  WHERE created_at >= (NOW() - INTERVAL ? HOUR)
  ORDER BY id DESC
  LIMIT 200
");
$stmt->bind_param("i", $hours);
$stmt->execute();
$res = $stmt->get_result();

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, "UTF-8"); }
?>
<!doctype html>
<html>
<head><meta charset="utf-8"><title>RiseWatcher Logs</title></head>
<body style="font-family:Arial;padding:20px">
  <h2>RiseWatcher Logs (son <?=h($hours)?> saat)</h2>
  <form method="get">
    <label>Son kaç saat:</label>
    <input name="hours" type="number" value="<?=h($hours)?>" min="1" max="<?=h(24*30)?>">
    <button>Getir</button>
  </form>
  <hr>
  <table border="1" cellpadding="6" cellspacing="0">
    <tr>
      <th>Zaman</th><th>PC</th><th>Type</th><th>Code</th><th>Val</th><th>Text</th>
    </tr>
    <?php while($row = $res->fetch_assoc()): ?>
      <tr>
        <td><?=h($row["created_at"])?></td>
        <td><?=h($row["pc"])?></td>
        <td><?=h($row["ev_type"])?></td>
        <td><?=h($row["ev_code"])?></td>
        <td><?=h($row["val_int"])?></td>
        <td><?=h($row["val_text"])?></td>
      </tr>
    <?php endwhile; ?>
  </table>
</body>
</html>
