<?php
/**
 * go-link.php - KISA LİNK REDIRECT SİSTEMİ
 * 
 * Kullanım: domain.com/code → Laravel API'ye gönder → Hedef URL'ye redirect
 */

// ============================================
// 1. ERROR REPORTING
// ============================================
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');

// DEBUG MODE (production'da false yap)
define('DEBUG_MODE', true);
$debug_log = __DIR__ . '/debug.log';

function debug($message) {
    if (DEBUG_MODE) {
        file_put_contents($GLOBALS['debug_log'], "[" . date('Y-m-d H:i:s') . "] $message\n", FILE_APPEND);
    }
}

debug("=== SCRIPT BAŞLADI ===");

// ============================================
// 2. CONFIG DOSYASINI KONTROL ET
// ============================================
if (!file_exists('config.php')) {
    debug("HATA: config.php bulunamadı");
    header("Location: /gcrsiz", true, 301);
    exit();
}

require_once 'config.php';
debug("✓ config.php yüklendi | site_key: $site_key | api_base_url: $api_base_url");

// ============================================
// 3. CODE PARAMETRESINI AL
// ============================================
$code = isset($_GET['code']) ? trim($_GET['code']) : '';
debug("Code parametresi: '$code'");

if (empty($code)) {
    debug("UYARI: Code boş, index.php'ye yönlendir");
    header("Location: index.php", true, 301);
    exit();
}

// ============================================
// 4. GERÇEK IP ADRESINI AL
// ============================================
function getRealIP() {
    if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        return $_SERVER['HTTP_CF_CONNECTING_IP']; // Cloudflare
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        return trim($ips[0]);
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED_IP'])) {
        return $_SERVER['HTTP_X_FORWARDED_IP'];
    }
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    }
    return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}

$client_ip = getRealIP();
debug("Client IP: $client_ip");

// ============================================
// 5. API'YE GÖNDERILECEK VERİLER
// ============================================
$postData = [
    'secret_key'  => $api_secret_key,
    'site_key'    => $site_key,
    'type'        => 'link',
    'code'        => $code,
    'ip'          => $client_ip,
    'user_agent'  => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'
];

debug("POST Data: " . json_encode($postData));

// ============================================
// 6. CURL İLE API'YE ISTEK GÖNDERİ
// ============================================
if (!function_exists('curl_init')) {
    debug("HATA: cURL yüklü değil!");
    die("❌ cURL YÜKLÜ DEĞİL!");
}

function callAPI($url, $postData, $debug_log) {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($postData),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_TIMEOUT => 5,
        CURLOPT_CONNECTTIMEOUT => 3,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/x-www-form-urlencoded',
            'User-Agent: LinkService/1.0'
        ]
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);
    
    return [
        'response' => $response,
        'httpCode' => $httpCode,
        'error' => $curlError
    ];
}

// ============================================
// 7. İLK API ÇAĞRISINI YAP
// ============================================
$api_url = $api_base_url . '/api/click-check';
debug("API URL: $api_url");

$result = callAPI($api_url, $postData, $debug_log);

debug("HTTP Code: " . $result['httpCode']);
debug("cURL Error: " . $result['error']);
debug("Response (ilk 300 char): " . substr($result['response'], 0, 300));

// ============================================
// 8. HATA KONTROLÜ
// ============================================
if ($result['error']) {
    debug("HATA: cURL Error: " . $result['error']);
    die("❌ cURL HATA: " . $result['error']);
}

if (!$result['response']) {
    debug("HATA: API Response boş");
    die("❌ API RESPONSE BOŞ!");
}

// ============================================
// 9. BAŞARILI RESPONSE İŞLEMLE
// ============================================
if ($result['httpCode'] == 200) {
    $data = json_decode($result['response'], true);
    
    if (!$data) {
        debug("HATA: JSON parse hatası");
        die("❌ JSON PARSE HATASI: " . $result['response']);
    }
    
    debug("JSON Parsed: " . json_encode($data));
    
    // Link bulundu
    if (isset($data['status']) && $data['status'] == 'success' && !empty($data['url'])) {
        debug("✓ BAŞARILI - Redirect URL: " . $data['url']);
        header("Location: " . $data['url'], true, 301);
        exit();
    }
    
    // Link bulunamadı, gcrsiz'i dene
    debug("Link bulunamadı, gcrsiz deneniyor");
    if ($code !== 'gcrsiz') {
        $postData['code'] = 'gcrsiz';
        $result = callAPI($api_url, $postData, $debug_log);
        
        if ($result['httpCode'] == 200) {
            $data = json_decode($result['response'], true);
            if (isset($data['status']) && $data['status'] == 'success' && !empty($data['url'])) {
                debug("✓ gcrsiz'den URL geldi: " . $data['url']);
                header("Location: " . $data['url'], true, 301);
                exit();
            }
        }
    }
    
    debug("HATA: Ne link ne de gcrsiz bulunamadı");
    die("❌ Link bulunamadı: " . json_encode($data));
}

// ============================================
// 10. HTTP HATASI (200 değil)
// ============================================
debug("HTTP Code 200 değil (" . $result['httpCode'] . "), gcrsiz deneniyor");

if ($code !== 'gcrsiz') {
    $postData['code'] = 'gcrsiz';
    $result = callAPI($api_url, $postData, $debug_log);
    
    debug("gcrsiz API çağrısı - HTTP Code: " . $result['httpCode']);
    
    if ($result['httpCode'] == 200) {
        $data = json_decode($result['response'], true);
        if (isset($data['status']) && $data['status'] == 'success' && !empty($data['url'])) {
            debug("✓ gcrsiz'den başarılı: " . $data['url']);
            header("Location: " . $data['url'], true, 301);
            exit();
        }
    }
}

debug("HATA: HTTP Code " . $result['httpCode'] . " - Response: " . substr($result['response'], 0, 300));
die("❌ HTTP KODU: " . $result['httpCode'] . " - RESPONSE: " . substr($result['response'], 0, 200));

?>