<?php
include 'includes/header.php';
include 'includes/sidebar.php';
require 'includes/db_connect.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['mark_seen'])) {
    $visitor_id = (int)$_POST['visitor_id'];

    $update = $conn->prepare("UPDATE visitors SET status = 'Attended' WHERE id = ?");
    $update->bind_param("i", $visitor_id);
    if ($update->execute()) {
        $message = "<div class='alert alert-success'>Visitor marked as Attended.</div>";
    } else {
        $message = "<div class='alert alert-danger'>Failed to update visitor status.</div>";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Visitors Log</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container mt-5">
    <h3 class="mb-4">Visitors Log</h3>
    <?php if (isset($message)) echo $message; ?>

    <table class="table table-bordered table-striped bg-white">
        <thead class="table-dark">
            <tr>
                <th>#</th>
                <th>Full Name</th>
                <th>Reason</th>
                <th>Status</th>
                <th>Date Registered</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $query = $conn->query("SELECT * FROM visitors ORDER BY reg_date DESC");
            $count = 1;
            while ($row = $query->fetch_assoc()) {
                echo "<tr>";
                echo "<td>{$count}</td>";
                echo "<td>{$row['fullname']}</td>";
                echo "<td>{$row['reason']}</td>";
                echo "<td><span class='badge bg-" . ($row['status'] === 'Attended' ? 'success' : 'warning') . "'>{$row['status']}</span></td>";
                echo "<td>{$row['reg_date']}</td>";
                echo "<td>";
                if ($row['status'] !== 'Attended') {
                    echo "<form method='post' class='d-inline'>
                            <input type='hidden' name='visitor_id' value='{$row['id']}'>
                            <button type='submit' name='mark_seen' class='btn btn-sm btn-success'>Seen</button>
                          </form>";
                } else {
                    echo "<span class='text-muted'>—</span>";
                }
                echo "</td>";
                echo "</tr>";
                $count++;
            }
            ?>
        </tbody>
    </table>
</div>

</body>
</html>
