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

$is_admin = $_SESSION['is_admin'] ?? 0;
// Mendapatkan ID Subkomponen dari URL
$subkomponen_id = isset($_GET['subkomponen_id']) ? (int)$_GET['subkomponen_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 Detail Kegiatan.</div>';
    include_once 'footer.php';
    exit();
}

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

// Ambil Nama Subkomponen dan seluruh hierarki di atasnya
$info = [
    'nama_subkomponen' => 'Subkomponen Tidak Ditemukan', 
    'komponen_id' => 0,
    'subkegiatan_id' => 0,
    'kegiatan_id' => 0,
    'program_id' => 0,
    'nama_komponen' => 'N/A',
    'nama_subkegiatan' => 'N/A',
    'nama_kegiatan' => 'N/A',
    'nama_program' => 'N/A'
];

$sql_info = "SELECT sbk.nama_subkomponen, 
                    kp.id AS komponen_id, kp.nama_komponen,
                    sk.id AS subkegiatan_id, sk.nama_subkegiatan, 
                    k.id AS kegiatan_id, k.nama_kegiatan, 
                    p.id AS program_id, p.nama_program
             FROM subkomponen sbk
             JOIN komponen kp ON sbk.komponen_id = kp.id
             JOIN subkegiatan sk ON kp.subkegiatan_id = sk.id
             JOIN kegiatan k ON sk.kegiatan_id = k.id
             JOIN program p ON k.program_id = p.id
             WHERE sbk.id = ? AND sbk.tahun_aktif_id = ?";
$stmt_info = $conn->prepare($sql_info);
$stmt_info->bind_param("ii", $subkomponen_id, $tahun_aktif_id);
$stmt_info->execute();
$result_info = $stmt_info->get_result();

if ($result_info->num_rows > 0) {
    $info = $result_info->fetch_assoc();
} else {
    echo '<div class="alert alert-danger">Subkomponen tidak ditemukan untuk tahun aktif ini.</div>';
    include_once 'footer.php';
    exit();
}
$stmt_info->close();


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

    if ($action == 'add' && $nama_detail) {
        // PERUBAHAN DB: Hanya perlu subkomponen_id dan tahun_aktif_id
        $sql = "INSERT INTO detail_kegiatan (subkomponen_id, tahun_aktif_id, nama_detail) VALUES (?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iis", $subkomponen_id, $tahun_aktif_id, $nama_detail);
        if ($stmt->execute()) {
            $_SESSION['msg'] = ['type' => 'success', 'text' => 'Detail Kegiatan berhasil ditambahkan.'];
        } else {
            $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Gagal menambahkan Detail Kegiatan: ' . $stmt->error];
        }
        $stmt->close();
    } elseif ($action == 'delete' && $detail_kegiatan_id > 0) {
        $sql = "DELETE FROM detail_kegiatan WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $detail_kegiatan_id);
        if ($stmt->execute()) {
            $_SESSION['msg'] = ['type' => 'success', 'text' => 'Detail Kegiatan berhasil dihapus.'];
        } else {
            $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Gagal menghapus Detail Kegiatan (Pastikan tidak ada Aktivitas Kerja yang merujuk).'];
        }
        $stmt->close();
    }
    // Redirect ke halaman ini setelah aksi
    header("Location: detail_kegiatan_list.php?subkomponen_id=" . $subkomponen_id);
    exit();
}

// --- 2. AMBIL DATA DETAIL KEGIATAN ---
$detail_kegiatan_list = null;
$sql = "SELECT id, nama_detail FROM detail_kegiatan WHERE subkomponen_id = ? AND tahun_aktif_id = ? ORDER BY id ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $subkomponen_id, $tahun_aktif_id);
$stmt->execute();
$detail_kegiatan_list = $stmt->get_result();
$stmt->close();
?>

    <h2>Manajemen Detail Kegiatan</h2>
    <h5 class="text-secondary">Program: <?php echo htmlspecialchars($info['nama_program']); ?> &gt; Kegiatan: <?php echo htmlspecialchars($info['nama_kegiatan']); ?></h5>
    <h5 class="text-secondary">Subkegiatan: <?php echo htmlspecialchars($info['nama_subkegiatan']); ?> &gt; Komponen: <?php echo htmlspecialchars($info['nama_komponen']); ?></h5>
    <h5 class="text-primary">Subkomponen: <?php echo htmlspecialchars($info['nama_subkomponen']); ?></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="#addDetailKegiatanModal">
        <i class="bi bi-plus-circle"></i> Tambah Detail Kegiatan Baru
    </button>
    <a href="subkomponen_list.php?komponen_id=<?php echo $info['komponen_id']; ?>" class="btn btn-secondary mb-3">
        <i class="bi bi-arrow-left"></i> Kembali ke Subkomponen
    </a>

    <div class="table-responsive">
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nama Detail Kegiatan</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($detail_kegiatan_list && $detail_kegiatan_list->num_rows > 0): ?>
                    <?php while ($detail = $detail_kegiatan_list->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo $detail['id']; ?></td>
                        <td><?php echo htmlspecialchars($detail['nama_detail']); ?></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 Detail Kegiatan <?php echo htmlspecialchars($detail['nama_detail']); ?>?');">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="detail_kegiatan_id" value="<?php echo $detail['id']; ?>">
                                <button type="submit" class="btn btn-sm btn-danger">
                                    <i class="bi bi-trash"></i> Hapus
                                </button>
                            </form>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="3" class="text-center">Tidak ada Detail Kegiatan yang tersedia untuk Subkomponen ini.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

<div class="modal fade" id="addDetailKegiatanModal" tabindex="-1" aria-labelledby="addDetailKegiatanModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" action="detail_kegiatan_list.php?subkomponen_id=<?php echo $subkomponen_id; ?>">
                <div class="modal-header">
                    <h5 class="modal-title" id="addDetailKegiatanModalLabel">Tambah Detail 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_detail" class="form-label">Nama Detail Kegiatan</label>
                        <input type="text" class="form-control" id="nama_detail" name="nama_detail" 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 Detail Kegiatan</button>
                </div>
            </form>
        </div>
    </div>
</div>

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