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

require_login('admin');
$page_title = 'Approval Slot Time - ANATL Portal';

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

    $slot_id = intval($_POST['slot_id'] ?? 0);
    $action = $_POST['action'] ?? '';
    $admin_notes = trim($_POST['admin_notes'] ?? '');

    if ($slot_id && in_array($action, ['approved', 'rejected'])) {
        $stmt = $conn->prepare('UPDATE slot_requests SET status = ?, admin_notes = ?, updated_at = NOW() WHERE id = ?');
        $stmt->bind_param('ssi', $action, $admin_notes, $slot_id);
        $stmt->execute();
        $stmt->close();

        set_flash('success', 'Slot time berhasil ' . ($action === 'approved' ? 'disetujui' : 'ditolak'));
    }

    header('Location: ' . BASE_URL . '/admin/slot.php');
    exit;
}

// Get pending slots
$slots = [];
$result = $conn->query('
    SELECT sr.*, u.company_name, u.email
    FROM slot_requests sr
    JOIN users u ON sr.user_id = u.id
    WHERE sr.status IN ("submitted", "review")
    ORDER BY sr.created_at DESC
');
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $slots[] = $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 sidebar-item--active">✈️ 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">🚗 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;">Approval Slot Time</h1>

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

            <?php if (empty($slots)): ?>
            <div class="empty-state">
                <div class="empty-state__icon">✅</div>
                <div class="empty-state__message">Semua pengajuan slot time telah diproses</div>
            </div>
            <?php else: ?>

            <?php foreach ($slots as $slot): ?>
            <div class="card" style="margin-bottom: 24px;">
                <div class="card__header">
                    <div>
                        <div class="card__title"><?= esc($slot['flight_no']) ?></div>
                        <p style="color: #5A6A7A; font-size: 14px; margin-top: 4px;">
                            <?= esc($slot['company_name']) ?> • <?= format_date($slot['flight_date']) ?>
                        </p>
                    </div>
                    <span class="badge badge--<?= esc($slot['status']) ?>">
                        <?= esc(ucfirst($slot['status'])) ?>
                    </span>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 24px;">
                    <div>
                        <p style="color: #5A6A7A; font-size: 12px;">Tipe</p>
                        <p style="font-weight: 600;"><?= esc(ucfirst($slot['type'])) ?></p>
                    </div>
                    <div>
                        <p style="color: #5A6A7A; font-size: 12px;">Waktu Diminta</p>
                        <p style="font-weight: 600;"><?= $slot['requested_time'] ?></p>
                    </div>
                    <div>
                        <p style="color: #5A6A7A; font-size: 12px;">Tipe Aircraft</p>
                        <p style="font-weight: 600;"><?= esc($slot['aircraft_type'] ?? '-') ?></p>
                    </div>
                    <div>
                        <p style="color: #5A6A7A; font-size: 12px;">Email Maskapai</p>
                        <p style="font-weight: 600;"><?= esc($slot['email']) ?></p>
                    </div>
                </div>

                <form method="POST" style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
                    <input type="hidden" name="slot_id" value="<?= $slot['id'] ?>">

                    <div class="form-group">
                        <label for="notes_<?= $slot['id'] ?>">Catatan</label>
                        <textarea id="notes_<?= $slot['id'] ?>" name="admin_notes" placeholder="Catatan untuk maskapai..."></textarea>
                    </div>

                    <div style="display: flex; gap: 8px; align-items: flex-end;">
                        <button type="submit" name="action" value="approved" class="btn btn--success" style="flex: 1;">Setujui</button>
                        <button type="submit" name="action" value="rejected" class="btn btn--danger" style="flex: 1;">Tolak</button>
                    </div>
                </form>
            </div>
            <?php endforeach; ?>

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

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