<?php
$airports = [
    'LKPR' => ['name' => 'Praha Ruzyně',     'city' => 'Prague',          'icao' => 'LKPR', 'iata' => 'PRG'],
    'LKMT' => ['name' => 'Ostrava Mošnov',   'city' => 'Ostrava',         'icao' => 'LKMT', 'iata' => 'OSR'],
    'LKTB' => ['name' => 'Brno Tuřany',      'city' => 'Brno',            'icao' => 'LKTB', 'iata' => 'BRQ'],
    'LKKV' => ['name' => 'Karlovy Vary',     'city' => 'Karlovy Vary',    'icao' => 'LKKV', 'iata' => 'KLV'],
    'LKVO' => ['name' => 'Vodochody',        'city' => 'Prague North',    'icao' => 'LKVO', 'iata' => '---'],
];

$icao = isset($_GET['icao']) && isset($airports[strtoupper($_GET['icao'])])
    ? strtoupper($_GET['icao']) : 'LKMT';

$remote_url = "https://meteo.rlp.cz/txt/{$icao}_atis.txt";
$cache_file  = __DIR__ . "/cache_{$icao}_atis.txt";
$cache_ttl   = 30;

function fetch_remote($url, $timeout = 8) {
    if (function_exists('curl_version')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_FOLLOWLOCATION=>true,
            CURLOPT_TIMEOUT=>$timeout, CURLOPT_USERAGENT=>'ATIS-viewer/2.0']);
        $res = curl_exec($ch); $err = curl_errno($ch); curl_close($ch);
        return $err ? false : $res;
    }
    return @file_get_contents($url, false, stream_context_create(['http'=>['method'=>'GET','timeout'=>$timeout]]));
}

$stale = false;
if (file_exists($cache_file) && (time() - filemtime($cache_file) < $cache_ttl)) {
    $atis_raw = file_get_contents($cache_file);
} else {
    $fetched = fetch_remote($remote_url);
    if ($fetched !== false && !empty(trim($fetched))) {
        file_put_contents($cache_file, $fetched);
        $atis_raw = $fetched;
    } elseif (file_exists($cache_file)) {
        $atis_raw = file_get_contents($cache_file);
        $stale = true;
    } else {
        $atis_raw = "ATIS data unavailable.";
    }
}

$atis_clean = trim(strip_tags($atis_raw));
$updated_ts = file_exists($cache_file) ? filemtime($cache_file) : time();
$updated    = date('H:i:s \U\T\C', $updated_ts);
$age_sec    = time() - $updated_ts;
$age_str    = $age_sec < 60 ? "{$age_sec}s ago" : floor($age_sec/60)."m ago";

// Parse some fields from raw ATIS for highlights
$info_letter = '';
if (preg_match('/INFO(?:RMATION)?\s+([A-Z])/', $atis_clean, $m)) $info_letter = $m[1];
$wind = ''; if (preg_match('/WIND\s+([\d\/KTG]+)/', $atis_clean, $m)) $wind = $m[1];
$vis  = ''; if (preg_match('/VISIBILITY\s+([\d]+(?:\s?KM)?)/', $atis_clean, $m)) $vis = $m[1];
$temp = ''; if (preg_match('/TEMPERATURE\s+(M?[\d]+)/', $atis_clean, $m)) $temp = $m[1];
$qnh  = ''; if (preg_match('/QNH\s+([\d]+)/', $atis_clean, $m)) $qnh = $m[1];
$rwy  = ''; if (preg_match('/RWY\s+([\d]+[LRC]?)/', $atis_clean, $m)) $rwy = $m[1];

$ap = $airports[$icao];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="topbar-section" content="ATIS Viewer">
<link rel="icon" type="image/png" href="/favicon-32.png" sizes="32x32">
<title>ATIS — <?= $icao ?> | fushift.fun</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<script src="/js/topbar.js"></script>
<style>
:root {
    --bg: #07070d; --bg2: #0d0d16; --surface: #111120; --surface2: #191929;
    --border: rgba(255,255,255,0.06); --border-h: rgba(255,255,255,0.13);
    --text: #e8e8f0; --muted: #7878a0; --dim: #3a3a56;
    --accent: #6366f1; --accent2: #8b5cf6;
    --green: #22c55e; --yellow: #eab308; --red: #ef4444; --cyan: #06b6d4;
}
*, *::before, *::after { margin:0; padding:0; box-sizing:border-box; }
html { scroll-behavior:smooth; }
body { background:var(--bg); color:var(--text); font-family:'Inter',sans-serif; min-height:100vh; -webkit-font-smoothing:antialiased; }

.page { max-width:900px; margin:0 auto; padding:36px 24px 80px; }

/* Airport selector */
.airport-tabs { display:flex; gap:6px; flex-wrap:wrap; margin-bottom:32px; }
.airport-tab {
    text-decoration:none; font-family:'JetBrains Mono',monospace; font-size:11px;
    padding:8px 16px; border-radius:8px; border:1px solid var(--border);
    color:var(--muted); background:var(--surface); transition:all .2s;
    display:flex; flex-direction:column; align-items:center; gap:2px;
}
.airport-tab:hover { border-color:var(--border-h); color:var(--text); }
.airport-tab.active { background:rgba(99,102,241,.12); border-color:rgba(99,102,241,.35); color:var(--accent); }
.airport-tab .icao { font-size:13px; font-weight:600; }
.airport-tab .iata { font-size:9px; color:var(--dim); letter-spacing:.5px; }

/* Hero */
.hero { margin-bottom:24px; }
.hero-label { font-family:'JetBrains Mono',monospace; font-size:10px; text-transform:uppercase; letter-spacing:3px; color:var(--accent); margin-bottom:8px; display:flex; align-items:center; gap:8px; }
.hero-label::after { content:''; display:block; height:1px; width:28px; background:var(--accent); opacity:.4; }
.hero h1 { font-size:clamp(28px,5vw,48px); font-weight:800; letter-spacing:-2px; line-height:1.05; margin-bottom:6px; }
.hero h1 span { background:linear-gradient(135deg,var(--accent),var(--accent2)); -webkit-background-clip:text; -webkit-text-fill-color:transparent; background-clip:text; }
.hero-sub { color:var(--muted); font-size:14px; }

/* Status row */
.status-row { display:flex; align-items:center; gap:10px; flex-wrap:wrap; padding:12px 18px; background:var(--surface); border:1px solid var(--border); border-radius:10px; margin-bottom:24px; font-family:'JetBrains Mono',monospace; font-size:11px; }
.s-dot { width:7px; height:7px; border-radius:50%; background:var(--green); animation:pulse 2s infinite; flex-shrink:0; }
.s-dot.stale { background:var(--yellow); }
@keyframes pulse { 0%,100%{box-shadow:0 0 0 0 rgba(34,197,94,.4);} 50%{box-shadow:0 0 0 5px rgba(34,197,94,0);} }
.s-sep { width:1px; height:14px; background:var(--border); }
.s-val { color:var(--text); }
.s-lbl { color:var(--dim); }

/* Info letter badge */
.info-badge {
    display:inline-flex; align-items:center; justify-content:center;
    width:44px; height:44px; border-radius:10px; font-size:22px; font-weight:800;
    background:rgba(99,102,241,.15); border:2px solid rgba(99,102,241,.35); color:var(--accent);
    font-family:'JetBrains Mono',monospace; flex-shrink:0;
}

/* Highlights grid */
.highlights { display:grid; grid-template-columns:repeat(auto-fit,minmax(120px,1fr)); gap:10px; margin-bottom:24px; }
.hl-card { background:var(--surface); border:1px solid var(--border); border-radius:10px; padding:14px 16px; }
.hl-val { font-size:20px; font-weight:700; font-family:'JetBrains Mono',monospace; color:var(--text); margin-bottom:3px; }
.hl-lbl { font-size:9px; text-transform:uppercase; letter-spacing:1.5px; color:var(--dim); font-family:'JetBrains Mono',monospace; }

/* Raw ATIS box */
.atis-card { background:var(--surface); border:1px solid var(--border); border-radius:12px; overflow:hidden; }
.atis-header { display:flex; align-items:center; gap:12px; padding:16px 20px; border-bottom:1px solid var(--border); }
.atis-title { font-size:12px; font-weight:600; color:var(--muted); text-transform:uppercase; letter-spacing:1px; font-family:'JetBrains Mono',monospace; }
.atis-raw { padding:20px; font-family:'JetBrains Mono',monospace; font-size:13px; line-height:1.9; color:#c0c0d8; white-space:pre-wrap; word-break:break-word; }
.atis-raw .kw { color:var(--accent); font-weight:600; }
.atis-raw .val { color:var(--cyan); }
.atis-raw .warn { color:var(--yellow); }

/* Refresh button */
.refresh-btn {
    margin-left:auto; display:inline-flex; align-items:center; gap:6px;
    font-family:'JetBrains Mono',monospace; font-size:11px; color:var(--muted);
    background:var(--surface2); border:1px solid var(--border-h); border-radius:6px;
    padding:6px 12px; cursor:pointer; text-decoration:none; transition:all .2s;
}
.refresh-btn:hover { color:var(--text); border-color:var(--accent); }

/* Footer */
.page-footer { margin-top:48px; padding-top:24px; border-top:1px solid var(--border); display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px; font-family:'JetBrains Mono',monospace; font-size:11px; color:var(--dim); }
.page-footer a { color:var(--muted); text-decoration:none; transition:color .2s; }
.page-footer a:hover { color:var(--accent); }

@media(max-width:560px) { .airport-tabs { gap:4px; } .airport-tab { padding:6px 10px; } .highlights { grid-template-columns:1fr 1fr; } }
</style>
</head>
<body>

<div class="page">

    <!-- Airport tabs -->
    <div class="airport-tabs">
        <?php foreach ($airports as $code => $a): ?>
        <a href="?icao=<?= $code ?>" class="airport-tab <?= ($code === $icao ? 'active' : '') ?>">
            <span class="icao"><?= $code ?></span>
            <span class="iata"><?= $a['iata'] ?></span>
        </a>
        <?php endforeach; ?>
    </div>

    <!-- Hero -->
    <div class="hero">
        <div class="hero-label">Live ATIS</div>
        <h1><?= $ap['name'] ?><br><span><?= $icao ?></span></h1>
        <p class="hero-sub"><?= $ap['city'] ?> · Automatic Terminal Information Service</p>
    </div>

    <!-- Status row -->
    <div class="status-row">
        <?php if ($info_letter): ?>
        <div class="info-badge"><?= $info_letter ?></div>
        <?php endif; ?>
        <span class="s-dot <?= $stale ? 'stale' : '' ?>"></span>
        <span class="s-lbl">Status:</span>
        <span class="s-val"><?= $stale ? 'STALE (using cached)' : 'LIVE' ?></span>
        <span class="s-sep"></span>
        <span class="s-lbl">Updated:</span>
        <span class="s-val"><?= $updated ?></span>
        <span class="s-sep"></span>
        <span class="s-lbl">Age:</span>
        <span class="s-val"><?= $age_str ?></span>
        <a href="?icao=<?= $icao ?>" class="refresh-btn">↻ Refresh</a>
    </div>

    <!-- Parsed highlights -->
    <?php if ($wind || $vis || $temp || $qnh || $rwy): ?>
    <div class="highlights">
        <?php if ($rwy): ?>
        <div class="hl-card"><div class="hl-val"><?= htmlspecialchars($rwy) ?></div><div class="hl-lbl">Active RWY</div></div>
        <?php endif; ?>
        <?php if ($wind): ?>
        <div class="hl-card"><div class="hl-val"><?= htmlspecialchars($wind) ?></div><div class="hl-lbl">Wind</div></div>
        <?php endif; ?>
        <?php if ($vis): ?>
        <div class="hl-card"><div class="hl-val"><?= htmlspecialchars($vis) ?></div><div class="hl-lbl">Visibility</div></div>
        <?php endif; ?>
        <?php if ($temp): ?>
        <div class="hl-card"><div class="hl-val"><?= htmlspecialchars($temp) ?>°C</div><div class="hl-lbl">Temperature</div></div>
        <?php endif; ?>
        <?php if ($qnh): ?>
        <div class="hl-card"><div class="hl-val"><?= htmlspecialchars($qnh) ?> hPa</div><div class="hl-lbl">QNH</div></div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- Raw ATIS -->
    <div class="atis-card">
        <div class="atis-header">
            <span class="atis-title">Raw ATIS Text</span>
            <span style="font-family:'JetBrains Mono',monospace;font-size:10px;color:var(--dim);">meteo.rlp.cz · <?= htmlspecialchars($icao) ?>_atis.txt</span>
        </div>
        <div class="atis-raw" id="atis-text"><?php
            // Simple keyword highlighting
            $text = htmlspecialchars($atis_clean, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8');
            $kws = ['WIND','VISIBILITY','TEMPERATURE','DEWPOINT','QNH','QFE','RWY','RUNWAY',
                    'INFORMATION','METAR','CLOUD','CEILING','CAVOK','VRB','NOSIG','BECMG',
                    'TREND','ATIS','TRANSITION','LEVEL'];
            foreach ($kws as $kw) {
                $text = preg_replace('/\b('.$kw.')\b/', '<span class="kw">$1</span>', $text);
            }
            echo $text;
        ?></div>
    </div>

    <div class="page-footer">
        <span>✈️ ATIS Viewer · Czech Airports</span>
        <a href="/">← fushift.fun</a>
    </div>
</div>

<script>
// Auto-refresh every 30s
setTimeout(() => location.reload(), 30000);

// Keyboard shortcuts: 1-5 for airports
const codes = <?= json_encode(array_keys($airports)) ?>;
document.addEventListener('keydown', e => {
    const i = parseInt(e.key) - 1;
    if (i >= 0 && i < codes.length) location.href = '?icao=' + codes[i];
});
</script>
</body>
</html>
