<?php
// admin/panitia_pemilihan.php
include_once 'init.php'; // Termasuk koneksi DB, PDO, dan variabel seperti $id_tahun_aktif

$page_title = 'Panitia Pemilihan';
$page_icon = 'bi-person-badge-fill';

$action = $_POST['action'] ?? $_GET['action'] ?? '';
$message = $_SESSION['message'] ?? '';
unset($_SESSION['message']);

// Definisikan Opsi Jabatan di sini agar bisa dipakai di form
$jabatan_sekolah_options = [
    'Kepala Madrasah',
    'Wakamad Kesiswaan',
    'Pembina OSIM',
    'Anggota OSIM',
    'Lainnya'
];

// =========================================================================================
// == LOGIKA PROSES (TAMBAH, UPDATE, HAPUS, UPLOAD FOTO)
// =========================================================================================

// Hanya proses aksi jika TAHUN AKTIF sudah ada
if ($id_tahun_aktif) {
    try {
        if ($action === 'tambah_panitia') {
            $stmt = $pdo->prepare(
                "INSERT INTO panitia (id_tahun_fk, nama_panitia, jabatan_sekolah, jabatan_panitia) 
                 VALUES (?, ?, ?, ?)"
            );
            $stmt->execute([
                $id_tahun_aktif, // <-- Ditautkan ke tahun aktif
                $_POST['nama_panitia'],
                $_POST['jabatan_sekolah'],
                $_POST['jabatan_panitia']
            ]);
            $_SESSION['message'] = '<div class="alert alert-success">Anggota panitia baru berhasil ditambahkan.</div>';
        }

        if ($action === 'update_panitia') {
            $stmt = $pdo->prepare(
                "UPDATE panitia SET nama_panitia = ?, jabatan_sekolah = ?, jabatan_panitia = ?
                 WHERE id_panitia = ?"
            );
            $stmt->execute([
                $_POST['nama_panitia'],
                $_POST['jabatan_sekolah'],
                $_POST['jabatan_panitia'],
                $_POST['id_panitia']
            ]);
            $_SESSION['message'] = '<div class="alert alert-success">Data panitia berhasil diperbarui.</div>';
        }

        if ($action === 'upload_foto' && isset($_POST['id_panitia']) && isset($_FILES['foto_panitia'])) {
            $id = $_POST['id_panitia'];
            $file = $_FILES['foto_panitia'];
            
            // Validasi file
            $allowed_types = ['image/jpeg', 'image/jpg', 'image/png'];
            $max_size = 2 * 1024 * 1024; // 2MB
            
            if ($file['error'] === UPLOAD_ERR_OK) {
                if (in_array($file['type'], $allowed_types) && $file['size'] <= $max_size) {
                    // Ambil data panitia lama untuk hapus foto lama
                    $stmt = $pdo->prepare("SELECT foto_panitia FROM panitia WHERE id_panitia = ?");
                    $stmt->execute([$id]);
                    $old_data = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    // Hapus foto lama jika ada
                    if ($old_data && $old_data['foto_panitia']) {
                        $old_file = '../assets/img/panitia/' . $old_data['foto_panitia'];
                        if (file_exists($old_file)) {
                            unlink($old_file);
                        }
                    }
                    
                    // Generate nama file unik
                    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                    $new_filename = 'panitia_' . $id . '_' . time() . '.' . $extension;
                    $upload_path = '../assets/img/panitia/' . $new_filename;
                    
                    // Buat direktori jika belum ada
                    if (!is_dir('../assets/img/panitia/')) {
                        mkdir('../assets/img/panitia/', 0755, true);
                    }
                    
                    // Upload file
                    if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                        // Update database
                        $stmt = $pdo->prepare("UPDATE panitia SET foto_panitia = ? WHERE id_panitia = ?");
                        $stmt->execute([$new_filename, $id]);
                        $_SESSION['message'] = '<div class="alert alert-success">Foto berhasil diupload.</div>';
                    } else {
                        $_SESSION['message'] = '<div class="alert alert-danger">Gagal mengupload foto.</div>';
                    }
                } else {
                    $_SESSION['message'] = '<div class="alert alert-danger">File harus berupa JPG/PNG dan maksimal 2MB.</div>';
                }
            } else {
                $_SESSION['message'] = '<div class="alert alert-danger">Error saat upload file.</div>';
            }
        }

        if ($action === 'hapus_foto' && isset($_GET['id'])) {
            $id = $_GET['id'];
            
            // Ambil nama file foto
            $stmt = $pdo->prepare("SELECT foto_panitia FROM panitia WHERE id_panitia = ?");
            $stmt->execute([$id]);
            $data = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($data && $data['foto_panitia']) {
                $file_path = '../assets/img/panitia/' . $data['foto_panitia'];
                if (file_exists($file_path)) {
                    unlink($file_path);
                }
                
                // Update database
                $stmt = $pdo->prepare("UPDATE panitia SET foto_panitia = NULL WHERE id_panitia = ?");
                $stmt->execute([$id]);
                $_SESSION['message'] = '<div class="alert alert-success">Foto berhasil dihapus.</div>';
            }
        }

        if ($action === 'hapus_panitia' && isset($_GET['id'])) {
            $id = $_GET['id'];
            
            // Hapus foto jika ada
            $stmt = $pdo->prepare("SELECT foto_panitia FROM panitia WHERE id_panitia = ?");
            $stmt->execute([$id]);
            $data = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($data && $data['foto_panitia']) {
                $file_path = '../assets/img/panitia/' . $data['foto_panitia'];
                if (file_exists($file_path)) {
                    unlink($file_path);
                }
            }
            
            // Hapus data panitia
            $stmt = $pdo->prepare("DELETE FROM panitia WHERE id_panitia = ?");
            $stmt->execute([$id]);
            $_SESSION['message'] = '<div class="alert alert-success">Data panitia berhasil dihapus.</div>';
        }
    } catch (PDOException $e) {
        $_SESSION['message'] = '<div class="alert alert-danger">Terjadi kesalahan: ' . $e->getMessage() . '</div>';
    }
}

if ($action) {
    // Redirect untuk menghindari pengiriman data ulang (Post/Redirect/Get pattern)
    header("Location: panitia_pemilihan.php");
    exit();
}

// =========================================================================================
// == AMBIL DATA UNTUK DITAMPILKAN
// =========================================================================================
$panitia_list = [];
if ($id_tahun_aktif) {
    
    // Menggunakan ORDER BY FIELD() untuk mengurutkan berdasarkan daftar kustom jabatan
    $query_panitia = "
        SELECT * FROM panitia 
        WHERE id_tahun_fk = ? 
        ORDER BY 
            FIELD(jabatan_panitia, 
                'Pelindung', 
                'Penanggung Jawab', 
                'Pembina', 
                'Ketua Panitia', 
                'Sekretaris', 
                'Anggota'
            ), 
            nama_panitia ASC
    ";

    $stmt_panitia = $pdo->prepare($query_panitia);
    $stmt_panitia->execute([$id_tahun_aktif]);
    $panitia_list = $stmt_panitia->fetchAll();
}

include 'header.php';
?>

<style>
    /* Style Desktop (Fixed) */
    .table-panitia {
        table-layout: fixed; 
        width: 100%;
    }
    .table-panitia th,
    .table-panitia td {
        word-wrap: break-word; 
        vertical-align: middle;
    }
    
    /* Atur persentase lebar kolom desktop */
    .table-panitia .col-no { width: 5%; }
    .table-panitia .col-nama { width: 30%; }
    .table-panitia .col-jabatan-sekolah { width: 20%; }
    .table-panitia .col-jabatan-panitia { width: 25%; }
    .table-panitia .col-aksi { width: 20%; text-align: center; }
    .table-panitia td:last-child { text-align: center; } 


    /* === KODE RESPONSIVE (COMPACT & AUTO-FIT) === */
    @media (max-width: 767px) {
        .table-panitia {
            font-family: 'Arial Narrow', Arial, sans-serif; 
            font-size: 13px;
            table-layout: auto; 
            width: 100%;
        }
        
        .table-panitia .btn-sm {
            font-size: 12px;
            padding: 2px 5px;
        }

        .table-panitia th, 
        .table-panitia td {
            padding: 0.35rem 0.25rem; 
            white-space: normal; 
            vertical-align: middle;
        }

        .btn-tambah-manual-text {
            display: none;
        }
        /* Pada mobile, kembalikan rata kiri */
        .table-panitia .col-aksi { text-align: left; width: auto; }
        .table-panitia td:last-child { text-align: left; }
    }
</style>
<?= $message ?>

<?php if (!$id_tahun_aktif): ?>
    <div class="alert alert-danger shadow-sm">
        <h4 class="alert-heading"><i class="bi bi-exclamation-triangle-fill"></i> Tidak Ada Tahun Aktif!</h4>
        <p>Anda tidak dapat mengelola panitia sebelum memilih tahun pemilihan yang aktif.</p>
        <hr>
        <p class="mb-0">Silakan pergi ke <a href="pengaturan.php?tab=tahun" class="alert-link">Manajemen Tahun</a> untuk mengaktifkan satu tahun pemilihan.</p>
    </div>
<?php else: ?>
    <div class="content-card">
        <div class="card-header-custom">
            
            <span class="badge bg-info text-dark"><h6>Tahun Pemilihan : <?= htmlspecialchars($tahun_aktif_display) ?></h6></span>
            
            <?php if (!empty($panitia_list)): ?>
            <a href="cetak_id_panitia.php?mode=massal" target="_blank" class="btn btn-secondary me-2" title="Cetak Semua ID Card (4 per A4)">
                <i class="bi bi-printer me-1"></i> Cetak Kartu Semua
            </a>
            <?php endif; ?>
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#tambahPanitiaModal">
                <i class="bi bi-plus-circle me-1"></i> <span class="btn-tambah-manual-text">Tambah Panitia</span>
            </button>

        </div>

        <div class="table-responsive p-3">
            <table class="table table-striped table-hover table-bordered table-panitia">
                <thead class="table-light">
                    <tr>
                        <th class="col-no">No</th>
                        <th class="col-nama">Nama</th>
                        <th class="col-jabatan-sekolah">Jabatan (di Sekolah)</th>
                        <th class="col-jabatan-panitia">Jabatan (di Panitia)</th>
                        <th class="col-aksi">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($panitia_list)): ?>
                        <tr>
                            <td colspan="5" class="text-center">Belum ada data panitia untuk tahun ini.</td>
                        </tr>
                    <?php endif; ?>
                    <?php $i = 1; ?>
                    <?php foreach ($panitia_list as $p) : ?>
                        <tr>
                            <td><?= $i++ ?></td>
                            <td><?= htmlspecialchars($p['nama_panitia']) ?></td>
                            <td><?= htmlspecialchars($p['jabatan_sekolah']) ?></td>
                            <td><?= htmlspecialchars($p['jabatan_panitia']) ?></td>
                            <td class="text-nowrap">
                                <button class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#editPanitiaModal<?= $p['id_panitia'] ?>" title="Edit Data">
                                    <i class="bi bi-pencil-square"></i>
                                </button>
                                <?php if (!empty($p['foto_panitia'])): ?>
                                <button class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#uploadFotoModal<?= $p['id_panitia'] ?>" title="Edit Foto">
                                    <i class="bi bi-image"></i>
                                </button>
                                <?php else: ?>
                                <button class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#uploadFotoModal<?= $p['id_panitia'] ?>" title="Upload Foto">
                                    <i class="bi bi-upload"></i>
                                </button>
                                <?php endif; ?>
                                <a href="panitia_pemilihan.php?action=hapus_panitia&id=<?= $p['id_panitia'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Yakin ingin menghapus anggota panitia <?= htmlspecialchars($p['nama_panitia']) ?>?')" title="Hapus Data">
                                    <i class="bi bi-trash"></i>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Modal Edit Panitia -->
    <?php foreach ($panitia_list as $p) : ?>
        <div class="modal fade" id="editPanitiaModal<?= $p['id_panitia'] ?>" tabindex="-1" aria-labelledby="editPanitiaLabel<?= $p['id_panitia'] ?>" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <form method="POST" action="panitia_pemilihan.php">
                        <input type="hidden" name="action" value="update_panitia">
                        <input type="hidden" name="id_panitia" value="<?= $p['id_panitia'] ?>">
                        
                        <div class="modal-header">
                            <h5 class="modal-title" id="editPanitiaLabel<?= $p['id_panitia'] ?>">Edit Data Panitia: <?= htmlspecialchars($p['nama_panitia']) ?></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 class="form-label">Nama Lengkap</label>
                                <input type="text" class="form-control" name="nama_panitia" value="<?= htmlspecialchars($p['nama_panitia']) ?>" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Jabatan (di Sekolah)</label>
                                <select class="form-select" name="jabatan_sekolah">
                                    <?php foreach ($jabatan_sekolah_options as $jabatan): ?>
                                        <option value="<?= $jabatan ?>" <?= ($p['jabatan_sekolah'] == $jabatan) ? 'selected' : '' ?>>
                                            <?= $jabatan ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Jabatan (di Panitia)</label>
                                <input type="text" class="form-control" name="jabatan_panitia" value="<?= htmlspecialchars($p['jabatan_panitia']) ?>" placeholder="Contoh: Ketua, Sekretaris, Anggota">
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                            <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Modal Upload Foto -->
        <div class="modal fade" id="uploadFotoModal<?= $p['id_panitia'] ?>" tabindex="-1" aria-labelledby="uploadFotoLabel<?= $p['id_panitia'] ?>" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <form method="POST" action="panitia_pemilihan.php" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="upload_foto">
                        <input type="hidden" name="id_panitia" value="<?= $p['id_panitia'] ?>">
                        
                        <div class="modal-header">
                            <h5 class="modal-title" id="uploadFotoLabel<?= $p['id_panitia'] ?>">Upload Foto: <?= htmlspecialchars($p['nama_panitia']) ?></h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <?php if ($p['foto_panitia']): ?>
                                <div class="text-center mb-3">
                                    <img src="../assets/img/panitia/<?= htmlspecialchars($p['foto_panitia']) ?>" 
                                         alt="Foto <?= htmlspecialchars($p['nama_panitia']) ?>" 
                                         class="img-thumbnail" 
                                         style="max-width: 200px; max-height: 250px;">
                                    <div class="mt-2">
                                        <a href="panitia_pemilihan.php?action=hapus_foto&id=<?= $p['id_panitia'] ?>" 
                                           class="btn btn-sm btn-danger" 
                                           onclick="return confirm('Yakin ingin menghapus foto ini?')">
                                            <i class="bi bi-trash"></i> Hapus Foto
                                        </a>
                                    </div>
                                </div>
                            <?php endif; ?>
                            <div class="mb-3">
                                <label class="form-label">Pilih Foto (JPG/PNG, Max 2MB)</label>
                                <input type="file" class="form-control" name="foto_panitia" accept="image/jpeg,image/jpg,image/png" required>
                                <div class="form-text">Rekomendasi: Foto ukuran 3x4 atau portrait</div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                            <button type="submit" class="btn btn-primary">Upload Foto</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    <?php endforeach; ?>

    <!-- Modal Tambah Panitia -->
    <div class="modal fade" id="tambahPanitiaModal" tabindex="-1" aria-labelledby="tambahPanitiaLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST" action="panitia_pemilihan.php">
                    <input type="hidden" name="action" value="tambah_panitia">
                    <div class="modal-header">
                        <h5 class="modal-title" id="tambahPanitiaLabel">Tambah Panitia Baru (Tahun <?= htmlspecialchars($tahun_aktif_display) ?>)</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 class="form-label">Nama Lengkap</label>
                            <input type="text" class="form-control" name="nama_panitia" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Jabatan (di Sekolah)</label>
                            <select class="form-select" name="jabatan_sekolah">
                                <?php foreach ($jabatan_sekolah_options as $jabatan): ?>
                                    <option value="<?= $jabatan ?>"><?= $jabatan ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Jabatan (di Panitia)</label>
                            <input type="text" class="form-control" name="jabatan_panitia" placeholder="Contoh: Ketua, Sekretaris, Anggota">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-primary">Simpan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

<?php
endif; // Akhir dari 'if ($id_tahun_aktif)'

include 'footer.php';
?>