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

$is_admin = $_SESSION['is_admin'] ?? 0;
// Mendapatkan ID Subkegiatan dari URL
$subkegiatan_id = isset($_GET['subkegiatan_id']) ? (int)$_GET['subkegiatan_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 Komponen.</div>';
    include_once 'footer.php';
    exit();
}

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

// Ambil Nama Subkegiatan, Kegiatan, dan Program
$info = [
    'nama_subkegiatan' => 'Subkegiatan Tidak Ditemukan', 
    'kegiatan_id' => 0,
    'program_id' => 0,
    'nama_kegiatan' => 'N/A',
    'nama_program' => 'N/A'
];

$sql_info = "SELECT sk.nama_subkegiatan, k.id AS kegiatan_id, k.nama_kegiatan, p.id AS program_id, p.nama_program
             FROM subkegiatan sk
             JOIN kegiatan k ON sk.kegiatan_id = k.id
             JOIN program p ON k.program_id = p.id
             WHERE sk.id = ? AND sk.tahun_aktif_id = ?";
$stmt_info = $conn->prepare($sql_info);
$stmt_info->bind_param("ii", $subkegiatan_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">Subkegiatan tidak ditemukan untuk tahun aktif ini.</div>';
    include_once 'footer.php';
    exit();
}
$stmt_info->close();


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

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

// --- 2. AMBIL DATA KOMPONEN ---
$komponen_list = null;
$sql = "SELECT id, nama_komponen FROM komponen WHERE subkegiatan_id = ? AND tahun_aktif_id = ? ORDER BY id ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $subkegiatan_id, $tahun_aktif_id);
$stmt->execute();
$komponen_list = $stmt->get_result();
$stmt->close();
?>

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

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

<div class="modal fade" id="addKomponenModal" tabindex="-1" aria-labelledby="addKomponenModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" action="komponen_list.php?subkegiatan_id=<?php echo $subkegiatan_id; ?>">
                <div class="modal-header">
                    <h5 class="modal-title" id="addKomponenModalLabel">Tambah Komponen 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_komponen" class="form-label">Nama Komponen</label>
                        <input type="text" class="form-control" id="nama_komponen" name="nama_komponen" 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 Komponen</button>
                </div>
            </form>
        </div>
    </div>
</div>

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