<?php
/**
 * OpenSky Network API Integration
 * Free flight tracking data from OpenSky Network
 * API: https://api.opensky-network.org
 */

class OpenSkyAPI {
    private $base_url = 'https://api.opensky-network.org/api';
    private $timeout = 5;

    /**
     * Get all flights in a given bounding box
     *
     * @param float $lamin Minimum latitude
     * @param float $lomin Minimum longitude
     * @param float $lamax Maximum latitude
     * @param float $lomax Maximum longitude
     * @param int|null $begin Begin timestamp (optional)
     * @return array|null
     */
    public function getStateVectors($lamin, $lomin, $lamax, $lomax, $begin = null) {
        $params = [
            'lamin' => $lamin,
            'lomin' => $lomin,
            'lamax' => $lamax,
            'lomax' => $lomax,
        ];

        if ($begin) {
            $params['begin'] = $begin;
        }

        return $this->makeRequest('/states/all', $params);
    }

    /**
     * Get all flights (worldwide) - WARNING: Large response!
     * Use with bounds parameter instead for better performance
     *
     * @return array|null
     */
    public function getAllFlights() {
        return $this->makeRequest('/states/all');
    }

    /**
     * Get flights for specific callsigns
     *
     * @param array|string $callsigns Single callsign or array of callsigns
     * @param int|null $begin Begin timestamp
     * @param int|null $end End timestamp
     * @return array|null
     */
    public function getFlightsBycallsign($callsigns, $begin = null, $end = null) {
        $params = [];

        if (is_array($callsigns)) {
            $params['callsigns'] = implode(',', $callsigns);
        } else {
            $params['callsigns'] = $callsigns;
        }

        if ($begin) $params['begin'] = $begin;
        if ($end) $params['end'] = $end;

        return $this->makeRequest('/flights/search', $params);
    }

    /**
     * Get tracks for a specific flight (full trajectory)
     *
     * @param string $icao24 ICAO 24-bit aircraft address
     * @param int $time Unix timestamp
     * @return array|null
     */
    public function getTrack($icao24, $time) {
        $params = [
            'icao24' => $icao24,
            'time' => $time,
        ];

        return $this->makeRequest('/tracks/all', $params);
    }

    /**
     * Make API request
     *
     * @param string $endpoint API endpoint
     * @param array $params Query parameters
     * @return array|null
     */
    private function makeRequest($endpoint, $params = []) {
        try {
            $url = $this->base_url . $endpoint;

            if (!empty($params)) {
                $url .= '?' . http_build_query($params);
            }

            $context = stream_context_create([
                'http' => [
                    'timeout' => $this->timeout,
                    'user_agent' => 'ANATL-Portal/1.0',
                ]
            ]);

            $response = @file_get_contents($url, false, $context);

            if ($response === false) {
                return null;
            }

            return json_decode($response, true);
        } catch (Exception $e) {
            error_log('OpenSky API Error: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * Format flight data for display
     *
     * @param array $flight Flight state vector
     * @return array
     */
    public static function formatFlight($flight) {
        return [
            'icao24' => $flight[0] ?? null,
            'callsign' => trim($flight[1] ?? ''),
            'origin_country' => $flight[2] ?? null,
            'time_position' => $flight[3] ?? null,
            'last_contact' => $flight[4] ?? null,
            'longitude' => $flight[5] ?? null,
            'latitude' => $flight[6] ?? null,
            'altitude' => $flight[7] ?? null,
            'on_ground' => $flight[8] ?? false,
            'velocity' => $flight[9] ?? null,
            'true_track' => $flight[10] ?? null,
            'vertical_rate' => $flight[11] ?? null,
            'sensors' => $flight[12] ?? null,
            'geo_altitude' => $flight[13] ?? null,
            'squawk' => $flight[14] ?? null,
            'spi' => $flight[15] ?? false,
            'position_source' => $flight[16] ?? null,
            'category' => $flight[17] ?? null,
        ];
    }

    /**
     * Convert latitude/longitude to bounding box around a point
     * Useful for airport location
     *
     * @param float $lat Latitude
     * @param float $lon Longitude
     * @param float $radius Radius in degrees (approximately 111km per degree)
     * @return array [lamin, lomin, lamax, lomax]
     */
    public static function getBoundingBox($lat, $lon, $radius = 1) {
        return [
            'lamin' => $lat - $radius,
            'lomin' => $lon - $radius,
            'lamax' => $lat + $radius,
            'lomax' => $lon + $radius,
        ];
    }
}
