<?php
// Simple page view counter for BBTools website
// Stores counts in SQLite database (counter.db)

// Ignore bots
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$bot_patterns = ['bot', 'spider', 'crawl', 'slurp', 'baidu', 'yandex'];
foreach ($bot_patterns as $bot) {
    if (stripos($user_agent, $bot) !== false) {
        exit(''); // Silent exit for bots
    }
}

// Get page name from request
$page = $_GET['page'] ?? 'unknown';
$page = preg_replace('/[^a-zA-Z0-9_-]/', '', $page); // Sanitize

// Open/create SQLite database
$db = new SQLite3(__DIR__ . '/counter.db');

// Create table if it doesn't exist
$db->exec('CREATE TABLE IF NOT EXISTS page_views (
    page TEXT PRIMARY KEY,
    count INTEGER DEFAULT 0,
    last_viewed TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)');

// Increment counter for this page
$db->exec("INSERT INTO page_views (page, count) VALUES ('$page', 1)
           ON CONFLICT(page) DO UPDATE SET 
           count = count + 1,
           last_viewed = CURRENT_TIMESTAMP");

// Also track daily stats
$db->exec('CREATE TABLE IF NOT EXISTS daily_views (
    date DATE,
    page TEXT,
    count INTEGER DEFAULT 0,
    PRIMARY KEY (date, page)
)');

$today = date('Y-m-d');
$db->exec("INSERT INTO daily_views (date, page, count) VALUES ('$today', '$page', 1)
           ON CONFLICT(date, page) DO UPDATE SET count = count + 1");

$db->close();

// Return a 1x1 transparent pixel
header('Content-Type: image/gif');
echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
?>