<?php
// admin/kandidat.php
include_once 'init.php'; // Otak kita

$page_title = 'Data Kandidat';
$page_icon = 'bi-people-fill';

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

// Definisikan direktori
$target_dir_foto = "../assets/img/kandidat/";
$target_dir_banner = "../assets/img/banner/";

// Buat direktori jika belum ada
if (!is_dir($target_dir_foto)) {
    mkdir($target_dir_foto, 0755, true);
}
if (!is_dir($target_dir_banner)) {
    mkdir($target_dir_banner, 0755, true);
}

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

// Hanya proses aksi jika TAHUN AKTIF sudah ada
if ($id_tahun_aktif) {
    try {
        if ($action === 'tambah_kandidat') {
            $foto_filename = null;
            if (isset($_FILES['foto_paslon']) && $_FILES['foto_paslon']['error'] == 0) {
                $foto_filename = uniqid() . '_' . basename($_FILES["foto_paslon"]["name"]);
                move_uploaded_file($_FILES["foto_paslon"]["tmp_name"], $target_dir_foto . $foto_filename);
            }

            $stmt = $pdo->prepare(
                "INSERT INTO kandidat (id_tahun_fk, no_urut, nama_ketua, kelas_ketua, nama_wakil, kelas_wakil, visi, misi, slogan, foto_paslon) 
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
            );
            $stmt->execute([
                $id_tahun_aktif, 
                $_POST['no_urut'], 
                $_POST['nama_ketua'], 
                $_POST['kelas_ketua'],
                $_POST['nama_wakil'],
                $_POST['kelas_wakil'],
                $_POST['visi'], 
                $_POST['misi'], 
                $_POST['slogan'],
                $foto_filename
            ]);
            $_SESSION['message'] = '<div class="alert alert-success">Kandidat baru berhasil ditambahkan.</div>';
        }

        if ($action === 'update_kandidat') {
            $foto_filename = $_POST['foto_lama'];
            if (isset($_FILES['foto_paslon']) && $_FILES['foto_paslon']['error'] == 0) {
                if ($foto_filename && file_exists($target_dir_foto . $foto_filename)) {
                    unlink($target_dir_foto . $foto_filename);
                }
                $foto_filename = uniqid() . '_' . basename($_FILES["foto_paslon"]["name"]);
                move_uploaded_file($_FILES["foto_paslon"]["tmp_name"], $target_dir_foto . $foto_filename);
            }

            $stmt = $pdo->prepare(
                "UPDATE kandidat SET 
                    no_urut = ?, 
                    nama_ketua = ?, 
                    kelas_ketua = ?, 
                    nama_wakil = ?, 
                    kelas_wakil = ?, 
                    visi = ?, 
                    misi = ?, 
                    slogan = ?,
                    foto_paslon = ? 
                 WHERE id_kandidat = ?"
            );
            $stmt->execute([
                $_POST['no_urut'], 
                $_POST['nama_ketua'], 
                $_POST['kelas_ketua'],
                $_POST['nama_wakil'], 
                $_POST['kelas_wakil'],
                $_POST['visi'], 
                $_POST['misi'], 
                $_POST['slogan'],
                $foto_filename, 
                $_POST['id_kandidat']
            ]);
            $_SESSION['message'] = '<div class="alert alert-success">Data kandidat berhasil diperbarui.</div>';
        }

        // === LOGIKA UNTUK UPLOAD BANNER ===
        if ($action === 'update_banner') {
            $id_kandidat_banner = $_POST['id_kandidat_banner'];
            $banner_lama = $_POST['banner_lama'];
            $banner_filename = $banner_lama; 

            if (isset($_FILES['file_banner']) && $_FILES['file_banner']['error'] == 0) {
                $allowed_types = ['image/jpeg', 'image/png', 'image/bmp', 'application/pdf'];
                $file_type = mime_content_type($_FILES['file_banner']['tmp_name']);
                
                if (in_array($file_type, $allowed_types)) {
                    if ($banner_lama && file_exists($target_dir_banner . $banner_lama)) {
                        unlink($target_dir_banner . $banner_lama);
                    }
                    $ext = pathinfo(basename($_FILES["file_banner"]["name"]), PATHINFO_EXTENSION);
                    $banner_filename = 'banner_' . $id_kandidat_banner . '_' . uniqid() . '.' . $ext;
                    move_uploaded_file($_FILES["file_banner"]["tmp_name"], $target_dir_banner . $banner_filename);
                    
                    $stmt_banner = $pdo->prepare("UPDATE kandidat SET file_banner = ? WHERE id_kandidat = ?");
                    $stmt_banner->execute([$banner_filename, $id_kandidat_banner]);
                    $_SESSION['message'] = '<div class="alert alert-success">Banner kampanye berhasil diunggah/diperbarui.</div>';
                
                } else {
                    $_SESSION['message'] = '<div class="alert alert-danger">Gagal: Tipe file tidak diizinkan. Harap unggah PDF, JPG, PNG, atau BMP.</div>';
                }
            } else {
                 $_SESSION['message'] = '<div class="alert alert-danger">Gagal: Terjadi kesalahan saat mengunggah file. Pastikan file dipilih.</div>';
            }
        }
        
        // =================================================================
        // === LOGIKA BARU UNTUK HAPUS BANNER ===
        // =================================================================
        if ($action === 'hapus_banner' && isset($_GET['id'])) {
            $id_kandidat_hapus_banner = $_GET['id'];
            
            // 1. Ambil nama file banner dari DB
            $stmt_get_banner = $pdo->prepare("SELECT file_banner FROM kandidat WHERE id_kandidat = ?");
            $stmt_get_banner->execute([$id_kandidat_hapus_banner]);
            $banner_file = $stmt_get_banner->fetchColumn();

            if ($banner_file) {
                // 2. Hapus file fisik jika ada
                $file_path = $target_dir_banner . $banner_file;
                if (file_exists($file_path)) {
                    unlink($file_path);
                }
                
                // 3. Set kolom di DB menjadi NULL
                $stmt_clear_banner = $pdo->prepare("UPDATE kandidat SET file_banner = NULL WHERE id_kandidat = ?");
                $stmt_clear_banner->execute([$id_kandidat_hapus_banner]);
                
                $_SESSION['message'] = '<div class="alert alert-success">Banner kampanye berhasil dihapus.</div>';
            } else {
                $_SESSION['message'] = '<div class="alert alert-warning">Tidak ada banner yang bisa dihapus.</div>';
            }
        }
        // =================================================================
        // === AKHIR LOGIKA BARU ===
        // =================================================================

        if ($action === 'hapus_kandidat' && isset($_GET['id'])) {
            $stmt_files = $pdo->prepare("SELECT foto_paslon, file_banner FROM kandidat WHERE id_kandidat = ?");
            $stmt_files->execute([$_GET['id']]);
            $files = $stmt_files->fetch(PDO::FETCH_ASSOC);

            if ($files['foto_paslon'] && file_exists($target_dir_foto . $files['foto_paslon'])) {
                unlink($target_dir_foto . $files['foto_paslon']);
            }
            if ($files['file_banner'] && file_exists($target_dir_banner . $files['file_banner'])) {
                unlink($target_dir_banner . $files['file_banner']);
            }

            $stmt = $pdo->prepare("DELETE FROM kandidat WHERE id_kandidat = ?");
            $stmt->execute([$_GET['id']]);
            $_SESSION['message'] = '<div class="alert alert-success">Kandidat (termasuk foto dan banner) berhasil dihapus.</div>';
        }
    } catch (PDOException $e) {
        if ($e->errorInfo[1] == 1062) {
            $_SESSION['message'] = '<div class="alert alert-danger">Gagal: Nomor urut sudah digunakan untuk tahun ini.</div>';
        } else {
            $_SESSION['message'] = '<div class="alert alert-danger">Terjadi kesalahan: ' . $e->getMessage() . '</div>';
        }
    }
}

if ($action) {
    header("Location: kandidat.php");
    exit();
}

// =========================================================================================
// == AMBIL DATA UNTUK DITAMPILKAN
// =========================================================================================
$kandidat_list = [];
if ($id_tahun_aktif) {
    $stmt_kandidat = $pdo->prepare("SELECT * FROM kandidat WHERE id_tahun_fk = ? ORDER BY no_urut ASC");
    $stmt_kandidat->execute([$id_tahun_aktif]);
    $kandidat_list = $stmt_kandidat->fetchAll();
}

include 'header.php';
?>

<style>
    .table-kandidat {
        table-layout: fixed; 
        width: 100%;
    }
    .table-kandidat th,
    .table-kandidat td {
        word-wrap: break-word; 
        vertical-align: middle;
    }
    
    .table-kandidat .col-no-urut { width: 7%; }
    .table-kandidat .col-foto { width: 17%; }
    .table-kandidat .col-ketua { width: 14%; }
    .table-kandidat .col-wakil { width: 14%; }
    .table-kandidat .col-visi { width: 19%; } 
    .table-kandidat .col-misi { width: 19%; } 
    .table-kandidat .col-aksi { width: 10%; }

    .visi-misi-cell {
        font-size: 0.85rem; 
        line-height: 1.4;   
    }
    
    .view-banner-link {
        font-size: 0.8rem;
        font-weight: bold;
        text-decoration: none;
    }
    
    #viewBannerModalBody iframe {
        min-height: 70vh;
        border: none;
    }

    /* === KODE RESPONSIVE === */
    @media (max-width: 767px) {
        .table-kandidat { font-size: 0.875rem; }
        .table-kandidat thead { display: none; }
        .mobile-kandidat-header {
            display: flex;
            align-items: center;
            gap: 1rem;
            margin-bottom: 1rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e9ecef;
        }

      


        .mobile-kandidat-no {
            background: #007bff;
            color: white;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 1.1rem;
            flex-shrink: 0;
        }
        .mobile-kandidat-info { flex: 1; }
        .mobile-kandidat-nama {
            font-weight: 600;
            font-size: 1rem;
            margin-bottom: 0.25rem;
        }
        .mobile-kandidat-kelas {
            font-size: 0.875rem;
            color: #6c757d;
        }
        .btn-group-mobile {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
            justify-content: center;
        }
        .btn-group-mobile .btn {
            font-size: 0.8rem;
            padding: 0.4rem 0.6rem;
        }
        .btn-tambah-manual-text {
            display: none;
        }
    }
</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 kandidat 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>

            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#tambahKandidatModal">
                <i class="bi bi-plus-circle me-1"></i> <span class="btn-tambah-manual-text"> Tambah Kandidat</span>
            </button>
        </div>

        <div class="table-responsive p-3">
            <table class="table table-striped table-hover table-bordered table-kandidat d-none d-md-table">
                <thead class="table-light">
                    <tr>
                        <th class="col-no-urut">No <br> Urut</th>
                        <th class="col-foto">Foto & Slogan</th>
                        <th class="col-ketua">Nama Ketua</th>
                        <th class="col-wakil">Nama Wakil</th>
                        <th class="col-visi">Visi</th>
                        <th class="col-misi">Misi</th>
                        <th class="col-aksi">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($kandidat_list)): ?>
                        <tr>
                            <td colspan="7" class="text-center">Belum ada data kandidat untuk tahun ini.</td>
                        </tr>
                    <?php endif; ?>
                    <?php foreach ($kandidat_list as $k) : ?>
                        <tr>
                            <td class="text-center col-no-urut">
                                <span class="fs-4 fw-bold"><?= htmlspecialchars($k['no_urut']) ?></span>
                            </td>
                            
                            <td class="text-center col-foto">
                                <?php if ($k['foto_paslon']): ?>
                                    <img src="<?= $target_dir_foto . htmlspecialchars($k['foto_paslon']) ?>" alt="Foto" height="80" class="rounded">
                                <?php else: ?>
                                    <i class="bi bi-person-bounding-box" style="font-size: 80px; color: #ccc;"></i>
                                <?php endif; ?>
                                
                                <?php if (!empty($k['slogan'])): ?>
                                    <div class="mt-2 fst-italic text-muted small">
                                        "<?= htmlspecialchars($k['slogan'] ?? '') ?>"
                                    </div>
                                <?php endif; ?>
                                
                                <?php if (!empty($k['file_banner'])): 
                                    $banner_path = $target_dir_banner . htmlspecialchars($k['file_banner']);
                                    $is_pdf = strtolower(pathinfo($banner_path, PATHINFO_EXTENSION)) == 'pdf';
                                ?>
                                    <a href="#" class="view-banner-link" 
                                       data-banner-path="<?= $banner_path ?>" 
                                       data-is-pdf="<?= $is_pdf ? 'true' : 'false' ?>"
                                       data-nama-kandidat="<?= htmlspecialchars($k['nama_ketua'] . ' & ' . $k['nama_wakil']) ?>"
                                       data-bs-toggle="modal" data-bs-target="#viewBannerModal">
                                       <i class="bi bi-file-earmark-richtext"></i> Lihat Kampanye
                                    </a>
                                <?php endif; ?>
                            </td>
                            
                            <td class="col-ketua">
                                <strong><?= htmlspecialchars($k['nama_ketua']) ?></strong>
                                <br><small class="text-muted fst-italic">Kelas : <?= htmlspecialchars($k['kelas_ketua']) ?></small>
                            </td>
                            <td class="col-wakil">
                                <strong><?= htmlspecialchars($k['nama_wakil']) ?></strong>
                                <br><small class="text-muted fst-italic">Kelas : <?= htmlspecialchars($k['kelas_wakil']) ?></small>
                            </td>
                            
                            <td class="visi-misi-cell col-visi">
                                <?= nl2br(htmlspecialchars($k['visi'])) ?>
                            </td>
                            
                            <td class="visi-misi-cell col-misi">
                                <?= nl2br(htmlspecialchars($k['misi'])) ?>
                            </td>
                            
                            <td class="text-nowrap col-aksi text-center">
                                <button class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#editKandidatModal<?= $k['id_kandidat'] ?>" title="Edit Data Kandidat">
                                    <i class="bi bi-pencil-square"></i>
                                </button>
                                <a href="kandidat.php?action=hapus_kandidat&id=<?= $k['id_kandidat'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Yakin ingin menghapus kandidat ini?')" title="Hapus Kandidat">
                                    <i class="bi bi-trash"></i>
                                </a>
                                <br><br>
                                
                                <div class="btn-group btn-group-sm" role="group">
                                    <?php if (empty($k['file_banner'])): ?>
                                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#bannerModal" 
                                                data-id-kandidat="<?= $k['id_kandidat'] ?>" 
                                                data-nama-kandidat="<?= htmlspecialchars($k['nama_ketua'] . ' & ' . $k['nama_wakil']) ?>" 
                                                data-banner-lama=""
                                                title="Upload Banner Kampanye">
                                            <i class="bi bi-upload"></i>
                                        </button>
                                    <?php else: ?>
                                        <button class="btn btn-info" data-bs-toggle="modal" data-bs-target="#bannerModal" 
                                                data-id-kandidat="<?= $k['id_kandidat'] ?>" 
                                                data-nama-kandidat="<?= htmlspecialchars($k['nama_ketua'] . ' & ' . $k['nama_wakil']) ?>" 
                                                data-banner-lama="<?= htmlspecialchars($k['file_banner']) ?>"
                                                title="Edit Banner Kampanye">
                                            <i class="bi bi-file-earmark-arrow-up-fill"></i> 
                                        </button> 
                                        <a href="kandidat.php?action=hapus_banner&id=<?= $k['id_kandidat'] ?>" class="btn btn-danger" 
                                           onclick="return confirm('Yakin ingin menghapus banner kampanye ini?')" title="Hapus Banner">
                                            <i class="bi bi-x-lg"></i>
                                        </a>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <div class="d-md-none">
                <?php if (empty($kandidat_list)): ?>
                    <div class="text-center py-4">
                        <i class="bi bi-people display-4 text-muted"></i>
                        <p class="text-muted mt-2">Belum ada data kandidat untuk tahun ini.</p>
                    </div>
                <?php endif; ?>
                
                <?php foreach ($kandidat_list as $k) : ?>
                    <div class="card mb-3 shadow-sm">
                        <div class="card-body">
                            <div class="mobile-kandidat-header">
                                <div class="mobile-kandidat-no">
                                    <?= htmlspecialchars($k['no_urut']) ?>
                                </div>
                                <div class="mobile-kandidat-info">
                                    <div class="mobile-kandidat-nama">
                                        <?= htmlspecialchars($k['nama_ketua']) ?> & <?= htmlspecialchars($k['nama_wakil']) ?>
                                    </div>
                                    <div class="mobile-kandidat-kelas">
                                        <?= htmlspecialchars($k['kelas_ketua']) ?> & <?= htmlspecialchars($k['kelas_wakil']) ?>
                                    </div>
                                </div>
                                <div class="text-center">
                                    <?php if ($k['foto_paslon']): ?>
                                        <img src="<?= $target_dir_foto . htmlspecialchars($k['foto_paslon']) ?>" alt="Foto" height="50" class="rounded">
                                    <?php else: ?>
                                        <i class="bi bi-person-bounding-box" style="font-size: 40px; color: #ccc;"></i>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <?php if (!empty($k['slogan'])): ?>
                            <div class="mb-3 text-center fst-italic text-muted">
                                "<?= htmlspecialchars($k['slogan'] ?? '') ?>"
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($k['file_banner'])): 
                                $banner_path = $target_dir_banner . htmlspecialchars($k['file_banner']);
                                $is_pdf = strtolower(pathinfo($banner_path, PATHINFO_EXTENSION)) == 'pdf';
                            ?>
                                <div class="text-center mb-3">
                                    <a href="#" class="view-banner-link" 
                                       data-banner-path="<?= $banner_path ?>" 
                                       data-is-pdf="<?= $is_pdf ? 'true' : 'false' ?>"
                                       data-nama-kandidat="<?= htmlspecialchars($k['nama_ketua'] . ' & ' . $k['nama_wakil']) ?>"
                                       data-bs-toggle="modal" data-bs-target="#viewBannerModal">
                                       <i class="bi bi-file-earmark-richtext"></i> Lihat Kampanye
                                    </a>
                                </div>
                            <?php endif; ?>

                            <div class="mb-3">
                                <strong class="d-block mb-1">Visi:</strong>
                                <div class="bg-light p-2 rounded small">
                                    <?= nl2br(htmlspecialchars($k['visi'])) ?>
                                </div>
                            </div>
                            <div class="mb-3">
                                <strong class="d-block mb-1">Misi:</strong>
                                <div class="bg-light p-2 rounded small">
                                    <?= nl2br(htmlspecialchars($k['misi'])) ?>
                                </div>
                            </div>

                            <div class="btn-group-mobile">
                                <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#editKandidatModal<?= $k['id_kandidat'] ?>" title="Edit Data Kandidat">
                                    <i class="bi bi-pencil-square"></i>
                                </button>
                                <a href="kandidat.php?action=hapus_kandidat&id=<?= $k['id_kandidat'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Yakin ingin menghapus kandidat ini?')" title="Hapus Kandidat">
                                    <i class="bi bi-trash"></i>
                                </a>

                                <?php if (empty($k['file_banner'])): ?>
                                    <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#bannerModal" 
                                            data-id-kandidat="<?= $k['id_kandidat'] ?>" 
                                            data-nama-kandidat="<?= htmlspecialchars($k['nama_ketua'] . ' & ' . $k['nama_wakil']) ?>" 
                                            data-banner-lama=""
                                            title="Upload Banner Kampanye">
                                        <i class="bi bi-upload"></i>
                                    </button>
                                <?php else: ?>
                                    <button class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#bannerModal" 
                                            data-id-kandidat="<?= $k['id_kandidat'] ?>" 
                                            data-nama-kandidat="<?= htmlspecialchars($k['nama_ketua'] . ' & ' . $k['nama_wakil']) ?>" 
                                            data-banner-lama="<?= htmlspecialchars($k['file_banner']) ?>"
                                            title="Edit Banner Kampanye">
                                        <i class="bi bi-file-earmark-arrow-up-fill"></i>
                                    </button>
                                    <a href="kandidat.php?action=hapus_banner&id=<?= $k['id_kandidat'] ?>" class="btn btn-sm btn-danger" 
                                       onclick="return confirm('Yakin ingin menghapus banner kampanye ini?')" title="Hapus Banner">
                                        <i class="bi bi-x-lg"></i>
                                    </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <?php foreach ($kandidat_list as $k) : ?>
        <div class="modal fade" id="editKandidatModal<?= $k['id_kandidat'] ?>" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <form method="POST" action="kandidat.php" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="update_kandidat">
                        <input type="hidden" name="id_kandidat" value="<?= $k['id_kandidat'] ?>">
                        <input type="hidden" name="foto_lama" value="<?= htmlspecialchars($k['foto_paslon']) ?>">
                        
                        <div class="modal-header">
                            <h5 class="modal-title">Edit Kandidat No Urut <?= htmlspecialchars($k['no_urut']) ?></h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                             <div class="row">
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">No Urut</label>
                                    <input type="number" class="form-control" name="no_urut" value="<?= htmlspecialchars($k['no_urut']) ?>" required>
                                </div>
                                <div class="col-md-9 mb-3">
                                    <label class="form-label">Foto Paslon (Biarkan kosong jika tidak diubah)</label>
                                    <input class="form-control" type="file" name="foto_paslon" accept="image/*">
                                </div>
                                
                                <div class="col-12 mb-3">
                                    <label class="form-label">Slogan</label>
                                    <input type="text" class="form-control" name="slogan" value="<?= htmlspecialchars($k['slogan'] ?? '') ?>" placeholder="Contoh: Jujur, Adil, Sejahtera">
                                </div>

                                <div class="col-md-8 mb-3">
                                    <label class="form-label">Nama Ketua</label>
                                    <input type="text" class="form-control" name="nama_ketua" value="<?= htmlspecialchars($k['nama_ketua']) ?>" required>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Kelas Ketua</label>
                                    <input type="text" class="form-control" name="kelas_ketua" value="<?= htmlspecialchars($k['kelas_ketua']) ?>" placeholder="Contoh: XII-A">
                                </div>
                                <div class="col-md-8 mb-3">
                                    <label class="form-label">Nama Wakil</label>
                                    <input type="text" class="form-control" name="nama_wakil" value="<?= htmlspecialchars($k['nama_wakil']) ?>" required>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Kelas Wakil</label>
                                    <input type="text" class="form-control" name="kelas_wakil" value="<?= htmlspecialchars($k['kelas_wakil']) ?>" placeholder="Contoh: XI-B">
                                </div>
                                <div class="col-12 mb-3">
                                    <label class="form-label">Visi</label>
                                    <textarea class="form-control" name="visi" rows="3"><?= htmlspecialchars($k['visi']) ?></textarea>
                                </div>
                                <div class="col-12 mb-3">
                                    <label class="form-label">Misi</label>
                                    <textarea class="form-control" name="misi" rows="5"><?= htmlspecialchars($k['misi']) ?></textarea>
                                </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">Simpan Perubahan</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    <?php endforeach; ?>

    <div class="modal fade" id="tambahKandidatModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form method="POST" action="kandidat.php" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="tambah_kandidat">
                    <div class="modal-header">
                        <h5 class="modal-title">Tambah Kandidat Baru (Tahun <?= htmlspecialchars($tahun_aktif_display) ?>)</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                         <div class="row">
                            <div class="col-md-3 mb-3">
                                <label class="form-label">No Urut</label>
                                <input type="number" class="form-control" name="no_urut" required>
                            </div>
                            <div class="col-md-9 mb-3">
                                <label class="form-label">Foto Paslon</label>
                                <input class="form-control" type="file" name="foto_paslon" accept="image/*">
                            </div>
                            
                            <div class="col-12 mb-3">
                                <label class="form-label">Slogan</label>
                                <input type="text" class="form-control" name="slogan" placeholder="Contoh: Jujur, Adil, Sejahtera">
                            </div>

                            <div class="col-md-8 mb-3">
                                <label class="form-label">Nama Ketua</label>
                                <input type="text" class="form-control" name="nama_ketua" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Kelas Ketua</label>
                                <input type="text" class="form-control" name="kelas_ketua" placeholder="Contoh: XII-A">
                            </div>
                            <div class="col-md-8 mb-3">
                                <label class="form-label">Nama Wakil</label>
                                <input type="text" class="form-control" name="nama_wakil" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Kelas Wakil</label>
                                <input type="text" class="form-control" name="kelas_wakil" placeholder="Contoh: XI-B">
                            </div>
                            <div class="col-12 mb-3">
                                <label class="form-label">Visi</label>
                                <textarea class="form-control" name="visi" rows="3"></textarea>
                            </div>
                            <div class="col-12 mb-3">
                                <label class="form-label">Misi</label>
                                <textarea class="form-control" name="misi" rows="5"></textarea>
                            </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">Simpan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <div class="modal fade" id="bannerModal" tabindex="-1" aria-labelledby="bannerModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST" action="kandidat.php" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="update_banner">
                    <input type="hidden" name="id_kandidat_banner" id="banner_id_kandidat">
                    <input type="hidden" name="banner_lama" id="banner_lama">
                    
                    <div class="modal-header">
                        <h5 class="modal-title" id="bannerModalLabel">Upload Banner Kampanye</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <p>Kandidat: <strong id="banner_nama_kandidat"></strong></p>
                        <div class="mb-3">
                            <label for="file_banner_input" class="form-label">Pilih file (PDF, JPG, PNG, BMP)</label>
                            <input class="form-control" type="file" name="file_banner" id="file_banner_input" 
                                   accept=".pdf,.jpg,.jpeg,.png,.bmp" required>
                        </div>
                        <small class="text-muted">Mengunggah file baru akan otomatis mengganti file banner yang lama.</small>
                    </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 Banner</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <div class="modal fade" id="viewBannerModal" tabindex="-1" aria-labelledby="viewBannerModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewBannerModalLabel">Banner Kampanye</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="viewBannerModalBody" style="padding:0;">
                    </div>
            </div>
        </div>
    </div>

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

include 'footer.php';
?>

<script>
document.addEventListener("DOMContentLoaded", function() {
    
    // 1. Logika untuk Modal Upload/Edit Banner
    const bannerModal = document.getElementById('bannerModal');
    if (bannerModal) {
        bannerModal.addEventListener('show.bs.modal', function(event) {
            const button = event.relatedTarget;
            const idKandidat = button.getAttribute('data-id-kandidat');
            const namaKandidat = button.getAttribute('data-nama-kandidat');
            const bannerLama = button.getAttribute('data-banner-lama');
            
            const modalTitle = bannerModal.querySelector('.modal-title');
            const modalNamaKandidat = bannerModal.querySelector('#banner_nama_kandidat');
            const modalIdInput = bannerModal.querySelector('#banner_id_kandidat');
            const modalBannerLamaInput = bannerModal.querySelector('#banner_lama');
            
            modalNamaKandidat.textContent = namaKandidat;
            modalIdInput.value = idKandidat;
            modalBannerLamaInput.value = bannerLama;
            
            if (bannerLama) {
                modalTitle.textContent = 'Edit Banner Kampanye';
            } else {
                modalTitle.textContent = 'Upload Banner Kampanye';
            }
        });
    }
    
    // 2. Logika untuk Modal Lihat Banner
    const viewBannerModal = document.getElementById('viewBannerModal');
    if (viewBannerModal) {
        viewBannerModal.addEventListener('show.bs.modal', function(event) {
            const link = event.relatedTarget;
            const bannerPath = link.getAttribute('data-banner-path');
            const isPdf = link.getAttribute('data-is-pdf') === 'true';
            const namaKandidat = link.getAttribute('data-nama-kandidat');
            
            const modalTitle = viewBannerModal.querySelector('#viewBannerModalLabel');
            const modalBody = viewBannerModal.querySelector('#viewBannerModalBody');
            
            modalTitle.textContent = 'Banner Kampanye: ' + namaKandidat;
            modalBody.innerHTML = ''; 
            
            if (isPdf) {
                const iframe = document.createElement('iframe');
                iframe.src = bannerPath;
                iframe.width = '100%';
                iframe.height = '600px'; 
                modalBody.appendChild(iframe);
            } else {
                const img = document.createElement('img');
                img.src = bannerPath;
                img.className = 'img-fluid';
                img.alt = 'Banner Kampanye';
                modalBody.appendChild(img);
            }
        });
    }
});
</script>