<?php

if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

if (!isset($_SESSION['username'])) {
  header('Location: /local/login.php');
  exit;
}

// header('Content-Type: text/plain');

$data = file_get_contents("$_SERVER[DOCUMENT_ROOT]/storage/messages.table");
// echo $data;
$rows = explode(PHP_EOL, $data);
// var_dump($rows);
$headers = [];
$entries = [];

foreach ($rows as $idx => $row) {
  if (!empty($row)) {
    if ($idx === 0) {
      preg_match_all('/<col>(.*?)<\/col>/s', $row, $matches);
      $r = $matches[1][0];
      $headers = explode(',', $r);
    }
    else {
      $r = explode('<|>', $row);
      $entries[] = $r;
    }
  }
}

?>

<html lang="en">
<? include 'parts/head.php' ?>

<body>
  <table>
    <thead>
      <tr>
        <? foreach ($headers as $h) { ?>
          <th><? echo $h ?></th>
        <? } ?>
      </tr>
    </thead>
    <tbody>
      <? foreach ($entries as $entry) { ?>
        <tr>
          <? foreach ($entry as $col) { ?>
            <td><? echo $col ?></td>
          <? } ?>
        </tr>
      <? } ?>
    </tbody>
  </table>
</body>

</html>