<?php
// program_list.php
// FILE INI HARUS DISIMPAN SEBAGAI program_list.php

// Memuat header, session, koneksi, dan sidebar
// Pastikan ob_start(); sudah ditambahkan di header.php jika Anda mengalami warning "Headers already sent"
include_once 'header.php';

// Variabel dari header.php: $conn, $is_admin
// Asumsikan function getTahunAktifId() sudah tersedia dan mengembalikan ID tahun aktif
$tahun_aktif_id = getTahunAktifId($conn);

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

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

    // Aksi Tambah (ADD)
    if ($action == 'add' && $nama_program && $tahun_aktif_id) {
        $sql = "INSERT INTO program (tahun_aktif_id, nama_program) VALUES (?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("is", $tahun_aktif_id, $nama_program);
        if ($stmt->execute()) {
            $_SESSION['msg'] = ['type' => 'success', 'text' => 'Program berhasil ditambahkan.'];
        } else {
            $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Gagal menambahkan Program: ' . $stmt->error];
        }
        $stmt->close();
        
    // Aksi Edit/Update (EDIT)
    } elseif ($action == 'edit' && $id > 0 && $nama_program) {
        $sql = "UPDATE program SET nama_program = ? WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("si", $nama_program, $id);
        if ($stmt->execute()) {
            $_SESSION['msg'] = ['type' => 'success', 'text' => 'Program berhasil diperbarui.'];
        } else {
            $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Gagal memperbarui Program: ' . $stmt->error];
        }
        $stmt->close();

    // Aksi Hapus (DELETE)
    } elseif ($action == 'delete' && $id > 0) {
        $sql = "DELETE FROM program WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            $_SESSION['msg'] = ['type' => 'success', 'text' => 'Program berhasil dihapus.'];
        } else {
            $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Gagal menghapus Program (Pastikan tidak ada Kegiatan yang merujuk).'];
        }
        $stmt->close();
    }
    header("Location: program_list.php");
    exit();
}

// --- 2. AMBIL DATA PROGRAM ---
$program_list = null;
$tahun_aktif_info = 'N/A';
if ($tahun_aktif_id) {
    // Ambil tahun_aktif info
    $sql_tahun = "SELECT tahun FROM tahun_aktif WHERE id = ?";
    $stmt_tahun = $conn->prepare($sql_tahun);
    $stmt_tahun->bind_param("i", $tahun_aktif_id);
    $stmt_tahun->execute();
    $result_tahun = $stmt_tahun->get_result();
    $tahun_aktif_info = $result_tahun->fetch_assoc()['tahun'];
    $stmt_tahun->close();

    // Ambil semua Program
    $sql = "SELECT id, nama_program FROM program WHERE tahun_aktif_id = ? ORDER BY id ASC";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $tahun_aktif_id);
    $stmt->execute();
    $program_list = $stmt->get_result();
    $stmt->close();
}
?>

    <h2>Manajemen Program Kegiatan BPS (Tahun <?php echo $tahun_aktif_info; ?>)</h2>
    <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="#addProgramModal">
        <i class="bi bi-plus-circle"></i> Tambah Program Baru
    </button>

    <div class="table-responsive">
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nama Program</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($program_list && $program_list->num_rows > 0): ?>
                    <?php while ($program = $program_list->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo $program['id']; ?></td>
                        <td><?php echo htmlspecialchars($program['nama_program']); ?></td>
                        <td>
                            <button 
                                class="btn btn-sm btn-warning me-1 edit-btn" 
                                data-bs-toggle="modal" 
                                data-bs-target="#editProgramModal"
                                data-id="<?php echo $program['id']; ?>"
                                data-nama="<?php echo htmlspecialchars($program['nama_program']); ?>">
                                <i class="bi bi-pencil"></i> Edit
                            </button>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('Yakin hapus Program <?php echo htmlspecialchars($program['nama_program']); ?>? (Semua Kegiatan di bawahnya akan ikut terhapus)');">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?php echo $program['id']; ?>">
                                <button type="submit" class="btn btn-sm btn-danger">
                                    <i class="bi bi-trash"></i> Hapus
                                </button>
                            </form>
                            <a href="kegiatan_list.php?program_id=<?php echo $program['id']; ?>" class="btn btn-sm btn-info ms-2">
                                <i class="bi bi-arrow-right"></i> Kelola Kegiatan
                            </a>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="3" class="text-center">Tidak ada Program yang tersedia untuk Tahun Aktif ini.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

<hr>

<div class="modal fade" id="addProgramModal" tabindex="-1" aria-labelledby="addProgramModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" action="program_list.php">
                <div class="modal-header">
                    <h5 class="modal-title" id="addProgramModalLabel">Tambah Program 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_program" class="form-label">Nama Program</label>
                        <input type="text" class="form-control" id="nama_program" name="nama_program" 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 Program</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="editProgramModal" tabindex="-1" aria-labelledby="editProgramModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" action="program_list.php">
                <div class="modal-header">
                    <h5 class="modal-title" id="editProgramModalLabel">Edit Program</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="edit_nama_program" class="form-label">Nama Program</label>
                        <input type="text" class="form-control" id="edit_nama_program" name="nama_program" required>
                        <input type="hidden" name="action" value="edit">
                        <input type="hidden" name="id" id="edit_program_id"> </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-warning">Simpan Perubahan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // === JavaScript untuk mengisi data ke Modal Edit ===
    document.addEventListener('DOMContentLoaded', function () {
        const modalEdit = document.getElementById('editProgramModal');

        modalEdit.addEventListener('show.bs.modal', function (event) {
            // Tombol yang memicu modal (tombol 'Edit')
            const button = event.relatedTarget;
            
            // Ambil data dari data-attribute tombol
            const programId = button.getAttribute('data-id');
            const programNama = button.getAttribute('data-nama');

            // Perbarui konten modal
            const modalTitle = modalEdit.querySelector('.modal-title');
            const inputId = modalEdit.querySelector('#edit_program_id');
            const inputNama = modalEdit.querySelector('#edit_nama_program');

            modalTitle.textContent = 'Edit Program ID: ' + programId;
            inputId.value = programId;
            inputNama.value = programNama;
        });
    });
</script>

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