<?php
require_once 'includes/auth.php';
require_once 'includes/functions.php';
require_once 'includes/opensky-api.php';
require_once 'includes/sample-flights.php';

$page_title = 'Live Flights - ANATL Portal';

// Jakarta Airport (CGK) coordinates: -6.1256, 106.6590
$jakarta_lat = -6.1256;
$jakarta_lon = 106.6590;
$radius = 2; // ~220km radius

// Get bounding box
$bounds = OpenSkyAPI::getBoundingBox($jakarta_lat, $jakarta_lon, $radius);

// Fetch live flights from OpenSky API
$api = new OpenSkyAPI();
$data = $api->getStateVectors($bounds['lamin'], $bounds['lomin'], $bounds['lamax'], $bounds['lomax']);

$flights = [];
$is_sample_data = false;

if ($data && isset($data['states']) && !empty($data['states'])) {
    // Real data from OpenSky API
    foreach ($data['states'] as $state) {
        $flight = OpenSkyAPI::formatFlight($state);
        if (!empty($flight['callsign'])) {
            $flights[] = $flight;
        }
    }
} else {
    // Fallback to sample data for demo
    $flights = getSampleFlightsJakarta();
    $is_sample_data = true;
}

// Sort by altitude descending
usort($flights, function($a, $b) {
    $alt_a = $a['altitude'] ?? 0;
    $alt_b = $b['altitude'] ?? 0;
    return $alt_b <=> $alt_a;
});
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $page_title ?></title>
    <link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/style.css">
</head>
<body>
<?php require 'includes/header.php'; ?>

<div class="main">
    <div class="container">
        <h1 style="color: #003A70; margin-bottom: 32px;">✈️ Live Flights Near Jakarta</h1>

        <div style="background: <?= $is_sample_data ? '#FEF3C7' : '#E8F0F7' ?>; padding: 16px; border-radius: 8px; margin-bottom: 32px; border-left: 4px solid <?= $is_sample_data ? '#D97706' : '#003A70' ?>;">
            <p style="color: <?= $is_sample_data ? '#78350F' : '#003A70' ?>; margin: 0;">
                <?= $is_sample_data ? '📋' : '📡' ?> <strong>Data Source:</strong> <?= $is_sample_data ? 'Sample Demo Data' : 'OpenSky Network (Real-time ADS-B)' ?>
                <br><small style="color: <?= $is_sample_data ? '#92400E' : '#5A6A7A' ?>;">Area: 220km radius dari Bandar Udara Soekarno-Hatta Jakarta (CGK)<?= $is_sample_data ? ' • Simulated for demo purposes' : '' ?></small>
            </p>
        </div>

        <?php if (empty($flights)): ?>
        <div class="empty-state">
            <div class="empty-state__icon">✈️</div>
            <div class="empty-state__message">
                Tidak ada penerbangan terdeteksi saat ini dalam radius Jakarta<br>
                <small style="color: #5A6A7A;">Refresh halaman untuk update data terbaru</small>
            </div>
        </div>
        <?php else: ?>

        <div style="margin-bottom: 24px;">
            <p style="color: #5A6A7A; font-size: 14px;">
                📊 Total Flights: <strong><?= count($flights) ?></strong>
                <span style="margin-left: 16px;">🔄 Last update: <?= date('H:i:s') ?> (Refresh untuk update)</span>
            </p>
        </div>

        <div style="overflow-x: auto;">
            <table class="table">
                <thead>
                    <tr>
                        <th>Flight</th>
                        <th>Aircraft</th>
                        <th>Origin</th>
                        <th>Latitude</th>
                        <th>Longitude</th>
                        <th>Altitude (ft)</th>
                        <th>Velocity (m/s)</th>
                        <th>Track</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($flights as $flight): ?>
                    <tr>
                        <td><strong><?= esc($flight['callsign']) ?></strong></td>
                        <td><?= esc($flight['icao24']) ?></td>
                        <td><?= esc($flight['origin_country']) ?></td>
                        <td><?= number_format($flight['latitude'], 4) ?></td>
                        <td><?= number_format($flight['longitude'], 4) ?></td>
                        <td>
                            <?php if ($flight['altitude'] !== null): ?>
                                <?= number_format($flight['altitude'], 0) ?>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($flight['velocity'] !== null): ?>
                                <?= number_format($flight['velocity'], 2) ?>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($flight['true_track'] !== null): ?>
                                <?= number_format($flight['true_track'], 0) ?>°
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($flight['on_ground']): ?>
                                <span class="badge badge--submitted">Ground</span>
                            <?php else: ?>
                                <span class="badge badge--approved">Flying</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div style="margin-top: 32px; padding: 16px; background: #F4F6F9; border-radius: 8px;">
            <h3 style="color: #003A70; margin-top: 0;">📚 Informasi</h3>
            <ul style="color: #1A2332; line-height: 1.8;">
                <li><strong>Sumber Data:</strong> OpenSky Network - real-time ADS-B transponder data</li>
                <li><strong>Update Rate:</strong> Data di-cache 10 detik untuk stabilitas</li>
                <li><strong>Radius Area:</strong> ~220km dari Bandar Udara Soekarno-Hatta Jakarta (CGK)</li>
                <li><strong>Lokasi:</strong> Jakarta, Indonesia (-6.1256°, 106.6590°)</li>
                <li><strong>Altitude:</strong> Diukur dalam feet (1 ft = 0.3048 meter)</li>
                <li><strong>Velocity:</strong> Kecepatan dalam meter per detik</li>
                <li><strong>Refresh:</strong> Tekan F5 atau klik tombol refresh untuk data terbaru</li>
            </ul>
            <a href="<?= BASE_URL ?>/live-flights.php" class="btn btn--primary" style="margin-top: 16px;">🔄 Refresh Data</a>
        </div>

        <?php endif; ?>
    </div>
</div>

<?php require 'includes/footer.php'; ?>
