<?= $this->extend('layout/default') ?>

<?= $this->section('content') ?>
<div class="card-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
    <h1 class="page-title" style="margin-bottom: 0;">Data Master Mahasiswa</h1>
    <div>
        <a href="<?= base_url('mahasiswa/create') ?>" class="btn btn-success" style="margin-right: 10px;">
            <i class='bx bx-plus'></i> Tambah Mahasiswa
        </a>
        <button type="button" class="btn btn-info" onclick="startBatchSync()" style="margin-right: 10px;">
            <i class='bx bx-cloud-download'></i> Sinkron Biodata Massal
        </button>
        <button type="button" class="btn btn-warning" onclick="syncWilayah()" style="margin-right: 10px;">
            <i class='bx bx-map-alt'></i> Sinkron Data Wilayah
        </button>
        <a href="<?= base_url('mahasiswa/sync') ?>" class="btn btn-warning" onclick="return confirm('Proses ini akan menarik data Utama Mahasiswa dari PDDIKTI. Lanjutkan?');">
            <i class='bx bx-refresh'></i> Sinkronisasi Utama PDDIKTI
        </a>
    </div>
</div>

<?php if (session()->getFlashdata('success')) : ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert" style="background-color: #d1fae5; color: #065f46; padding: 1rem; border-radius: 6px; margin-bottom: 1rem; border: 1px solid #a7f3d0;">
        <?= session()->getFlashdata('success') ?>
    </div>
<?php endif; ?>

<?php if (session()->getFlashdata('error')) : ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert" style="background-color: #fee2e2; color: #991b1b; padding: 1rem; border-radius: 6px; margin-bottom: 1rem; border: 1px solid #fecaca;">
        <?= session()->getFlashdata('error') ?>
    </div>
<?php endif; ?>

<div class="filter-section" style="background: white; padding: 1.5rem; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 1.5rem;">
    <form action="" method="GET" id="filterForm">
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; align-items: end;">
            
            <div class="form-group" style="margin: 0;">
                <label style="font-size: 0.85rem; font-weight: 600; color: #475569; margin-bottom: 5px; display: block;">Cari Mahasiswa</label>
                <div style="position: relative;">
                    <i class='bx bx-search' style="position: absolute; left: 10px; top: 10px; color: #94a3b8;"></i>
                    <input type="text" name="search" value="<?= esc($search) ?>" placeholder="Nama atau NIM..." style="width: 100%; padding: 8px 10px 8px 30px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 0.9rem;">
                </div>
            </div>

            <div class="form-group" style="margin: 0;">
                <label style="font-size: 0.85rem; font-weight: 600; color: #475569; margin-bottom: 5px; display: block;">Program Studi</label>
                <select name="prodi" style="width: 100%; padding: 8px 10px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 0.9rem; background: #fff;" onchange="document.getElementById('filterForm').submit();">
                    <option value="">Semua Program Studi</option>
                    <?php foreach($listProdi as $p): ?>
                        <option value="<?= $p['id'] ?>" <?= $prodi_id == $p['id'] ? 'selected' : '' ?>><?= $p['jenjang'] ?> <?= $p['nama_prodi'] ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group" style="margin: 0;">
                <label style="font-size: 0.85rem; font-weight: 600; color: #475569; margin-bottom: 5px; display: block;">Angkatan</label>
                <select name="angkatan" style="width: 100%; padding: 8px 10px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 0.9rem; background: #fff;" onchange="document.getElementById('filterForm').submit();">
                    <option value="">Semua Angkatan</option>
                    <?php foreach($listAngkatan as $a): ?>
                        <option value="<?= $a['angkatan'] ?>" <?= $angkatan == $a['angkatan'] ? 'selected' : '' ?>><?= $a['angkatan'] ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group" style="margin: 0;">
                <label style="font-size: 0.85rem; font-weight: 600; color: #475569; margin-bottom: 5px; display: block;">Status</label>
                <select name="status" style="width: 100%; padding: 8px 10px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 0.9rem; background: #fff;" onchange="document.getElementById('filterForm').submit();">
                    <option value="">Semua Status</option>
                    <?php foreach($listStatus as $s): ?>
                        <option value="<?= $s['status_mahasiswa'] ?>" <?= $status == $s['status_mahasiswa'] ? 'selected' : '' ?>><?= $s['status_mahasiswa'] ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group" style="margin: 0;">
                <label style="font-size: 0.85rem; font-weight: 600; color: #475569; margin-bottom: 5px; display: block;">Tampilkan</label>
                <div style="display: flex; gap: 10px;">
                    <select name="per_page" style="width: 80px; padding: 8px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 0.9rem; background: #fff;" onchange="document.getElementById('filterForm').submit();">
                        <option value="10" <?= $per_page == 10 ? 'selected' : '' ?>>10</option>
                        <option value="25" <?= $per_page == 25 ? 'selected' : '' ?>>25</option>
                        <option value="50" <?= $per_page == 50 ? 'selected' : '' ?>>50</option>
                        <option value="100" <?= $per_page == 100 ? 'selected' : '' ?>>100</option>
                    </select>
                    <button type="submit" class="btn btn-primary" style="padding: 8px 15px;"><i class='bx bx-search-alt-2'></i> Cari</button>
                    <?php if(!empty($search) || !empty($prodi_id) || !empty($angkatan) || !empty($status)): ?>
                        <a href="<?= base_url('mahasiswa') ?>" class="btn btn-light" style="padding: 8px 15px;" title="Reset Filter"><i class='bx bx-x'></i></a>
                    <?php endif; ?>
                </div>
            </div>

        </div>
    </form>
</div>

<div class="card" style="background: white; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); overflow: hidden;">
    <div class="table-responsive">
        <table class="table" style="width: 100%; border-collapse: collapse; margin: 0;">
            <thead>
                <tr style="background-color: #f8fafc; border-bottom: 2px solid #e2e8f0;">
                    <th style="padding: 1rem; text-align: left; color: #64748b; font-weight: 600; font-size: 0.875rem;">NO</th>
                    <th style="padding: 1rem; text-align: left; color: #64748b; font-weight: 600; font-size: 0.875rem;">NAMA</th>
                    <th style="padding: 1rem; text-align: left; color: #64748b; font-weight: 600; font-size: 0.875rem;">NIM</th>
                    <th style="padding: 1rem; text-align: left; color: #64748b; font-weight: 600; font-size: 0.875rem;">PROGRAM STUDI</th>
                    <th style="padding: 1rem; text-align: left; color: #64748b; font-weight: 600; font-size: 0.875rem;">JENIS KELAMIN</th>
                    <th style="padding: 1rem; text-align: left; color: #64748b; font-weight: 600; font-size: 0.875rem;">STATUS AKTIF</th>
                    <th style="padding: 1rem; text-align: center; color: #64748b; font-weight: 600; font-size: 0.875rem;">ANGKATAN</th>
                    <th style="padding: 1rem; text-align: center; color: #64748b; font-weight: 600; font-size: 0.875rem;">AKSI</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $page = isset($_GET['page_mahasiswa']) ? $_GET['page_mahasiswa'] : 1;
                $no = 1 + ($per_page * ($page - 1));
                foreach ($mahasiswa as $m) : 
                ?>
                    <tr style="border-bottom: 1px solid #e2e8f0; transition: background-color 0.2s;" onmouseover="this.style.backgroundColor='#f8fafc';" onmouseout="this.style.backgroundColor='transparent';">
                        <td style="padding: 1rem;"><?= $no++ ?></td>
                        <td style="padding: 1rem; font-weight: 500; color: #334155;">
                            <a href="<?= base_url('mahasiswa/show/'.$m['id']) ?>" style="color: #4f46e5; text-decoration: none; font-weight: 600;">
                                <?= strtoupper($m['nama_lengkap']) ?>
                            </a>
                        </td>
                        <td style="padding: 1rem;">
                            <span style="font-weight: 600; color: #0284c7;"><?= $m['nim'] ?></span>
                        </td>
                        <td style="padding: 1rem; color: #475569;">
                            <?= $m['nama_prodi'] ?>
                        </td>
                        <td style="padding: 1rem;">
                            <?php if($m['jenis_kelamin'] == 'L' || $m['jenis_kelamin'] == 'Laki-Laki'): ?>
                                <span style="background-color: #e0f2fe; color: #0369a1; padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">
                                    <i class='bx bx-male'></i> Laki-Laki
                                </span>
                            <?php else: ?>
                                <span style="background-color: #fce7f3; color: #be185d; padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">
                                    <i class='bx bx-female'></i> Perempuan
                                </span>
                            <?php endif; ?>
                        </td>
                        <td style="padding: 1rem;">
                            <?php 
                            if($m['status_mahasiswa'] == 'Aktif') {
                                $bg = '#d1fae5'; $color = '#059669';
                            } elseif($m['status_mahasiswa'] == 'Cuti') {
                                $bg = '#fef3c7'; $color = '#d97706';
                            } elseif($m['status_mahasiswa'] == 'Lulus') {
                                $bg = '#dbeafe'; $color = '#1d4ed8';
                            } else {
                                $bg = '#fee2e2'; $color = '#dc2626';
                            }
                            ?>
                            <span style="background-color: <?= $bg ?>; color: <?= $color ?>; padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">
                                <?= $m['status_mahasiswa'] ?>
                            </span>
                        </td>
                        <td style="padding: 1rem; text-align: center;">
                            <span style="font-weight: 500; color: #64748b; background-color: #f1f5f9; padding: 4px 10px; border-radius: 20px; font-size: 13px;">
                                <?= $m['angkatan'] ?: '-' ?>
                            </span>
                        </td>
                        <td style="padding: 1rem; text-align: center;">
                            <a href="<?= base_url('mahasiswa/show/'.$m['id']) ?>" class="btn btn-sm btn-outline-primary" style="padding: 4px 8px; font-size: 12px; margin-right: 4px;">
                                <i class='bx bx-detail'></i> Detail
                            </a>
                            <a href="<?= base_url('mahasiswa/edit/'.$m['id']) ?>" class="btn btn-sm btn-outline-warning" style="padding: 4px 8px; font-size: 12px;">
                                <i class='bx bx-edit-alt'></i> Edit
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if(empty($mahasiswa)) : ?>
                    <tr>
                        <td colspan="8" style="padding: 3rem; text-align: center; color: #64748b;">
                            <i class='bx bx-group' style="font-size: 3rem; color: #cbd5e1; margin-bottom: 1rem; display: block;"></i>
                            Belum ada data Mahasiswa. Silakan sinkronisasi dari PDDIKTI.
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- Pagination Container -->
    <div style="padding: 1.5rem; border-top: 1px solid #e2e8f0; background: #f8fafc;">
        <?= $pager->links('mahasiswa', 'custom_pagination') ?>
    </div>
</div>

<!-- Custom Progress Modal -->
<div id="customSyncModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999; justify-content: center; align-items: center;">
    <div style="background: white; width: 400px; padding: 2rem; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); text-align: center;">
        <h3 style="margin-top: 0; font-size: 1.25rem; color: #1e293b;">Sinkronisasi Biodata Mahasiswa</h3>
        <p id="syncStatusText" style="color: #64748b; font-size: 0.9rem; margin-bottom: 1rem;">Mempersiapkan sinkronisasi...</p>
        
        <div style="width: 100%; height: 20px; background: #e2e8f0; border-radius: 10px; overflow: hidden; margin-bottom: 1rem;">
            <div id="syncProgressBar" style="width: 0%; height: 100%; background: #4f46e5; transition: width 0.3s ease; display: flex; align-items: center; justify-content: center; color: white; font-size: 0.75rem; font-weight: bold;">0%</div>
        </div>
        
        <p id="syncCountText" style="color: #64748b; font-size: 0.85rem; margin-bottom: 1.5rem;">0 / 0 Mahasiswa</p>
        
        <div id="syncFooter" style="display: none;">
            <button type="button" onclick="location.reload()" style="background: #4f46e5; color: white; border: none; padding: 8px 16px; border-radius: 6px; cursor: pointer; font-weight: 600;">Selesai & Muat Ulang</button>
        </div>
    </div>
</div>

<script>
let totalStudents = [];
let currentIndex = 0;
const BATCH_SIZE = 20;

function startBatchSync() {
    if (!confirm('Apakah Anda yakin ingin menyinkronkan profil biodata seluruh mahasiswa? Proses ini membutuhkan waktu beberapa menit.')) return;
    
    // Show custom modal
    document.getElementById('customSyncModal').style.display = 'flex';
    document.getElementById('syncStatusText').innerText = 'Mempersiapkan sinkronisasi...';
    document.getElementById('syncProgressBar').style.width = '0%';
    document.getElementById('syncProgressBar').innerText = '0%';
    document.getElementById('syncProgressBar').style.background = '#4f46e5';
    document.getElementById('syncFooter').style.display = 'none';
    
    // Fetch all student IDs
    fetch('<?= base_url('mahasiswa/getBatchStudents') ?>')
    .then(response => {
        if (!response.ok) throw new Error('Network response was not ok');
        return response.json();
    })
    .then(res => {
        if (res.status === 'success') {
            totalStudents = res.data;
            if (totalStudents.length === 0) {
                document.getElementById('syncStatusText').innerText = 'Tidak ada mahasiswa untuk disinkronisasi.';
                document.getElementById('syncFooter').style.display = 'block';
                return;
            }
            processNextBatch();
        } else {
            alert('Gagal mengambil data mahasiswa');
            document.getElementById('customSyncModal').style.display = 'none';
        }
    })
    .catch(error => {
        console.error('Error fetching students:', error);
        alert('Terjadi kesalahan koneksi saat mengambil data mahasiswa.');
        document.getElementById('customSyncModal').style.display = 'none';
    });
}

function processNextBatch() {
    if (currentIndex >= totalStudents.length) {
        // Done
        document.getElementById('syncStatusText').innerText = 'Sinkronisasi Selesai!';
        document.getElementById('syncStatusText').style.color = '#10b981';
        document.getElementById('syncProgressBar').style.background = '#10b981';
        document.getElementById('syncFooter').style.display = 'block';
        return;
    }

    let batchIds = totalStudents.slice(currentIndex, currentIndex + BATCH_SIZE);
    
    document.getElementById('syncStatusText').innerText = 'Menarik biodata mahasiswa dari PDDIKTI...';
    
    fetch('<?= base_url('mahasiswa/syncBiodataBatch') ?>', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({ ids: batchIds })
    })
    .then(response => {
        if (!response.ok) throw new Error('Network response was not ok');
        return response.json();
    })
    .then(res => {
        currentIndex += BATCH_SIZE;
        if (currentIndex > totalStudents.length) currentIndex = totalStudents.length;
        
        let percent = Math.round((currentIndex / totalStudents.length) * 100);
        document.getElementById('syncProgressBar').style.width = percent + '%';
        document.getElementById('syncProgressBar').innerText = percent + '%';
        document.getElementById('syncCountText').innerText = currentIndex + ' / ' + totalStudents.length + ' Mahasiswa';
        
        // Call next batch
        processNextBatch();
    })
    .catch(err => {
        console.error('Batch error:', err);
        document.getElementById('syncStatusText').innerText = 'Terjadi kesalahan pada batch ini. Melanjutkan batch berikutnya...';
        // Still continue despite error on one batch
        currentIndex += BATCH_SIZE;
        setTimeout(processNextBatch, 2000); // delay before next batch on error
    });
}

function syncWilayah() {
    if (!confirm('Proses ini akan mengunduh seluruh referensi wilayah dari PDDIKTI ke database lokal. Membutuhkan waktu beberapa detik. Lanjutkan?')) {
        return;
    }

    // Show custom modal for sync
    document.getElementById('customSyncModal').style.display = 'flex';
    document.getElementById('syncStatusText').innerText = 'Mengunduh referensi wilayah dari PDDIKTI...';
    document.getElementById('syncProgressBar').style.width = '50%';
    document.getElementById('syncProgressBar').innerText = 'Sedang proses...';
    document.getElementById('syncProgressBar').style.background = '#eab308';
    document.getElementById('syncCountText').innerText = 'Harap tunggu...';
    document.getElementById('syncFooter').style.display = 'none';

    fetch('<?= base_url("mahasiswa/syncWilayah") ?>')
        .then(response => {
            if (!response.ok) throw new Error(response.statusText);
            return response.json();
        })
        .then(result => {
            if (result.status === 'success') {
                document.getElementById('syncStatusText').innerText = 'Sinkronisasi Berhasil!';
                document.getElementById('syncStatusText').style.color = '#10b981';
                document.getElementById('syncProgressBar').style.width = '100%';
                document.getElementById('syncProgressBar').innerText = '100%';
                document.getElementById('syncProgressBar').style.background = '#10b981';
                document.getElementById('syncCountText').innerText = result.message;
                document.getElementById('syncFooter').style.display = 'block';
            } else {
                alert('Gagal: ' + result.message);
                document.getElementById('customSyncModal').style.display = 'none';
            }
        })
        .catch(error => {
            console.error(error);
            alert('Terjadi kesalahan jaringan atau server saat mengunduh data.');
            document.getElementById('customSyncModal').style.display = 'none';
        });
}

function syncPT(offset = 0, totalSynced = 0) {
    if (offset === 0) {
        if (!confirm('Proses ini akan mengunduh seluruh data Perguruan Tinggi dari PDDIKTI ke database lokal. Membutuhkan waktu beberapa detik hingga satu menit. Lanjutkan?')) {
            return;
        }

        // Show custom modal for sync
        document.getElementById('customSyncModal').style.display = 'flex';
        document.getElementById('syncStatusText').innerText = 'Mengunduh data Perguruan Tinggi dari PDDIKTI...';
        document.getElementById('syncProgressBar').style.width = '10%';
        document.getElementById('syncProgressBar').innerText = 'Menyiapkan...';
        document.getElementById('syncProgressBar').style.background = '#eab308';
        document.getElementById('syncCountText').innerText = 'Harap tunggu, memulai pengunduhan...';
        document.getElementById('syncFooter').style.display = 'none';
    }

    fetch('<?= base_url("mahasiswa/syncPT") ?>?offset=' + offset)
        .then(response => {
            if (!response.ok) throw new Error(response.statusText);
            return response.json();
        })
        .then(result => {
            if (result.status === 'success') {
                if (result.done) {
                    document.getElementById('syncStatusText').innerText = 'Sinkronisasi Selesai!';
                    document.getElementById('syncStatusText').style.color = '#10b981';
                    document.getElementById('syncProgressBar').style.width = '100%';
                    document.getElementById('syncProgressBar').innerText = '100%';
                    document.getElementById('syncProgressBar').style.background = '#10b981';
                    document.getElementById('syncCountText').innerText = 'Total Tersinkronisasi: ' + totalSynced + ' Perguruan Tinggi';
                    document.getElementById('syncFooter').style.display = 'block';
                } else {
                    totalSynced += result.count;
                    // Approximate total PT is around 4500, calculate percentage safely
                    let percent = Math.min(Math.round((totalSynced / 4500) * 100), 99); 
                    document.getElementById('syncProgressBar').style.width = percent + '%';
                    document.getElementById('syncProgressBar').innerText = percent + '%';
                    document.getElementById('syncCountText').innerText = 'Tersinkronisasi: ' + totalSynced + ' (Offset: ' + offset + ')';
                    
                    // Fetch next batch
                    syncPT(result.next_offset, totalSynced);
                }
            } else {
                alert('Gagal pada offset ' + offset + ': ' + result.message);
                document.getElementById('customSyncModal').style.display = 'none';
            }
        })
        .catch(error => {
            console.error(error);
            alert('Terjadi kesalahan jaringan atau server saat mengunduh data pada offset ' + offset + '. Anda bisa mencoba klik Sinkron PT lagi nanti untuk melanjutkan.');
            document.getElementById('customSyncModal').style.display = 'none';
        });
}
</script>
<?= $this->endSection() ?>
