<?php
header('Content-Type: application/json; charset=utf-8');
error_reporting(0);

$bin = $_GET['bin'] ?? '';
if (empty($bin)) {
    die(json_encode(['error' => 'BIN gerekli'], JSON_UNESCAPED_UNICODE));
}

// İlk 6 haneyi al
$bin = substr($bin, 0, 6);

// Ülke bayrakları
$country_flags = [
    'TR' => '🇹🇷', 'US' => '🇺🇸', 'GB' => '🇬🇧', 'DE' => '🇩🇪', 'FR' => '🇫🇷',
    'IT' => '🇮🇹', 'ES' => '🇪🇸', 'NL' => '🇳🇱', 'CA' => '🇨🇦', 'AU' => '🇦🇺',
    'BR' => '🇧🇷', 'RU' => '🇷🇺', 'CN' => '🇨🇳', 'JP' => '🇯🇵', 'IN' => '🇮🇳',
    'SA' => '🇸🇦', 'AE' => '🇦🇪', 'MX' => '🇲🇽', 'AR' => '🇦🇷', 'SE' => '🇸🇪',
    'NO' => '🇳🇴', 'DK' => '🇩🇰', 'PL' => '🇵🇱', 'CH' => '🇨🇭', 'AT' => '🇦🇹',
    'BE' => '🇧🇪', 'PT' => '🇵🇹', 'GR' => '🇬🇷', 'CZ' => '🇨🇿', 'HU' => '🇭🇺',
    'RO' => '🇷🇴', 'UA' => '🇺🇦', 'ZA' => '🇿🇦', 'EG' => '🇪🇬', 'KR' => '🇰🇷',
    'SG' => '🇸🇬', 'MY' => '🇲🇾', 'TH' => '🇹🇭', 'ID' => '🇮🇩', 'PH' => '🇵🇭',
    'VN' => '🇻🇳', 'IL' => '🇮🇱', 'FI' => '🇫🇮', 'IE' => '🇮🇪', 'NZ' => '🇳🇿',
    'CL' => '🇨🇱', 'CO' => '🇨🇴', 'PE' => '🇵🇪', 'VE' => '🇻🇪', 'KW' => '🇰🇼',
    'QA' => '🇶🇦', 'BH' => '🇧🇭', 'OM' => '🇴🇲', 'JO' => '🇯🇴', 'LB' => '🇱🇧'
];

$result = null;

// Global Database #1 - binlist-data.csv
// Dinamik yol - hem Windows hem Linux'ta çalışır
$global_csv = __DIR__ . '/binlist-data.csv';
if (file_exists($global_csv)) {
    $file = fopen($global_csv, 'r');
    
    while (($data = fgetcsv($file, 10000, ',')) !== FALSE) {
        $csv_bin = substr(trim($data[0]), 0, 6);
        
        if ($csv_bin == $bin) {
            $country_code = strtoupper($data[5] ?? '');
            $country_name = $data[7] ?? 'UNKNOWN';
            $country_flag = $country_flags[$country_code] ?? '';
            $country = ($country_flag ? $country_flag . ' ' : '') . $country_code;
            
            $bank = !empty($data[4]) ? $data[4] : $country_name;
            $brand = strtoupper($data[1] ?? 'UNKNOWN');
            $type = strtoupper($data[2] ?? 'UNKNOWN');
            $category = strtoupper($data[3] ?? '');
            
            $level = !empty($category) ? $category : 'CLASSIC';
            
            $result = [
                'bin' => $bin,
                'bank' => $bank,
                'country' => $country,
                'level' => $level,
                'type' => $type,
                'brand' => $brand
            ];
            break;
        }
    }
    fclose($file);
}

if (!$result) {
    $result = [
        'bin' => $bin,
        'bank' => 'NOT_FOUND',
        'country' => 'NOT_FOUND',
        'level' => 'NOT_FOUND',
        'type' => 'NOT_FOUND',
        'brand' => 'NOT_FOUND'
    ];
}

echo json_encode($result, JSON_UNESCAPED_UNICODE);
?>
