<?php

use Jaybizzle\CrawlerDetect\CrawlerDetect;
use Vectorface\Whip\Whip;

require_once './config/config.php';

$CrawlerDetect = new CrawlerDetect;

// Check the user agent of the current 'visitor'
if ($CrawlerDetect->isCrawler()) {
    // true if crawler user agent detected
    http_response_code(403);
    die();
}

if (!isset($_GET['key']) || isset($_GET['key']) && $_GET['key'] != KEY) {
    http_response_code(403);
    die();
}

$whip = new Whip();
$clientAddress = $whip->getValidIpAddress();

// Assuming SQLite database file 'visitors.db' and a table 'visitors'
// Table 'visitors' structure should include a column for 'is_active' (INTEGER)

// Open a database connection
$db = new SQLiteDB(BASE_PATH . '/data/db/visitors.db');

// Create the 'visitors' table if it doesn't exist
$db->exec("CREATE TABLE IF NOT EXISTS visitors (
    session_id TEXT PRIMARY KEY,
    url TEXT,
    redirect INTEGER,
    is_active INTEGER,
    last_visit INTEGER,
    ip_address TEXT,
    country_code TEXT,
    country_name TEXT,
    region_name TEXT,
    city_name TEXT,
    zip_code TEXT,
    user_agent TEXT,
    created_at TEXT
)");

$currentTime = time();

// Update the is_active status for each visitor
$updateStmt = $db->prepare("UPDATE visitors SET is_active = CASE WHEN :current_time - last_visit <= 3 THEN 1 ELSE 0 END");
$updateStmt->bindValue(':current_time', $currentTime, SQLITE3_INTEGER);
$updateStmt->execute();

$perPage = 15; // Number of results to show per page
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1; // Get the current page number
$filterDate = isset($_GET['date']) ? $_GET['date'] : null; // Get the filter date

$start = ($page - 1) * $perPage; // Calculate the offset

$sql = "SELECT * FROM visitors";
$sqlCount = "SELECT COUNT(*) as count FROM visitors"; // For counting total records

// Apply date filter if set
if ($filterDate !== null) {
    $sql .= " WHERE DATE(created_at) = :filterDate";
    $sqlCount .= " WHERE DATE(created_at) = :filterDate";
}

$sql .= " ORDER BY is_active DESC, last_visit DESC, created_at DESC";

// Add LIMIT and OFFSET directly in the query string
$sql .= " LIMIT " . $perPage . " OFFSET " . $start;

$selectStmt = $db->prepare($sql);
if ($filterDate !== null) {
    $selectStmt->bindValue(':filterDate', $filterDate, SQLITE3_TEXT);
}
$result = $selectStmt->execute();
$tableData = [];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    $tableData[] = $row;
}

$countStmt = $db->prepare($sqlCount);
if ($filterDate !== null) {
    $countStmt->bindValue(':filterDate', $filterDate, SQLITE3_TEXT);
}
$countResult = $countStmt->execute();
$countRow = $countResult->fetchArray();
$totalRecords = $countRow['count'];
$totalPages = ceil($totalRecords / $perPage);

// Close the database connection
$db->close();

// Display visitor count for today or filtered date
$today = date('Y-m-d');
$today_visitors = $filterDate === null || $filterDate === $today ? $totalRecords : 0;
$visitor_counter_string = $filterDate === null ? "Today's visitors: $today_visitors" : "Visitors on $filterDate: $totalRecords";

$currentDateTime = date('Y-m-d H:i:s');
$paginationQueryString = $filterDate ? "?date=" . htmlspecialchars($filterDate) . "&page=" : "?page=";
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Visitor Data</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="#">Admin Panel</a>
            <div class="navbar-nav">
                <a class="nav-link active" href="visitors.php?key=<?php echo KEY; ?>">Visitors</a>
                <a class="nav-link" href="blacklist.php?key=<?php echo KEY; ?>">Blacklist</a>
                <a class="nav-link" href="status.php?key=<?php echo KEY; ?>">Status</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <h1 class="mb-4">Visitor Data</h1>

        <div class="row mb-4">
            <div class="col-md-6">
                <form method="GET" class="d-flex gap-2">
                    <input type="date" id="date" name="date" class="form-control" value="<?php echo htmlspecialchars($filterDate); ?>">
                    <button type="submit" class="btn btn-primary">Filter</button>
                    <?php if ($filterDate): ?>
                        <a href="visitors.php?key=<?php echo KEY; ?>&" class="btn btn-secondary">Clear</a>
                    <?php endif; ?>
                </form>
            </div>
        </div>

        <div class="row mb-3">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h6 class="card-subtitle mb-2 text-muted">Current date and time</h6>
                        <p class="card-text"><?php echo $currentDateTime; ?></p>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h6 class="card-subtitle mb-2 text-muted">Visitor Count</h6>
                        <p class="card-text"><?php echo $visitor_counter_string; ?></p>
                    </div>
                </div>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead class="table-dark">
                            <tr>
                                <th>Session ID</th>
                                <th>IP Address</th>
                                <th>Country</th>
                                <th>Region</th>
                                <th>City</th>
                                <th>Zip</th>
                                <th>User Agent</th>
                                <th>Status</th>
                                <th>Date</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($tableData as $row) : ?>
                                <tr>
                                    <td><code><?php echo substr($row['session_id'], 0, 8); ?>...</code></td>
                                    <td><strong><?php echo $row['ip_address']; ?></strong></td>
                                    <td>
                                        <?php echo country2flag($row['country_code']) . ' ' . $row['country_name']; ?>
                                    </td>
                                    <td><?php echo $row['region_name']; ?></td>
                                    <td><?php echo $row['city_name']; ?></td>
                                    <td><?php echo $row['zip_code']; ?></td>
                                    <td title="<?php echo htmlspecialchars($row['user_agent']); ?>">
                                        <?php echo substr($row['user_agent'], 0, 30) . '...'; ?>
                                    </td>
                                    <td>
                                        <?php if ($row['is_active']): ?>
                                            <span class="badge bg-success">Online</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger">Offline</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo $row['created_at']; ?></td>
                                    <td>
                                        <a href="blacklist.php?key=<?php echo KEY; ?>&ip_address=<?php echo urlencode($row['ip_address']); ?>"
                                            class="btn btn-danger btn-sm" target="_blank">Block IP</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($totalPages > 1) : ?>
                    <nav aria-label="Page navigation">
                        <ul class="pagination justify-content-center">
                            <?php for ($i = 1; $i <= $totalPages; $i++) : ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="<?php echo $paginationQueryString . $i; ?>"><?php echo $i; ?></a>
                                </li>
                            <?php endfor; ?>
                        </ul>
                    </nav>
                <?php endif; ?>
        </div>

        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>