<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<style>
.nav-tabs .nav-link {
    font-size: .85rem;
    padding: 8px 16px;
}
.sync-table {
    font-size: .8rem;
}
.sync-table th {
    background: #f8f9fa;
    font-weight: 600;
}
.status-badge {
    display: inline-block;
    width: 24px;
    text-align: center;
}
.status-synced { color: #198754; }
.status-warning { color: #ffc107; }
.status-not-sync { color: #dc3545; }
.match-select {
    min-width: 200px;
    font-size: .75rem;
}
</style>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0">
        <i class="bi bi-arrow-repeat text-primary me-2"></i>
        Sync Data Import
    </h5>
    <div>
        <select id="selectImport" class="form-select form-select-sm" style="width:auto;display:inline-block"
            onchange="switchImport(this.value)">
            <?php foreach ($imports as $imp): ?>
            <option value="<?= $imp['id'] ?>" <?= $imp['id'] == $import_id ? 'selected' : '' ?>>
                <?= esc($imp['name']) ?> <?= $imp['is_active'] ? '(Aktif)' : '' ?>
            </option>
            <?php endforeach; ?>
        </select>
        <a href="/asc-import" class="btn btn-sm btn-outline-secondary ms-2">
            <i class="bi bi-arrow-left me-1"></i>Kembali
        </a>
    </div>
</div>

<div class="card">
    <div class="card-header py-2">
        <ul class="nav nav-tabs card-header-tabs" role="tablist">
            <li class="nav-item">
                <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tabGuru">
                    <i class="bi bi-person-badge me-1"></i>Guru
                    <span class="badge bg-secondary ms-1"><?= count($teacher_sync) ?></span>
                </button>
            </li>
            <li class="nav-item">
                <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabKelas">
                    <i class="bi bi-door-open me-1"></i>Kelas
                    <span class="badge bg-secondary ms-1"><?= count($class_sync) ?></span>
                </button>
            </li>
            <li class="nav-item">
                <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabMapel">
                    <i class="bi bi-book me-1"></i>Mata Pelajaran
                    <span class="badge bg-secondary ms-1"><?= count($subject_sync) ?></span>
                </button>
            </li>
        </ul>
    </div>
    <div class="card-body">
        
        <div class="tab-content">
            
            <!-- TAB GURU -->
            <div class="tab-pane fade show active" id="tabGuru">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div>
                        <button class="btn btn-sm btn-primary" id="btnSyncSelectedGuru" disabled>
                            <i class="bi bi-check-circle me-1"></i>Sync Terpilih
                        </button>
                        <button class="btn btn-sm btn-success ms-2" id="btnAutoMatchGuru">
                            <i class="bi bi-magic me-1"></i>Auto Match
                        </button>
                        <button class="btn btn-sm btn-outline-danger ms-2" id="btnResetGuru">
                            <i class="bi bi-arrow-counterclockwise me-1"></i>Reset Semua
                        </button>
                    </div>
                    <div class="text-muted small">
                        <i class="bi bi-info-circle"></i>
                        🟢 Tersync &nbsp; 🟡 Kode match nama beda &nbsp; 🔴 Belum sync
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-sm table-bordered sync-table" id="tableGuru">
                        <thead>
                            <tr>
                                <th style="width:30px"><input type="checkbox" id="checkAllGuru"></th>
                                <th>Nama (aSc)</th>
                                <th>Match ke Guru Existing</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($teacher_sync as $t): ?>
                            <tr data-asc-id="<?= $t['asc_id'] ?>" data-status="<?= $t['status'] ?>">
                                <td class="text-center">
                                    <?php if ($t['status'] !== 'synced'): ?>
                                    <input type="checkbox" class="teacher-check" value="<?= $t['asc_id'] ?>">
                                    <?php endif; ?>
                                </td>
                                <td><?= esc($t['asc_name']) ?></td>
                                <td>
                                    <select class="form-select form-select-sm match-select" data-asc-id="<?= $t['asc_id'] ?>">
                                        <option value="">-- Pilih Guru --</option>
                                        <?php foreach ($existing_teachers as $et): ?>
                                        <option value="<?= $et['id'] ?>"
                                            <?= ($t['matched_id'] == $et['id']) ? 'selected' : '' ?>
                                            data-short-code="<?= esc($et['short_code']) ?>">
                                            <?= esc($et['short_code'] ? "[{$et['short_code']}] " : '') ?>
                                            <?= esc($et['name']) ?>
                                            <?= $et['nip'] ? " ({$et['nip']})" : '' ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td class="text-center">
                                    <?php if ($t['status'] == 'synced'): ?>
                                    <span class="status-badge status-synced">🟢</span> Tersync
                                    <?php elseif ($t['status'] == 'warning'): ?>
                                    <span class="status-badge status-warning">🟡</span> Periksa
                                    <?php else: ?>
                                    <span class="status-badge status-not-sync">🔴</span> Belum
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- TAB KELAS -->
            <div class="tab-pane fade" id="tabKelas">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div>
                        <button class="btn btn-sm btn-primary" id="btnSyncSelectedKelas" disabled>
                            <i class="bi bi-check-circle me-1"></i>Sync Terpilih
                        </button>
                        <button class="btn btn-sm btn-success ms-2" id="btnAutoMatchKelas">
                            <i class="bi bi-magic me-1"></i>Auto Match
                        </button>
                        <button class="btn btn-sm btn-outline-danger ms-2" id="btnResetKelas">
                            <i class="bi bi-arrow-counterclockwise me-1"></i>Reset Semua
                        </button>
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-sm table-bordered sync-table" id="tableKelas">
                        <thead>
                            <tr>
                                <th style="width:30px"><input type="checkbox" id="checkAllKelas"></th>
                                <th>Nama Kelas (aSc)</th>
                                <th>Match ke Kelas Existing</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($class_sync as $c): ?>
                            <tr data-asc-id="<?= $c['asc_id'] ?>" data-status="<?= $c['status'] ?>">
                                <td class="text-center">
                                    <?php if ($c['status'] !== 'synced'): ?>
                                    <input type="checkbox" class="class-check" value="<?= $c['asc_id'] ?>">
                                    <?php endif; ?>
                                </td>
                                <td><span class="fw-bold"><?= esc($c['asc_name']) ?></span></td>
                                <td>
                                    <select class="form-select form-select-sm match-select-class" data-asc-id="<?= $c['asc_id'] ?>">
                                        <option value="">-- Pilih Kelas --</option>
                                        <?php foreach ($existing_classes as $ec): ?>
                                        <option value="<?= $ec['id'] ?>" <?= ($c['matched_id'] == $ec['id']) ? 'selected' : '' ?>>
                                            <?= esc($ec['name']) ?> (<?= esc($ec['grade_name']) ?>)
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td class="text-center">
                                    <?php if ($c['status'] == 'synced'): ?>
                                    <span class="status-badge status-synced">🟢</span> Tersync
                                    <?php else: ?>
                                    <span class="status-badge status-not-sync">🔴</span> Belum
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- TAB MAPEL -->
            <div class="tab-pane fade" id="tabMapel">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div>
                        <button class="btn btn-sm btn-primary" id="btnSyncSelectedMapel" disabled>
                            <i class="bi bi-check-circle me-1"></i>Sync Terpilih
                        </button>
                        <button class="btn btn-sm btn-success ms-2" id="btnAutoMatchMapel">
                            <i class="bi bi-magic me-1"></i>Auto Match
                        </button>
                        <button class="btn btn-sm btn-outline-danger ms-2" id="btnResetMapel">
                            <i class="bi bi-arrow-counterclockwise me-1"></i>Reset Semua
                        </button>
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-sm table-bordered sync-table" id="tableMapel">
                        <thead>
                            <tr>
                                <th style="width:30px"><input type="checkbox" id="checkAllMapel"></th>
                                <th>Kode</th>
                                <th>Nama Mapel (aSc)</th>
                                <th>Match ke Mapel Existing</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($subject_sync as $s): ?>
                            <tr data-asc-id="<?= $s['asc_id'] ?>" data-status="<?= $s['status'] ?>">
                                <td class="text-center">
                                    <?php if ($s['status'] !== 'synced'): ?>
                                    <input type="checkbox" class="subject-check" value="<?= $s['asc_id'] ?>">
                                    <?php endif; ?>
                                </td>
                                <td><span class="fw-bold"><?= esc($s['asc_code']) ?></span></td>
                                <td><?= esc($s['asc_name']) ?></td>
                                <td>
                                    <select class="form-select form-select-sm match-select-subject" data-asc-id="<?= $s['asc_id'] ?>">
                                        <option value="">-- Pilih Mapel --</option>
                                        <?php foreach ($existing_subjects as $es): ?>
                                        <option value="<?= $es['id'] ?>" <?= ($s['matched_id'] == $es['id']) ? 'selected' : '' ?>>
                                            [<?= esc($es['code']) ?>] <?= esc($es['name']) ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td class="text-center">
                                    <?php if ($s['status'] == 'synced'): ?>
                                    <span class="status-badge status-synced">🟢</span> Tersync
                                    <?php else: ?>
                                    <span class="status-badge status-not-sync">🔴</span> Belum
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
        </div>
    </div>
</div>

<script>
const importId = <?= $import_id ?>;

// ── PERSIST ACTIVE TAB ON RELOAD ───────────────────────────────────────
document.addEventListener('DOMContentLoaded', function() {
    const activeTab = localStorage.getItem('activeSyncTab');
    if (activeTab) {
        const tabTriggerEl = document.querySelector(`.nav-link[data-bs-target="${activeTab}"]`);
        if (tabTriggerEl) {
            const tab = new bootstrap.Tab(tabTriggerEl);
            tab.show();
        }
    }

    document.querySelectorAll('.nav-link[data-bs-toggle="tab"]').forEach(tabTriggerEl => {
        tabTriggerEl.addEventListener('shown.bs.tab', function(event) {
            const target = event.target.getAttribute('data-bs-target');
            localStorage.setItem('activeSyncTab', target);
        });
    });
});

// ── SWITCH IMPORT ──────────────────────────────────────────────────────
function switchImport(id) {
    window.location.href = `/asc-sync/${id}`;
}

// ── SYNC PER BARIS (GURU) ──────────────────────────────────────────────
document.querySelectorAll('.match-select').forEach(select => {
    select.addEventListener('change', async function() {
        const ascId = this.dataset.ascId;
        const teacherId = this.value;
        
        const formData = new FormData();
        formData.append('asc_id', ascId);
        formData.append('teacher_id', teacherId);
        
        const response = await fetch('/asc-sync/teacher/sync', {
            method: 'POST',
            body: formData,
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });
        const data = await response.json();
        
        if (data.success) {
            location.reload();
        } else {
            alert(data.message);
        }
    });
});

// ── SYNC PER BARIS (KELAS) ──────────────────────────────────────────────
document.querySelectorAll('.match-select-class').forEach(select => {
    select.addEventListener('change', async function() {
        const ascId = this.dataset.ascId;
        const classroomId = this.value;
        
        const formData = new FormData();
        formData.append('asc_id', ascId);
        formData.append('classroom_id', classroomId);
        
        const response = await fetch('/asc-sync/class/sync', {
            method: 'POST',
            body: formData,
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });
        const data = await response.json();
        
        if (data.success) {
            location.reload();
        } else {
            alert(data.message);
        }
    });
});

// ── SYNC PER BARIS (MAPEL) ──────────────────────────────────────────────
document.querySelectorAll('.match-select-subject').forEach(select => {
    select.addEventListener('change', async function() {
        const ascId = this.dataset.ascId;
        const subjectId = this.value;
        
        const formData = new FormData();
        formData.append('asc_id', ascId);
        formData.append('subject_id', subjectId);
        
        const response = await fetch('/asc-sync/subject/sync', {
            method: 'POST',
            body: formData,
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });
        const data = await response.json();
        
        if (data.success) {
            location.reload();
        } else {
            alert(data.message);
        }
    });
});

// ── AUTO MATCH GURU ────────────────────────────────────────────────────
document.getElementById('btnAutoMatchGuru')?.addEventListener('click', async () => {
    if (!confirm('Auto-match akan mencoba menyamakan berdasarkan kode dan nama guru. Lanjutkan?')) return;
    
    const formData = new FormData();
    formData.append('import_id', importId);
    
    const response = await fetch('/asc-sync/teacher/auto-match', {
        method: 'POST',
        body: formData,
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    });
    const data = await response.json();
    
    alert(data.message);
    if (data.success) location.reload();
});

// ── AUTO MATCH KELAS ───────────────────────────────────────────────────
document.getElementById('btnAutoMatchKelas')?.addEventListener('click', async () => {
    const formData = new FormData();
    formData.append('import_id', importId);
    
    const response = await fetch('/asc-sync/class/auto-match', {
        method: 'POST',
        body: formData,
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    });
    const data = await response.json();
    
    alert(data.message);
    if (data.success) location.reload();
});

// ── AUTO MATCH MAPEL ───────────────────────────────────────────────────
document.getElementById('btnAutoMatchMapel')?.addEventListener('click', async () => {
    const formData = new FormData();
    formData.append('import_id', importId);
    
    const response = await fetch('/asc-sync/subject/auto-match', {
        method: 'POST',
        body: formData,
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    });
    const data = await response.json();
    
    alert(data.message);
    if (data.success) location.reload();
});

// ── RESET GURU ─────────────────────────────────────────────────────────
document.getElementById('btnResetGuru')?.addEventListener('click', async () => {
    if (!confirm('Reset akan menghapus semua mapping guru. Lanjutkan?')) return;
    
    const response = await fetch(`/asc-sync/reset/${importId}/teacher`, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    });
    location.reload();
});

// ── RESET KELAS ─────────────────────────────────────────────────────────
document.getElementById('btnResetKelas')?.addEventListener('click', async () => {
    if (!confirm('Reset akan menghapus semua mapping kelas. Lanjutkan?')) return;
    
    const response = await fetch(`/asc-sync/reset/${importId}/class`, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    });
    location.reload();
});

// ── RESET MAPEL ─────────────────────────────────────────────────────────
document.getElementById('btnResetMapel')?.addEventListener('click', async () => {
    if (!confirm('Reset akan menghapus semua mapping mata pelajaran. Lanjutkan?')) return;
    
    const response = await fetch(`/asc-sync/reset/${importId}/subject`, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    });
    location.reload();
});

// ── CHECKBOX HANDLERS ─────────────────────────────────────────────────
function updateSyncButton(tableId, btnId, checkClass) {
    const checked = document.querySelectorAll(`${tableId} ${checkClass}:checked`);
    const btn = document.querySelector(btnId);
    if (btn) btn.disabled = checked.length === 0;
}

document.getElementById('checkAllGuru')?.addEventListener('change', function() {
    document.querySelectorAll('#tableGuru .teacher-check').forEach(cb => cb.checked = this.checked);
    updateSyncButton('#tableGuru', '#btnSyncSelectedGuru', '.teacher-check');
});

document.querySelectorAll('#tableGuru .teacher-check').forEach(cb => {
    cb.addEventListener('change', () => updateSyncButton('#tableGuru', '#btnSyncSelectedGuru', '.teacher-check'));
});

document.getElementById('checkAllKelas')?.addEventListener('change', function() {
    document.querySelectorAll('#tableKelas .class-check').forEach(cb => cb.checked = this.checked);
    updateSyncButton('#tableKelas', '#btnSyncSelectedKelas', '.class-check');
});

document.querySelectorAll('#tableKelas .class-check').forEach(cb => {
    cb.addEventListener('change', () => updateSyncButton('#tableKelas', '#btnSyncSelectedKelas', '.class-check'));
});

document.getElementById('checkAllMapel')?.addEventListener('change', function() {
    document.querySelectorAll('#tableMapel .subject-check').forEach(cb => cb.checked = this.checked);
    updateSyncButton('#tableMapel', '#btnSyncSelectedMapel', '.subject-check');
});

document.querySelectorAll('#tableMapel .subject-check').forEach(cb => {
    cb.addEventListener('change', () => updateSyncButton('#tableMapel', '#btnSyncSelectedMapel', '.subject-check'));
});

// Sync selected guru
document.getElementById('btnSyncSelectedGuru')?.addEventListener('click', async () => {
    const checks = document.querySelectorAll('#tableGuru .teacher-check:checked');
    const mappings = [];
    
    checks.forEach(cb => {
        const row = cb.closest('tr');
        const ascId = row.dataset.ascId;
        const select = row.querySelector('.match-select');
        const teacherId = select.value;
        if (teacherId) {
            mappings.push({ asc_id: ascId, teacher_id: teacherId });
        }
    });
    
    if (mappings.length === 0) {
        alert('Pilih guru dan pilih match terlebih dahulu!');
        return;
    }
    
    const response = await fetch('/asc-sync/teacher/sync-bulk', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
        body: JSON.stringify({ mappings })
    });
    const data = await response.json();
    
    alert(data.message);
    if (data.success) location.reload();
});

// Sync selected kelas
document.getElementById('btnSyncSelectedKelas')?.addEventListener('click', async () => {
    const checks = document.querySelectorAll('#tableKelas .class-check:checked');
    const mappings = [];
    
    checks.forEach(cb => {
        const row = cb.closest('tr');
        const ascId = row.dataset.ascId;
        const select = row.querySelector('.match-select-class');
        const classroomId = select.value;
        if (classroomId) {
            mappings.push({ asc_id: ascId, classroom_id: classroomId });
        }
    });
    
    if (mappings.length === 0) {
        alert('Pilih kelas dan pilih match terlebih dahulu!');
        return;
    }
    
    const response = await fetch('/asc-sync/class/sync-bulk', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
        body: JSON.stringify({ mappings })
    });
    const data = await response.json();
    
    alert(data.message);
    if (data.success) location.reload();
});

// Sync selected mapel
document.getElementById('btnSyncSelectedMapel')?.addEventListener('click', async () => {
    const checks = document.querySelectorAll('#tableMapel .subject-check:checked');
    const mappings = [];
    
    checks.forEach(cb => {
        const row = cb.closest('tr');
        const ascId = row.dataset.ascId;
        const select = row.querySelector('.match-select-subject');
        const subjectId = select.value;
        if (subjectId) {
            mappings.push({ asc_id: ascId, subject_id: subjectId });
        }
    });
    
    if (mappings.length === 0) {
        alert('Pilih mata pelajaran dan pilih match terlebih dahulu!');
        return;
    }
    
    const response = await fetch('/asc-sync/subject/sync-bulk', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
        body: JSON.stringify({ mappings })
    });
    const data = await response.json();
    
    alert(data.message);
    if (data.success) location.reload();
});
</script>

<?= $this->endSection() ?>