<?php
// Autoload dependencies installed via Composer
require '/home/juraga22/krlawfirm.co/vendor/autoload.php'; 

use GeoIp2\Database\Reader;
use Detection\MobileDetect;

try {

    // Set the default timezone to Jakarta
    date_default_timezone_set('Asia/Jakarta');

    // Get the current time in Jakarta timezone
    $visitTime = date('Y-m-d H:i:s');

    // GeoLite database paths
    $databaseFile1 = '/home/juraga22/krlawfirm.co/GeoLite2-ASN.mmdb'; 
    $reader1 = new Reader($databaseFile1);

    $databaseFile = '/home/juraga22/krlawfirm.co/GeoLite2-City.mmdb';  
    $reader = new Reader($databaseFile);

    // Mobile Detect instance
    $detect = new MobileDetect;

    // Get the IP address of the visitor
    $ipAddress = $_SERVER['REMOTE_ADDR'];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipAddress = trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ipAddress = $_SERVER['HTTP_CLIENT_IP'];
    }

    // Validate the IP address format
    if (!filter_var($ipAddress, FILTER_VALIDATE_IP)) {
        throw new Exception("Invalid IP address format: $ipAddress");
    }

    // Query the GeoLite2-ASN database for ASN info
    $record = $reader1->asn($ipAddress);
    $asn = $record->autonomousSystemNumber;
    $organization = $record->autonomousSystemOrganization;

    // Detect the device type
    $device = 'Desktop';
    if ($detect->isMobile()) {
        $device = 'Mobile';
    } elseif ($detect->isTablet()) {
        $device = 'Tablet';
    }

    // Detect OS and browser
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    $os = 'Unknown OS';
    $browser = 'Unknown Browser';

    if (preg_match('/linux/i', $userAgent)) {
        $os = 'Linux';
    } elseif (preg_match('/macintosh|mac os x/i', $userAgent)) {
        $os = 'Mac';
    } elseif (preg_match('/windows|win32/i', $userAgent)) {
        $os = 'Windows';
    }

    if (preg_match('/MSIE/i', $userAgent) && !preg_match('/Opera/i', $userAgent)) {
        $browser = 'Internet Explorer';
    } elseif (preg_match('/Firefox/i', $userAgent)) {
        $browser = 'Firefox';
    } elseif (preg_match('/Chrome/i', $userAgent)) {
        $browser = 'Chrome';
    } elseif (preg_match('/Safari/i', $userAgent)) {
        $browser = 'Safari';
    } elseif (preg_match('/Opera/i', $userAgent)) {
        $browser = 'Opera';
    }

    // Get the referer (if available)
    $referer = $_SERVER['HTTP_REFERER'] ?? 'Direct';

    // Get language preference
    //$language = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) : 'Unknown';
	$language = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) : 'Unknown';

    // Get the accessed URL
    $accessedUrl = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

    $parsedUrl = parse_url($accessedUrl);

    // Initialize the $queryParams array
    $queryParams = [];


    // Query the GeoLite2-City database for country and city info
    $record = $reader->city($ipAddress);
    $country = $record->country->name;
    $city = $record->city->name ?: 'Unknown';

    // Check conditions and insert into database accordingly
    $validTimeZones = ['Asia/Jakarta', 'Asia/Makassar', 'Asia/Jayapura', 'Asia/Pontianak'];
    $vpn = ['google'];
    $isVPN = false;
    foreach ($vpn as $vpnString) {
    if (stripos($organization, $vpnString) !== false) {
        $isVPN = true;
        break;
    }
    }
$score = 0;

if ($country === 'Indonesia') $score++;
if (in_array($record->location->timeZone, $validTimeZones)) $score++;
if ($detect->isMobile()) $score++;


$isGoogle = stripos($organization, 'google') !== false;

// Lolos jika:
$passed = ($score >= 3 || $isGoogle) ? 'yes' : 'no';

    // $passed = ($country === 'Indonesia'  &&
 //          $detect->isMobile()) ? 'yes' : 'no';
    //$passed = ($country === 'Indonesia' && $record->location->timeZone === 'Asia/Jakarta' && $detect->isMobile() && $language !== 'unknown') ? 'yes' : 'no';



} catch (Exception $e) {
    // Log the error instead of showing it
    error_log($e->getMessage(), 3, '/home/juraga22/krlawfirm.co/php_errors.log');
    echo "An error occurred. Please try again later.";
}
?>
