<?php
/* fetch_celestrak.php — исправленная версия
   Получает TLE израильских спутников в текстовом формате и конвертирует в JSON
*/

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);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($http_code !== 200 || $data === false || strlen(trim($data)) === 0) {
        throw new Exception("HTTP $http_code or empty response");
    }
    return $data;
}

function parseTLEText($text) {
    $lines = array_filter(array_map('trim', explode("\n", $text)));
    $sats = [];
    for ($i = 0; $i < count($lines); $i += 3) {
        if (!isset($lines[$i + 1], $lines[$i + 2])) break;
        $name = $lines[$i];
        $line1 = $lines[$i + 1];
        $line2 = $lines[$i + 2];
        // Извлекаем NORAD ID из Line 1 (символы 2–7)
        $norad = trim(substr($line1, 2, 5));
        $sats[] = [
            'OBJECT_NAME' => $name,
            'NORAD_CAT_ID' => (int)$norad,
            'TLE_LINE1' => $line1,
            'TLE_LINE2' => $line2
        ];
    }
    return $sats;
}

try {
    $url = 'https://celestrak.org/NORAD/elements/gp.php?GROUP=israel&FORMAT=tle';
    $text = curlGet($url);
    $sats = parseTLEText($text);

    if (empty($sats)) {
        throw new Exception("No satellites found in TLE response");
    }

    $output_file = __DIR__ . '/celestrak_israel.json';
    file_put_contents($output_file, json_encode([
        'source' => 'Celestrak (TLE text parsed to JSON)',
        'last_update' => date('d.m.Y H:i') . ' UTC',
        'count' => count($sats),
        'satellites' => $sats
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

    echo json_encode([
        'status' => 'success',
        'count' => count($sats),
        'file' => 'celestrak_israel.json',
        'satellites' => array_column($sats, 'OBJECT_NAME')
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>