<?php
session_start();

$validUsername = "us1";
$validPassword = "pwd1";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    if ($username === $validUsername && $password === $validPassword) {
        $_SESSION['user'] = $username; 
        header("Location: " . $_SERVER['PHP_SELF']); 
        exit;
    } else {
        $error = "Invalid username or password.";
    }
}

if (isset($_SESSION['user'])) {
    $directory = "places";

    try {
        if (!is_dir($directory)) {
            throw new Exception("Directory does not exist.");
        }

        $files = scandir($directory);
        $rows = []; // Array to store table rows with their intervals

        foreach ($files as $file) {
            $filePath = $directory . "/" . $file;

            if ($file !== "." && $file !== ".." && is_file($filePath)) {
                $content = file_get_contents($filePath);
                $parts = explode("~", $content);

                if (count($parts) === 3) {
                    [$uid, $status, $time] = $parts;

                    $currentDateTime = new DateTime();
                    $fileDateTime = new DateTime(trim($time));
                    $interval = $currentDateTime->getTimestamp() - $fileDateTime->getTimestamp();

                    // Add the row data to the array
                    $rows[] = [
                        'uid' => $uid,
                        'status' => $status,
                        'interval' => $interval,
                    ];
                }
            }
        }

        // Sort rows by interval (ascending)
        usort($rows, function ($a, $b) {
            return $a['interval'] <=> $b['interval'];
        });

        // Display the table
        echo "<h2>Welcome, " . htmlspecialchars($_SESSION['user']) . "!</h2>";
        echo "<a href='logout.php' style='margin-right:10px'>Logout</a>"; 
        echo "<table border='1' cellpadding='5' cellspacing='0'>";
        echo "<tr><th>ID</th><th>PLACE</th><th>TIME</th></tr>";

        foreach ($rows as $row) {
            echo "<tr>";
            echo "<td>" . htmlspecialchars($row['uid']) . "</td>";
            echo "<td>" . htmlspecialchars($row['status']) . "</td>";

            if ($row['interval'] < 10) {
                echo "<td style='color:green'>" . htmlspecialchars($row['interval']) . " seconds</td>";
            } else {
                echo "<td style='color:red'>" . htmlspecialchars($row['interval']) . " seconds</td>";
            }
            echo "</tr>";
        }

        echo "</table>";
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
} else {
    ?>
    <h2>Login</h2>
    <?php if (!empty($error)) echo "<p style='color: red;'>$error</p>"; ?>
    <form method="POST" action="">
        <label for="username">Username:</label>
        <input type="text" name="username" id="username" required>
        <br><br>
        <label for="password">Password:</label>
        <input type="password" name="password" id="password" required>
        <br><br>
        <button type="submit">Login</button>
    </form>
    <?php
}
?>
