<?php
function get_time_ago_human($time) {
    $time = time() - $time;
    $time = ($time<1)? 1 : $time;
    $tokens = array (
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );
    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $numberOfUnits = floor($time / $unit);
        return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="<?=url('/static/style/fonts.css')?>">
</head>
<body>
    <style>
        div {
            border: 1px solid silver;
            margin-bottom: .5rem;
            padding: .5rem;
            background: rgba(0, 0, 0, 0.75);
            color: white;
            word-break: break-all;
        }
        div > small {
            color: gray;
        }
        div > p {
            margin: 0;
            margin-top: .5rem;
        }
    </style>

    <?php foreach($messages as $message): ?>
        <div>
            <small><span style="color: yellow"><?=htmlspecialchars($message['nick'])?></span> <?=get_time_ago_human($message['date']) . ' ago'//gmdate("D M j G:i:s Y", $message['date']);?></small>
            <p><?=htmlspecialchars($message['text'])?></p>
        </div>
    <?php endforeach; ?>

    <script>
        let hash = '';
        setInterval(async () => {
            let new_hash = await fetch('sync').then((response) => response.json());
            if (hash == '') {
                hash = new_hash;
            }
            if (new_hash !== hash) {
                    document.location.reload();
            }
        }, 2000);
    </script>
</body>
</html>