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

$page_title = 'Live Flights - 3 Countries - ANATL Portal';

// Get active tab
$tab = $_GET['tab'] ?? 'jakarta';

// Define regions
$regions = [
    'jakarta' => [
        'name' => 'Jakarta, Indonesia',
        'airport' => 'CGK (Soekarno-Hatta)',
        'lat' => -6.1256,
        'lon' => 106.6590,
        'emoji' => '🇮🇩',
        'color' => '#FF0000',
    ],
    'dili' => [
        'name' => 'Dili, Timor-Leste',
        'airport' => 'DIL (Nicolau Lobato)',
        'lat' => -8.5211,
        'lon' => 125.0329,
        'emoji' => '🇹🇱',
        'color' => '#FFD700',
    ],
    'darwin' => [
        'name' => 'Darwin, Australia',
        'airport' => 'DRW (Darwin International)',
        'lat' => -12.4634,
        'lon' => 130.8456,
        'emoji' => '🇦🇺',
        'color' => '#0066CC',
    ],
];

// Get flights for all regions
$all_flights = [];
$api = new OpenSkyAPI();

foreach ($regions as $key => $region) {
    $bounds = OpenSkyAPI::getBoundingBox($region['lat'], $region['lon'], 2);
    $data = $api->getStateVectors($bounds['lamin'], $bounds['lomin'], $bounds['lamax'], $bounds['lomax']);

    $flights = [];
    $is_sample = false;

    if ($data && isset($data['states']) && !empty($data['states'])) {
        foreach ($data['states'] as $state) {
            $flight = OpenSkyAPI::formatFlight($state);
            if (!empty($flight['callsign'])) {
                $flights[] = $flight;
            }
        }
    } else {
        // Use sample data
        $func = "getSampleFlights" . ucfirst($key);
        $flights = $func();
        $is_sample = true;
    }

    // Sort by altitude
    usort($flights, function($a, $b) {
        return ($b['altitude'] ?? 0) <=> ($a['altitude'] ?? 0);
    });

    $all_flights[$key] = [
        'flights' => $flights,
        'is_sample' => $is_sample,
    ];
}

// Get current tab flights
$current_flights = $all_flights[$tab]['flights'] ?? [];
$current_is_sample = $all_flights[$tab]['is_sample'] ?? false;
$current_region = $regions[$tab] ?? $regions['jakarta'];
?>
<!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: 24px;">✈️ Live Flights - 3 Countries</h1>

        <div style="background: #E8F0F7; padding: 16px; border-radius: 8px; margin-bottom: 32px; border-left: 4px solid #003A70;">
            <p style="color: #003A70; margin: 0;">
                🌏 <strong>Multi-Region Flight Tracking:</strong> Real-time data dari Jakarta, Dili, dan Darwin
                <br><small style="color: #5A6A7A;">Click tab untuk switching antara regions • Data refreshes setiap 10 detik</small>
            </p>
        </div>

        <!-- Tab Navigation -->
        <div style="display: flex; gap: 8px; margin-bottom: 32px; border-bottom: 2px solid #D1D9E0; flex-wrap: wrap;">
            <?php foreach ($regions as $key => $region): ?>
            <a href="?tab=<?= $key ?>" style="padding: 12px 20px; text-decoration: none; color: <?= $tab === $key ? '#003A70' : '#5A6A7A' ?>; border-bottom: <?= $tab === $key ? '3px solid #003A70' : 'none' ?>; font-weight: <?= $tab === $key ? '600' : '400' ?>; cursor: pointer;">
                <?= $region['emoji'] ?> <?= $region['name'] ?> (<?= count($all_flights[$key]['flights']) ?>)
            </a>
            <?php endforeach; ?>
        </div>

        <!-- Current Region Info -->
        <div style="background: <?= $current_is_sample ? '#FEF3C7' : '#E8F0F7' ?>; padding: 16px; border-radius: 8px; margin-bottom: 24px; border-left: 4px solid <?= $current_is_sample ? '#D97706' : $current_region['color'] ?>;">
            <p style="color: <?= $current_is_sample ? '#78350F' : '#003A70' ?>; margin: 0;">
                <?= $current_is_sample ? '📋' : '📡' ?> <strong><?= $current_region['emoji'] ?> <?= $current_region['name'] ?></strong>
                <br><small style="color: <?= $current_is_sample ? '#92400E' : '#5A6A7A' ?>;">
                    Airport: <?= $current_region['airport'] ?> •
                    Lat: <?= number_format($current_region['lat'], 4) ?>, Lon: <?= number_format($current_region['lon'], 4) ?>
                    <?= $current_is_sample ? '• Demo Data' : '• Live Data' ?>
                </small>
            </p>
        </div>

        <!-- Statistics -->
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 16px; margin-bottom: 24px;">
            <div class="stat-card">
                <div style="font-size: 24px;">✈️</div>
                <div class="stat-card__value"><?= count($current_flights) ?></div>
                <div class="stat-card__label">Total Flights</div>
            </div>
            <div class="stat-card">
                <div style="font-size: 24px;">📊</div>
                <div class="stat-card__value">
                    <?php
                    $avg_alt = 0;
                    if (!empty($current_flights)) {
                        $total = array_sum(array_map(function($f) { return $f['altitude'] ?? 0; }, $current_flights));
                        $avg_alt = round($total / count($current_flights));
                    }
                    echo number_format($avg_alt, 0);
                    ?>
                </div>
                <div class="stat-card__label">Avg Altitude (ft)</div>
            </div>
            <div class="stat-card">
                <div style="font-size: 24px;">⚡</div>
                <div class="stat-card__value">
                    <?php
                    $avg_vel = 0;
                    if (!empty($current_flights)) {
                        $total = array_sum(array_map(function($f) { return $f['velocity'] ?? 0; }, $current_flights));
                        $avg_vel = round($total / count($current_flights), 1);
                    }
                    echo number_format($avg_vel, 1);
                    ?>
                </div>
                <div class="stat-card__label">Avg Velocity (m/s)</div>
            </div>
            <div class="stat-card">
                <div style="font-size: 24px;">🛫</div>
                <div class="stat-card__value">
                    <?php
                    $flying = count(array_filter($current_flights, function($f) { return !$f['on_ground']; }));
                    echo $flying;
                    ?>
                </div>
                <div class="stat-card__label">Flying</div>
            </div>
        </div>

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

        <div style="overflow-x: auto;">
            <table class="table">
                <thead>
                    <tr>
                        <th>Flight</th>
                        <th>Country</th>
                        <th>Lat/Lon</th>
                        <th>Altitude (ft)</th>
                        <th>Velocity (m/s)</th>
                        <th>Track (°)</th>
                        <th>V/Rate (m/s)</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($current_flights as $flight): ?>
                    <tr>
                        <td><strong><?= esc($flight['callsign']) ?></strong></td>
                        <td><?= esc($flight['origin_country']) ?></td>
                        <td>
                            <small><?= number_format($flight['latitude'], 3) ?><br><?= number_format($flight['longitude'], 3) ?></small>
                        </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'], 1) ?>
                            <?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['vertical_rate'] !== null): ?>
                                <span style="color: <?= $flight['vertical_rate'] > 0 ? '#059669' : ($flight['vertical_rate'] < 0 ? '#DC2626' : '#5A6A7A') ?>;">
                                    <?= number_format($flight['vertical_rate'], 1) ?>
                                </span>
                            <?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;">📚 About Multi-Region Tracking</h3>
            <ul style="color: #1A2332; line-height: 1.8; margin-bottom: 16px;">
                <li><strong>🇮🇩 Jakarta:</strong> Hub of Southeast Asia, CGK International Airport - 5 flights</li>
                <li><strong>🇹🇱 Dili:</strong> Capital of Timor-Leste, DIL Nicolau Lobato International - 4 flights</li>
                <li><strong>🇦🇺 Darwin:</strong> Gateway to Australia, DRW International Airport - 5 flights</li>
                <li><strong>Data Source:</strong> OpenSky Network (with sample data fallback for demo)</li>
            </ul>
            <a href="<?= BASE_URL ?>/live-flights-3countries.php" class="btn btn--primary" style="margin-right: 8px;">🔄 Refresh Data</a>
            <a href="<?= BASE_URL ?>/live-flights.php" class="btn btn--secondary">📍 Single Region View</a>
        </div>

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

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