<?php
// kegiatan_list.php
include_once 'header.php'; 

// Variabel dari header.php: $conn, $is_admin
$is_admin = $_SESSION['is_admin'] ?? 0;
// Mendapatkan ID Program dari URL
$program_id = isset($_GET['program_id']) ? (int)$_GET['program_id'] : 0;
$tahun_aktif_id = getTahunAktifId($conn); // Mengambil dari header.php

if ($is_admin != 1) {
    echo '<div class="alert alert-danger">Akses Ditolak: Hanya Admin yang dapat mengelola Kegiatan.</div>';
    include_once 'footer.php';
    exit();
}

// Cek apakah Program ID valid
if ($program_id == 0) {
    echo '<div class="alert alert-warning">Program tidak dipilih. Silakan kembali ke <a href="program_list.php">Daftar Program</a>.</div>';
    include_once 'footer.php';
    exit();
}

// Ambil Nama Program
$program_info = ['id' => $program_id, 'nama_program' => 'Program Tidak Ditemukan'];
$sql_program = "SELECT nama_program FROM program WHERE id = ? AND tahun_aktif_id = ?";
$stmt_program = $conn->prepare($sql_program);
$stmt_program->bind_param("ii", $program_id, $tahun_aktif_id);
$stmt_program->execute();
$result_program = $stmt_program->get_result();
if ($result_program->num_rows > 0) {
    $program_info['nama_program'] = $result_program->fetch_assoc()['nama_program'];
} else {
    echo '<div class="alert alert-danger">Program tidak ditemukan untuk tahun aktif ini.</div>';
    include_once 'footer.php';
    exit();
}
$stmt_program->close();


// --- 1. PROSES CRUD KEGIATAN (ADD/DELETE) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $nama_kegiatan = isset($_POST['nama_kegiatan']) ? trim($conn->real_escape_string($_POST['nama_kegiatan'])) : '';
    $kegiatan_id = isset($_POST['kegiatan_id']) ? (int)$_POST['kegiatan_id'] : 0;

    if ($action == 'add' && $nama_kegiatan) {
        // PERUBAHAN DB: Menambahkan tahun_aktif_id saat INSERT
        $sql = "INSERT INTO kegiatan (program_id, tahun_aktif_id, nama_kegiatan) VALUES (?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iis", $program_id, $tahun_aktif_id, $nama_kegiatan);
        if ($stmt->execute()) {
            $_SESSION['msg'] = ['type' => 'success', 'text' => 'Kegiatan berhasil ditambahkan.'];
        } else {
            $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Gagal menambahkan Kegiatan: ' . $stmt->error];
        }
        $stmt->close();
    } elseif ($action == 'delete' && $kegiatan_id > 0) {
        $sql = "DELETE FROM kegiatan WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $kegiatan_id);
        if ($stmt->execute()) {
            $_SESSION['msg'] = ['type' => 'success', 'text' => 'Kegiatan berhasil dihapus.'];
        } else {
            $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Gagal menghapus Kegiatan (Pastikan tidak ada Subkegiatan yang merujuk).'];
        }
        $stmt->close();
    }
    // Redirect ke halaman ini setelah aksi
    header("Location: kegiatan_list.php?program_id=" . $program_id);
    exit();
}

// --- 2. AMBIL DATA KEGIATAN ---
$kegiatan_list = null;
// Mengambil Kegiatan berdasarkan program_id DAN tahun_aktif_id
$sql = "SELECT id, nama_kegiatan FROM kegiatan WHERE program_id = ? AND tahun_aktif_id = ? ORDER BY id ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $program_id, $tahun_aktif_id);
$stmt->execute();
$kegiatan_list = $stmt->get_result();
$stmt->close();
?>

    <h2>Manajemen Kegiatan</h2>
    <h5 class="text-primary">Program: <?php echo htmlspecialchars($program_info['nama_program']); ?></h5>
    <hr>

    <?php if (isset($_SESSION['msg'])): ?>
        <div class="alert alert-<?php echo $_SESSION['msg']['type']; ?>"><?php echo $_SESSION['msg']['text']; ?></div>
        <?php unset($_SESSION['msg']); ?>
    <?php endif; ?>

    <button class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#addKegiatanModal">
        <i class="bi bi-plus-circle"></i> Tambah Kegiatan Baru
    </button>
    <a href="program_list.php" class="btn btn-secondary mb-3">
        <i class="bi bi-arrow-left"></i> Kembali ke Program
    </a>

    <div class="table-responsive">
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nama Kegiatan</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($kegiatan_list && $kegiatan_list->num_rows > 0): ?>
                    <?php while ($kegiatan = $kegiatan_list->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo $kegiatan['id']; ?></td>
                        <td><?php echo htmlspecialchars($kegiatan['nama_kegiatan']); ?></td>
                        <td>
                            <button class="btn btn-sm btn-warning me-1">
                                <i class="bi bi-pencil"></i> Edit
                            </button>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('Yakin hapus Kegiatan <?php echo htmlspecialchars($kegiatan['nama_kegiatan']); ?>?');">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="kegiatan_id" value="<?php echo $kegiatan['id']; ?>">
                                <button type="submit" class="btn btn-sm btn-danger">
                                    <i class="bi bi-trash"></i> Hapus
                                </button>
                            </form>
                            <a href="subkegiatan_list.php?kegiatan_id=<?php echo $kegiatan['id']; ?>" class="btn btn-sm btn-info ms-2">
                                <i class="bi bi-arrow-right"></i> Kelola Subkegiatan
                            </a>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="3" class="text-center">Tidak ada Kegiatan yang tersedia untuk Program ini.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

<div class="modal fade" id="addKegiatanModal" tabindex="-1" aria-labelledby="addKegiatanModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" action="kegiatan_list.php?program_id=<?php echo $program_id; ?>">
                <div class="modal-header">
                    <h5 class="modal-title" id="addKegiatanModalLabel">Tambah Kegiatan Baru</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="nama_kegiatan" class="form-label">Nama Kegiatan</label>
                        <input type="text" class="form-control" id="nama_kegiatan" name="nama_kegiatan" required>
                        <input type="hidden" name="action" value="add">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-primary">Simpan Kegiatan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php 
include_once 'footer.php'; 
?>