<?php
require_once '../includes/auth.php';
require_once '../includes/functions.php';
require_once '../includes/upload.php';

require_login('airline');
$page_title = 'Flight Plan - ANATL Portal';
$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validate_csrf($_POST['csrf_token'] ?? '')) {
        die('Invalid request');
    }

    $flight_no = trim($_POST['flight_no'] ?? '');
    $route = trim($_POST['route'] ?? '');
    $etd = trim($_POST['etd'] ?? '');
    $eta = trim($_POST['eta'] ?? '');
    $aircraft_reg = trim($_POST['aircraft_reg'] ?? '');

    if ($flight_no && $route && $etd && $eta) {
        $doc_path = handle_upload('doc', 'flight-plan');

        $stmt = $conn->prepare('INSERT INTO flight_plans (user_id, flight_no, route, etd, eta, aircraft_reg, doc_path) VALUES (?, ?, ?, ?, ?, ?, ?)');
        $stmt->bind_param('issssss', $user_id, $flight_no, $route, $etd, $eta, $aircraft_reg, $doc_path);

        if ($stmt->execute()) {
            set_flash('success', 'Flight plan berhasil dikirim');
        } else {
            set_flash('error', 'Gagal mengirim flight plan');
        }
        $stmt->close();
    } else {
        set_flash('error', 'Semua field harus diisi');
    }

    header('Location: ' . BASE_URL . '/maskapai/flight-plan.php');
    exit;
}

$plans = [];
$result = $conn->query("SELECT * FROM flight_plans WHERE user_id = $user_id ORDER BY created_at DESC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $plans[] = $row;
    }
}
?>
<!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="portal">
        <div class="portal__sidebar">
            <div class="sidebar__title">Menu Maskapai</div>
            <a href="<?= BASE_URL ?>/maskapai/index.php" class="sidebar-item">📊 Dashboard</a>
            <a href="<?= BASE_URL ?>/maskapai/slot.php" class="sidebar-item">✈️ Slot Time</a>
            <a href="<?= BASE_URL ?>/maskapai/flight-plan.php" class="sidebar-item sidebar-item--active">📋 Flight Plan</a>
            <a href="<?= BASE_URL ?>/maskapai/safety.php" class="sidebar-item">⚠️ Safety Report</a>
        </div>

        <div class="portal__content">
            <h1 style="color: #003A70; margin-bottom: 32px;">Flight Plan</h1>

            <?php if ($flash = get_flash()): ?>
            <div class="alert alert--<?= esc($flash['type']) ?>">
                <?= esc($flash['msg']) ?>
            </div>
            <?php endif; ?>

            <div class="card" style="margin-bottom: 48px;">
                <div class="card__header">
                    <div class="card__title">Pengajuan Flight Plan</div>
                </div>
                <form method="POST" class="form" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div class="form-group">
                            <label for="flight_no">No. Penerbangan</label>
                            <input type="text" id="flight_no" name="flight_no" placeholder="GA101" required>
                        </div>

                        <div class="form-group">
                            <label for="route">Rute</label>
                            <input type="text" id="route" name="route" placeholder="Jakarta - Dili" required>
                        </div>

                        <div class="form-group">
                            <label for="etd">ETD (Estimated Departure Time)</label>
                            <input type="datetime-local" id="etd" name="etd" required>
                        </div>

                        <div class="form-group">
                            <label for="eta">ETA (Estimated Arrival Time)</label>
                            <input type="datetime-local" id="eta" name="eta" required>
                        </div>

                        <div class="form-group" style="grid-column: 1 / -1;">
                            <label for="aircraft_reg">Aircraft Registration</label>
                            <input type="text" id="aircraft_reg" name="aircraft_reg" placeholder="PK-XXX">
                        </div>

                        <div class="form-group" style="grid-column: 1 / -1;">
                            <label for="doc">Dokumen Pendukung</label>
                            <input type="file" id="doc" name="doc" accept=".pdf,.jpg,.jpeg,.png">
                        </div>
                    </div>

                    <button type="submit" class="btn btn--primary">Kirim Flight Plan</button>
                </form>
            </div>

            <div class="card">
                <div class="card__header">
                    <div class="card__title">Riwayat Flight Plan</div>
                </div>

                <?php if (empty($plans)): ?>
                <div class="empty-state">
                    <div class="empty-state__message">Belum ada pengajuan flight plan</div>
                </div>
                <?php else: ?>

                <div style="overflow-x: auto;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>No. Penerbangan</th>
                                <th>Rute</th>
                                <th>ETD / ETA</th>
                                <th>Aircraft</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($plans as $plan): ?>
                            <tr>
                                <td><?= esc($plan['flight_no']) ?></td>
                                <td><?= esc($plan['route']) ?></td>
                                <td>
                                    <?= format_datetime($plan['etd']) ?><br>
                                    <?= format_datetime($plan['eta']) ?>
                                </td>
                                <td><?= esc($plan['aircraft_reg'] ?? '-') ?></td>
                                <td><span class="badge badge--<?= esc($plan['status']) ?>"><?= esc(ucfirst($plan['status'])) ?></span></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

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

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