<?php

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

$start_time = microtime(true);

if (!isset($_GET['bin'])) {
    die(json_encode(['error' => 'Bin parametresi eksik'], JSON_UNESCAPED_UNICODE));
}

$bin = $_GET['bin'];

// 3 worker'ı paralel çağır
$urls = [
    'http://localhost/yenicheckbotaerithia/apiler/binapi/worker_tr.php?bin=' . $bin,
    'http://localhost/yenicheckbotaerithia/apiler/binapi/worker_global1.php?bin=' . $bin,
    'http://localhost/yenicheckbotaerithia/apiler/binapi/worker_global2.php?bin=' . $bin
];

$mh = curl_multi_init();
$curl_array = [];

foreach($urls as $i => $url) {
    $curl_array[$i] = curl_init($url);
    curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_array[$i], CURLOPT_TIMEOUT, 10);
    curl_multi_add_handle($mh, $curl_array[$i]);
}

// Paralel çalıştır
$running = null;
do {
    curl_multi_exec($mh, $running);
    curl_multi_select($mh);
} while ($running > 0);

// Sonuçları topla
$results = [];
foreach($curl_array as $i => $ch) {
    $results[$i] = curl_multi_getcontent($ch);
    curl_multi_remove_handle($mh, $ch);
    curl_close($ch);
}
curl_multi_close($mh);

// JSON parse et
$tr_result = json_decode($results[0], true);
$global_result = json_decode($results[1], true);
$global2_result = json_decode($results[2], true);

$end_time = microtime(true);
$query_time = round(($end_time - $start_time), 3);

$final_result = [
    'tr_db' => $tr_result,
    'global_db' => $global_result,
    'global2_db' => $global2_result,
    'query_time' => $query_time . 's'
];

echo json_encode($final_result, JSON_UNESCAPED_UNICODE);

?>
