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

$is_admin = $_SESSION['is_admin'] ?? 0;
$kegiatan_id = isset($_GET['kegiatan_id']) ? (int)$_GET['kegiatan_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 Subkegiatan.</div>';
    include_once 'footer.php';
    exit();
}

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

// Ambil Nama Kegiatan dan Program
$kegiatan_info = ['nama_kegiatan' => 'Kegiatan Tidak Ditemukan', 'program_id' => 0];
$sql_info = "SELECT k.nama_kegiatan, k.program_id, p.nama_program 
             FROM kegiatan k 
             JOIN program p ON k.program_id = p.id
             WHERE k.id = ? AND k.tahun_aktif_id = ?";
$stmt_info = $conn->prepare($sql_info);
$stmt_info->bind_param("ii", $kegiatan_id, $tahun_aktif_id);
$stmt_info->execute();
$result_info = $stmt_info->get_result();
if ($result_info->num_rows > 0) {
    $kegiatan_info = $result_info->fetch_assoc();
} else {
    echo '<div class="alert alert-danger">Kegiatan tidak ditemukan untuk tahun aktif ini.</div>';
    include_once 'footer.php';
    exit();
}
$stmt_info->close();


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

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

// --- 2. AMBIL DATA SUBKEGIATAN ---
$subkegiatan_list = null;
$sql = "SELECT id, nama_subkegiatan FROM subkegiatan WHERE kegiatan_id = ? AND tahun_aktif_id = ? ORDER BY id ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $kegiatan_id, $tahun_aktif_id);
$stmt->execute();
$subkegiatan_list = $stmt->get_result();
$stmt->close();
?>

    <h2>Manajemen Subkegiatan</h2>
    <h5 class="text-secondary">Program: <?php echo htmlspecialchars($kegiatan_info['nama_program']); ?></h5>
    <h5 class="text-primary">Kegiatan: <?php echo htmlspecialchars($kegiatan_info['nama_kegiatan']); ?></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="#addSubkegiatanModal">
        <i class="bi bi-plus-circle"></i> Tambah Subkegiatan Baru
    </button>
    <a href="kegiatan_list.php?program_id=<?php echo $kegiatan_info['program_id']; ?>" class="btn btn-secondary mb-3">
        <i class="bi bi-arrow-left"></i> Kembali ke Kegiatan
    </a>

    <div class="table-responsive">
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nama Subkegiatan</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($subkegiatan_list && $subkegiatan_list->num_rows > 0): ?>
                    <?php while ($subkegiatan = $subkegiatan_list->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo $subkegiatan['id']; ?></td>
                        <td><?php echo htmlspecialchars($subkegiatan['nama_subkegiatan']); ?></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 Subkegiatan <?php echo htmlspecialchars($subkegiatan['nama_subkegiatan']); ?>?');">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="subkegiatan_id" value="<?php echo $subkegiatan['id']; ?>">
                                <button type="submit" class="btn btn-sm btn-danger">
                                    <i class="bi bi-trash"></i> Hapus
                                </button>
                            </form>
                            <a href="komponen_list.php?subkegiatan_id=<?php echo $subkegiatan['id']; ?>" class="btn btn-sm btn-info ms-2">
                                <i class="bi bi-arrow-right"></i> Kelola Komponen
                            </a>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="3" class="text-center">Tidak ada Subkegiatan yang tersedia untuk Kegiatan ini.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

<div class="modal fade" id="addSubkegiatanModal" tabindex="-1" aria-labelledby="addSubkegiatanModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" action="subkegiatan_list.php?kegiatan_id=<?php echo $kegiatan_id; ?>">
                <div class="modal-header">
                    <h5 class="modal-title" id="addSubkegiatanModalLabel">Tambah Subkegiatan 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_subkegiatan" class="form-label">Nama Subkegiatan</label>
                        <input type="text" class="form-control" id="nama_subkegiatan" name="nama_subkegiatan" 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 Subkegiatan</button>
                </div>
            </form>
        </div>
    </div>
</div>

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