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

require_login('admin');
$page_title = 'Ground Handling - ANATL Portal';

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

    $action = $_POST['action'] ?? '';

    if ($action === 'add_flight') {
        $flight_no = trim($_POST['flight_no'] ?? '');
        $airline = trim($_POST['airline'] ?? '');
        $arrival_dt = trim($_POST['arrival_dt'] ?? '');
        $origin = trim($_POST['origin'] ?? '');
        $pax_count = intval($_POST['pax_count'] ?? 0);

        if ($flight_no && $airline && $arrival_dt && $origin) {
            $user_id = $_SESSION['user_id'];
            $stmt = $conn->prepare('INSERT INTO irregular_flights (flight_no, airline, arrival_dt, origin, pax_count, created_by) VALUES (?, ?, ?, ?, ?, ?)');
            $stmt->bind_param('ssssii', $flight_no, $airline, $arrival_dt, $origin, $pax_count, $user_id);

            if ($stmt->execute()) {
                set_flash('success', 'Penerbangan non-reguler berhasil ditambahkan');
            } else {
                set_flash('error', 'Gagal menambahkan penerbangan');
            }
            $stmt->close();
        } else {
            set_flash('error', 'Semua field harus diisi');
        }
    }

    header('Location: ' . BASE_URL . '/admin/ground-handling.php');
    exit;
}

// Get irregular flights
$flights = [];
$result = $conn->query('SELECT * FROM irregular_flights ORDER BY arrival_dt DESC LIMIT 20');
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $flights[] = $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 Admin</div>
            <a href="<?= BASE_URL ?>/admin/index.php" class="sidebar-item">📊 Dashboard</a>
            <a href="<?= BASE_URL ?>/admin/users.php" class="sidebar-item">👥 Kelola User</a>
            <a href="<?= BASE_URL ?>/admin/slot.php" class="sidebar-item">✈️ Slot Time</a>
            <a href="<?= BASE_URL ?>/admin/flight-plan.php" class="sidebar-item">📋 Flight Plan</a>
            <a href="<?= BASE_URL ?>/admin/tenant.php" class="sidebar-item">🏢 Tenant</a>
            <a href="<?= BASE_URL ?>/admin/ground-handling.php" class="sidebar-item sidebar-item--active">🚗 Ground Handler</a>
            <a href="<?= BASE_URL ?>/admin/cms.php" class="sidebar-item">📰 CMS</a>
        </div>

        <div class="portal__content">
            <h1 style="color: #003A70; margin-bottom: 32px;">Ground Handling</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">Tambah Penerbangan Non-Reguler</div>
                </div>
                <form method="POST" class="form">
                    <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
                    <input type="hidden" name="action" value="add_flight">

                    <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" required>
                        </div>
                        <div class="form-group">
                            <label for="airline">Maskapai</label>
                            <input type="text" id="airline" name="airline" required>
                        </div>
                        <div class="form-group">
                            <label for="arrival_dt">Waktu Tiba</label>
                            <input type="datetime-local" id="arrival_dt" name="arrival_dt" required>
                        </div>
                        <div class="form-group">
                            <label for="origin">Asal</label>
                            <input type="text" id="origin" name="origin" required>
                        </div>
                        <div class="form-group">
                            <label for="pax_count">Jumlah Penumpang</label>
                            <input type="number" id="pax_count" name="pax_count" min="0">
                        </div>
                        <button type="submit" class="btn btn--success" style="align-self: flex-end;">Tambah Penerbangan</button>
                    </div>
                </form>
            </div>

            <div class="card">
                <div class="card__header">
                    <div class="card__title">Daftar Penerbangan Non-Reguler</div>
                </div>

                <div style="overflow-x: auto;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>No. Penerbangan</th>
                                <th>Maskapai</th>
                                <th>Asal</th>
                                <th>Waktu Tiba</th>
                                <th>Penumpang</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($flights as $flight): ?>
                            <tr>
                                <td><?= esc($flight['flight_no']) ?></td>
                                <td><?= esc($flight['airline']) ?></td>
                                <td><?= esc($flight['origin']) ?></td>
                                <td><?= format_datetime($flight['arrival_dt']) ?></td>
                                <td><?= $flight['pax_count'] ?></td>
                                <td><a href="#" class="btn btn--small btn--secondary">Lihat Invoice</a></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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