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

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

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

    $incident_date = trim($_POST['incident_date'] ?? '');
    $category = trim($_POST['category'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $location = trim($_POST['location'] ?? '');
    $is_anonymous = isset($_POST['is_anonymous']) ? 1 : 0;

    if ($incident_date && $category && $description) {
        $doc_path = handle_upload('doc', 'safety');

        $final_user_id = $is_anonymous ? null : $user_id;
        $stmt = $conn->prepare('INSERT INTO safety_reports (user_id, incident_date, category, description, location, is_anonymous, doc_path) VALUES (?, ?, ?, ?, ?, ?, ?)');
        $stmt->bind_param('issssss', $final_user_id, $incident_date, $category, $description, $location, $is_anonymous, $doc_path);

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

    header('Location: ' . BASE_URL . '/maskapai/safety.php');
    exit;
}

$reports = [];
$result = $conn->query("SELECT * FROM safety_reports WHERE user_id = $user_id ORDER BY created_at DESC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $reports[] = $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">📋 Flight Plan</a>
            <a href="<?= BASE_URL ?>/maskapai/safety.php" class="sidebar-item sidebar-item--active">⚠️ Safety Report</a>
        </div>

        <div class="portal__content">
            <h1 style="color: #003A70; margin-bottom: 32px;">Safety Reporting</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">Lapor Safety Incident</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="incident_date">Tanggal Incident</label>
                            <input type="date" id="incident_date" name="incident_date" required>
                        </div>

                        <div class="form-group">
                            <label for="category">Kategori</label>
                            <select id="category" name="category" required>
                                <option value="">-- Pilih Kategori --</option>
                                <option value="bird_strike">Bird Strike</option>
                                <option value="ground_damage">Ground Damage</option>
                                <option value="fuel_spill">Fuel Spill</option>
                                <option value="near_miss">Near Miss</option>
                                <option value="other">Other</option>
                            </select>
                        </div>

                        <div class="form-group" style="grid-column: 1 / -1;">
                            <label for="location">Lokasi</label>
                            <input type="text" id="location" name="location" placeholder="Terminal, Runway, dll">
                        </div>

                        <div class="form-group" style="grid-column: 1 / -1;">
                            <label for="description">Deskripsi</label>
                            <textarea id="description" name="description" required></textarea>
                        </div>

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

                        <div class="form-group" style="grid-column: 1 / -1;">
                            <label for="is_anonymous">
                                <input type="checkbox" id="is_anonymous" name="is_anonymous">
                                Laporkan secara anonim
                            </label>
                        </div>
                    </div>

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

            <div class="card">
                <div class="card__header">
                    <div class="card__title">Riwayat Safety Reports</div>
                </div>

                <?php if (empty($reports)): ?>
                <div class="empty-state">
                    <div class="empty-state__message">Belum ada safety report</div>
                </div>
                <?php else: ?>

                <div style="overflow-x: auto;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Tanggal</th>
                                <th>Kategori</th>
                                <th>Lokasi</th>
                                <th>Status</th>
                                <th>Anonim</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($reports as $report): ?>
                            <tr>
                                <td><?= format_date($report['incident_date']) ?></td>
                                <td><?= esc(ucfirst(str_replace('_', ' ', $report['category']))) ?></td>
                                <td><?= esc($report['location'] ?? '-') ?></td>
                                <td><span class="badge badge--<?= esc($report['status']) ?>"><?= esc(ucfirst(str_replace('_', ' ', $report['status']))) ?></span></td>
                                <td><?= $report['is_anonymous'] ? 'Ya' : 'Tidak' ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

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

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