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

require_login('admin');
$page_title = 'CMS Management - ANATL Portal';

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

    $action = $_POST['action'] ?? '';
    $title = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $type = trim($_POST['type'] ?? '');
    $lang = trim($_POST['lang'] ?? 'id');
    $published = isset($_POST['published']) ? 1 : 0;

    if ($action === 'add' && $title && $content && $type) {
        $user_id = $_SESSION['user_id'];
        $stmt = $conn->prepare('INSERT INTO cms_posts (title, content, type, lang, published, created_by) VALUES (?, ?, ?, ?, ?, ?)');
        $stmt->bind_param('ssissi', $title, $content, $type, $lang, $published, $user_id);

        if ($stmt->execute()) {
            set_flash('success', 'Post berhasil ditambahkan');
        } else {
            set_flash('error', 'Gagal menambahkan post');
        }
        $stmt->close();
    }

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

$posts = [];
$result = $conn->query('SELECT * FROM cms_posts ORDER BY created_at DESC');
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $posts[] = $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">🚗 Ground Handler</a>
            <a href="<?= BASE_URL ?>/admin/cms.php" class="sidebar-item sidebar-item--active">📰 CMS</a>
        </div>

        <div class="portal__content">
            <h1 style="color: #003A70; margin-bottom: 32px;">CMS Management</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 Post Baru</div>
                </div>
                <form method="POST" class="form">
                    <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
                    <input type="hidden" name="action" value="add">

                    <div class="form-group">
                        <label for="type">Tipe</label>
                        <select id="type" name="type" required>
                            <option value="">-- Pilih Tipe --</option>
                            <option value="news">Berita</option>
                            <option value="announcement">Pengumuman</option>
                            <option value="notam">NOTAM</option>
                        </select>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div class="form-group">
                            <label for="lang">Bahasa</label>
                            <select id="lang" name="lang" required>
                                <option value="id">Indonesia</option>
                                <option value="en">English</option>
                                <option value="pt">Português</option>
                                <option value="tet">Tetum</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="published">
                                <input type="checkbox" id="published" name="published" value="1">
                                Publish Sekarang
                            </label>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="title">Judul</label>
                        <input type="text" id="title" name="title" required>
                    </div>

                    <div class="form-group">
                        <label for="content">Konten</label>
                        <textarea id="content" name="content" style="min-height: 300px;" required></textarea>
                    </div>

                    <button type="submit" class="btn btn--success">Tambah Post</button>
                </form>
            </div>

            <div class="card">
                <div class="card__header">
                    <div class="card__title">Daftar Post</div>
                </div>

                <div style="overflow-x: auto;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Judul</th>
                                <th>Tipe</th>
                                <th>Bahasa</th>
                                <th>Status</th>
                                <th>Tanggal</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($posts as $post): ?>
                            <tr>
                                <td><?= esc($post['title']) ?></td>
                                <td><span class="badge badge--submitted"><?= esc($post['type']) ?></span></td>
                                <td><?= esc(strtoupper($post['lang'])) ?></td>
                                <td><span class="badge badge--<?= $post['published'] ? 'approved' : 'submitted' ?>">
                                    <?= $post['published'] ? 'Published' : 'Draft' ?>
                                </span></td>
                                <td><?= format_datetime($post['created_at']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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