<?php
/* fetch_launches.php
   Получает данные о предстоящих и прошедших запусках:
   - ULTRASAT (Израиль + NASA)
   - Beresheet 2 (SpaceIL)
   - NISAR (США + Индия, но важно для Ирана)
*/

function curlGet($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Avatiah-OSINT/1.0 (research)');
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$missions_to_track = ['ULTRASAT', 'Beresheet', 'NISAR'];

$launches = [];
foreach ($missions_to_track as $mission) {
    $url = "https://ll.thespacedevs.com/2.2.0/launch/?search=" . urlencode($mission) . "&limit=3";
    $json = curlGet($url);
    if ($json) {
        $data = json_decode($json, true);
        if (!empty($data['results'])) {
            foreach ($data['results'] as $launch) {
                $launches[] = [
                    'mission' => $mission,
                    'name' => $launch['name'],
                    'status' => $launch['status']['name'] ?? 'Unknown',
                    'launch_date' => $launch['window_end'] ?? $launch['net'] ?? 'TBD',
                    'provider' => $launch['launch_service_provider']['name'] ?? 'Unknown',
                    'url' => $launch['url'] ?? ''
                ];
            }
        }
    }
    usleep(100000); // пауза 0.1 сек
}

// Сохраняем
$output_file = __DIR__ . '/israel_launches.json';
file_put_contents($output_file, json_encode([
    'source' => 'The Space Devs Launch Library (public API)',
    'last_update' => date('d.m.Y H:i') . ' UTC',
    'count' => count($launches),
    'launches' => $launches
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

echo json_encode([
    'status' => 'success',
    'file' => 'israel_launches.json',
    'count' => count($launches),
    'missions' => $missions_to_track
], JSON_UNESCAPED_UNICODE);
?>