<?php
// --------------------
// Ayarlar
// --------------------
$SMS_API_URL    = 'https://wapi.tr/api/message/send';
$SMS_API_KEY    = getenv('WAPI_API_KEY') ?: 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
$SMS_SECRET_KEY = getenv('WAPI_SECRET_KEY') ?: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$TARGET_PHONES  = getenv('ALERT_PHONES') ?: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';

// --------------------
// Kullanıcı IP bulma
// --------------------
function getUserIP(){
    $keys = [
        'HTTP_CLIENT_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED',
        'HTTP_X_CLUSTER_CLIENT_IP',
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'REMOTE_ADDR'
    ];
    foreach ($keys as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = $_SERVER[$key];
            if (strpos($ip, ',') !== false) {
                $parts = array_map('trim', explode(',', $ip));
                foreach ($parts as $p) {
                    if (filter_var($p, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                        return $p;
                    }
                }
                return $parts[0];
            }
            return $ip;
        }
    }
    return '0.0.0.0';
}

// --------------------
// Küçük cURL GET
// --------------------
function http_get($url, $timeout = 5) {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_CONNECTTIMEOUT => $timeout,
    ]);
    $resp = curl_exec($ch);
    $err  = curl_error($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return [$resp, $code, $err];
}

// --------------------
// IP → Geo + ISP
// --------------------
function geoLookup($ip) {
    if (!filter_var($ip, FILTER_VALIDATE_IP) ||
        filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
        return [false, "Private / invalid IP", "Unknown ISP", null];
    }

    // 1) ip-api.com
    list($resp, $code,) = http_get("http://ip-api.com/json/{$ip}?fields=status,message,country,regionName,city,isp");
    if ($resp && $code === 200) {
        $j = json_decode($resp, true);
        if (!empty($j['status']) && $j['status'] === 'success') {
            $loc = "{$j['city']}, {$j['regionName']}, {$j['country']}";
            $isp = $j['isp'] ?? "Unknown ISP";
            return [true, $loc, $isp, $j];
        }
    }

    // 2) ipapi.co
    list($resp2, $code2,) = http_get("https://ipapi.co/{$ip}/json/");
    if ($resp2 && $code2 === 200) {
        $j2 = json_decode($resp2, true);
        if (!empty($j2) && empty($j2['error'])) {
            $city = $j2['city'] ?? '';
            $region = $j2['region'] ?? '';
            $country = $j2['country_name'] ?? ($j2['country'] ?? '');
            $isp = $j2['org'] ?? "Unknown ISP";
            return [true, trim("$city, $region, $country"), $isp, $j2];
        }
    }

    // 3) ipinfo.io
    $token = getenv('IPINFO_TOKEN') ?: null;
    $url = "https://ipinfo.io/{$ip}/json";
    if ($token) $url .= "?token={$token}";
    list($resp3, $code3,) = http_get($url);
    if ($resp3 && $code3 === 200) {
        $j3 = json_decode($resp3, true);
        if (!empty($j3)) {
            $locParts = [];
            if (!empty($j3['city'])) $locParts[] = $j3['city'];
            if (!empty($j3['region'])) $locParts[] = $j3['region'];
            if (!empty($j3['country'])) $locParts[] = $j3['country'];
            $loc = implode(', ', $locParts);
            $isp = $j3['org'] ?? "Unknown ISP";
            return [true, $loc, $isp, $j3];
        }
    }

    return [false, "Location not found", "Unknown ISP", null];
}

// --------------------
// SMS Gönder
// --------------------
function sendSms($phones, $message, $apiUrl, $media, $apiKey, $secretKey) {
    $curl = curl_init();
    $data = [
        'api_key'      => $apiKey,
        'secret_key'   => $secretKey,
        'phone_number' => $phones,
        'message'      => $message,
        'media'      => $media,
    ];
    $postFields = http_build_query($data);

    curl_setopt_array($curl, [
        CURLOPT_URL            => $apiUrl,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $postFields,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER         => false,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/x-www-form-urlencoded',
            'Accept: application/json',
        ],
        CURLOPT_TIMEOUT => 10,
    ]);

    $response = curl_exec($curl);
    $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $err  = curl_error($curl);
    curl_close($curl);

    return [$response, $code, $err];
}

// --------------------
// MAIN
// --------------------
$userIP = getUserIP();
list($ok, $locationText, $ispText,) = geoLookup($userIP);

// İstanbul saat dilimi
$now = new DateTime('now', new DateTimeZone('Europe/Istanbul'));
$formattedDate = $now->format('d/m/Y H:i');

$message = "Test Dosyası Tetiklendi!\nTarih: {$formattedDate}\nIP: {$userIP}\nLocation: {$locationText}\nISP: {$ispText}";
$media ="https://www.gtcmedya.com/user.png"
// SMS gönder
list($smsResp, $smsCode, $smsErr) = sendSms($TARGET_PHONES, $message, $media, $SMS_API_URL, $SMS_API_KEY, $SMS_SECRET_KEY);

 