<?php
/**
 * Siro Unified Redirect Gateway (One-Click Redirect for non-Syrian countries)
 * URL Format: https://siromove.com/invite.php?code=REF_CODE&app=rider|driver
 */

// 1. Core Config & Links
$config = [
    'rider' => [
        'ios_store' => 'https://apps.apple.com/st/app/siro-rider/id6748075179',
        'android_store' => 'https://play.google.com/store/apps/details?id=com.Siro.siro'
    ],
    'driver' => [
        'ios_store' => 'https://apps.apple.com/st/app/siro-driver/id6482995159',
        'android_store' => 'https://play.google.com/store/apps/details?id=com.siro_driver'
    ]
];

$code = htmlspecialchars($_GET['code'] ?? '', ENT_QUOTES, 'UTF-8');
$appType = ($_GET['app'] ?? 'rider') === 'driver' ? 'driver' : 'rider';
$appConfig = $config[$appType];

// 2. Helper Functions
function getVisitorCountry() {
    if (!empty($_SERVER['HTTP_CF_IPCOUNTRY'])) {
        return strtoupper($_SERVER['HTTP_CF_IPCOUNTRY']);
    }
    
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    if (!empty($_SESSION['visitor_country'])) {
        return $_SESSION['visitor_country'];
    }
    
    $ip = $_SERVER['REMOTE_ADDR'];
    if ($ip === '127.0.0.1' || $ip === '::1' || filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
        return 'JO'; // Default Jordan
    }
    
    try {
        $ctx = stream_context_create(['http' => ['timeout' => 2]]);
        $apiResponse = @file_get_contents("http://ip-api.com/json/{$ip}", false, $ctx);
        if ($apiResponse) {
            $data = json_decode($apiResponse, true);
            if (!empty($data['countryCode'])) {
                $_SESSION['visitor_country'] = strtoupper($data['countryCode']);
                return $_SESSION['visitor_country'];
            }
        }
    } catch (Exception $e) {
        // Fallback
    }
    return 'JO';
}

function getDeviceOS() {
    $userAgent = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
    if (strpos($userAgent, 'iphone') !== false || strpos($userAgent, 'ipad') !== false || strpos($userAgent, 'ipod') !== false) {
        return 'ios';
    }
    if (strpos($userAgent, 'android') !== false) {
        return 'android';
    }
    return 'desktop';
}

$country = getVisitorCountry();
$os = getDeviceOS();

// 3. Fallback Handoff for Syrian Users
if ($country === 'SY') {
    header("Location: https://siromove.com/inviteSyria.php?code=" . urlencode($code) . "&app=" . urlencode($appType));
    exit;
}

// 4. One-Click Instant Redirection (Jordan / Egypt / others)
if ($os === 'ios') {
    header("Location: " . $appConfig['ios_store']);
    exit;
} else {
    // Android or Desktop default
    header("Location: " . $appConfig['android_store']);
    exit;
}
?>
