<?php
/**
 * SisPen Snesaka - Dapodik AJAX Handler
 * Menangani request sinkronisasi dari JavaScript
 */
require_once '../../includes/functions.php';
requireAdmin();

header('Content-Type: application/json; charset=utf-8');

$action = $_GET['action'] ?? '';
$pengaturan = getPengaturan();

$dapodikIp    = $pengaturan['dapodik_ip']    ?? 'localhost';
$dapodikPort  = $pengaturan['dapodik_port']  ?? '5774';
$dapodikToken = $pengaturan['dapodik_token'] ?? '';
$baseUrl      = "http://{$dapodikIp}:{$dapodikPort}";

// ── Helper: fetch dari Dapodik ────────────────────────────
function fetchDapodik($url, $timeout = 15) {
    $ctx = stream_context_create(array(
        'http' => array(
            'timeout'        => $timeout,
            'ignore_errors'  => true,
        )
    ));
    $raw = @file_get_contents($url, false, $ctx);
    if ($raw === false) return null;
    return json_decode($raw, true);
}

// ── Helper: simpan log ────────────────────────────────────
function simpanLog($jenis, $status, $total, $baru, $update, $lewat, $pesan = '') {
    db_insert('dapodik_log', array(
        'jenis'       => $jenis,
        'status'      => $status,
        'total_data'  => $total,
        'baru'        => $baru,
        'diperbarui'  => $update,
        'dilewati'    => $lewat,
        'pesan'       => $pesan,
    ));
}

// ════════════════════════════════════════════════════════
// ACTION: Tes Koneksi
// ════════════════════════════════════════════════════════
if ($action === 'tes_koneksi') {
    if (empty($dapodikToken)) {
        echo json_encode(array('sukses'=>false, 'pesan'=>'Token belum diisi. Simpan pengaturan koneksi dulu.'));
        exit;
    }
    $url  = "{$baseUrl}/webservice/getData?sandi={$dapodikToken}&data=getSekolah";
    $data = fetchDapodik($url, 8);

    if ($data === null) {
        echo json_encode(array('sukses'=>false, 'pesan'=>"Tidak dapat terhubung ke {$baseUrl}. Pastikan Dapodik aktif."));
        exit;
    }
    if (isset($data['error'])) {
        echo json_encode(array('sukses'=>false, 'pesan'=>'Token tidak valid: '.($data['error'] ?? '')));
        exit;
    }
    $namaSekolah = $data[0]['nama_sekolah'] ?? $data['nama_sekolah'] ?? 'Sekolah ditemukan';
    echo json_encode(array('sukses'=>true, 'pesan'=>"Terhubung ke Dapodik. Sekolah: {$namaSekolah}"));
    exit;
}

// ════════════════════════════════════════════════════════
// ACTION: Sinkronisasi
// ════════════════════════════════════════════════════════
if ($action === 'sinkron') {
    $jenis = $_GET['jenis'] ?? '';
    $ta    = $pengaturan['tahun_ajaran_aktif'];
    $sem   = $pengaturan['semester_aktif'];

    if (!in_array($jenis, array('siswa','guru','kelas'))) {
        echo json_encode(array('sukses'=>false, 'pesan'=>'Jenis tidak valid'));
        exit;
    }
    if (empty($dapodikToken)) {
        echo json_encode(array('sukses'=>false, 'pesan'=>'Token Dapodik belum diisi.'));
        exit;
    }

    // Map jenis → endpoint Dapodik
    $endpoint = array(
        'siswa' => 'getPesertaDidik',
        'guru'  => 'getPTK',
        'kelas' => 'getRombonganBelajar',
    );

    $url  = "{$baseUrl}/webservice/getData?sandi={$dapodikToken}&data={$endpoint[$jenis]}";
    $raw  = fetchDapodik($url, 30);

    if ($raw === null) {
        simpanLog($jenis, 'gagal', 0, 0, 0, 0, "Tidak dapat terhubung ke {$baseUrl}");
        echo json_encode(array('sukses'=>false, 'pesan'=>"Tidak dapat terhubung ke Dapodik ({$baseUrl})"));
        exit;
    }
    if (isset($raw['error'])) {
        simpanLog($jenis, 'gagal', 0, 0, 0, 0, 'Token tidak valid: '.($raw['error']??''));
        echo json_encode(array('sukses'=>false, 'pesan'=>'Token tidak valid: '.($raw['error']??'')));
        exit;
    }

    // Dapodik kadang bungkus dalam key 'data'
    $items = isset($raw['data']) ? $raw['data'] : $raw;
    if (!is_array($items)) {
        echo json_encode(array('sukses'=>false, 'pesan'=>'Format data Dapodik tidak dikenali.'));
        exit;
    }

    $total = count($items);
    $baru = $update = $lewat = 0;
    $preview = array();

    // ── SINKRON SISWA ─────────────────────────────────────
    if ($jenis === 'siswa') {
        foreach ($items as $item) {
            // Mapping field Dapodik → SisPen
            $nisn  = trim($item['nisn']            ?? $item['NISN']            ?? '');
            $nama  = trim($item['nama']             ?? $item['nm_pd']           ?? $item['NAMA'] ?? '');
            $jk    = strtoupper(trim($item['jenis_kelamin'] ?? $item['JK'] ?? 'L'));
            $jk    = ($jk === 'PEREMPUAN' || $jk === 'P' || $jk === '2') ? 'P' : 'L';
            $tl    = trim($item['tempat_lahir']     ?? $item['tmpt_lahir']      ?? '');
            $ttl   = trim($item['tanggal_lahir']    ?? $item['tgl_lahir']       ?? '');
            $nis   = trim($item['nis_sekolah']      ?? $item['NIS']             ?? $nisn);
            $namaRombel = trim($item['nama_rombel'] ?? $item['nm_rombel']       ?? '');

            if (empty($nama) || empty($nis)) { $lewat++; continue; }

            // Normalisasi tanggal
            $tglLahir = null;
            if ($ttl) {
                $parsed = date_create($ttl);
                if ($parsed) $tglLahir = date_format($parsed, 'Y-m-d');
            }

            // Cari kelas_id berdasarkan nama rombel
            $kelasId = null;
            if ($namaRombel) {
                $kelas = db_fetch(
                    "SELECT id FROM kelas WHERE nama_kelas=? AND tahun_ajaran=? AND semester=?",
                    array($namaRombel, $ta, $sem)
                );
                $kelasId = $kelas ? $kelas['id'] : null;
            }

            $rowData = array(
                'nama'          => $nama,
                'nisn'          => $nisn ?: null,
                'jenis_kelamin' => $jk,
                'tempat_lahir'  => $tl ?: null,
                'tanggal_lahir' => $tglLahir,
                'kelas_id'      => $kelasId,
                'status'        => 'aktif',
            );

            // Cek existing by NIS
            $existing = db_fetch("SELECT id FROM siswa WHERE nis=?", array($nis));
            if ($existing) {
                db_update('siswa', $rowData, 'id = :id', array('id' => $existing['id']));
                $update++;
            } else {
                db_insert('siswa', array_merge($rowData, array('nis' => $nis)));
                $baru++;
            }

            // Preview 10 pertama
            if (count($preview) < 10) {
                $preview[] = array(
                    'NIS'      => $nis,
                    'NISN'     => $nisn ?: '-',
                    'Nama'     => $nama,
                    'L/P'      => $jk,
                    'TTL'      => ($tl ? $tl.', ' : '').($tglLahir ?? '-'),
                    'Kelas'    => $namaRombel ?: '-',
                );
            }
        }
    }

    // ── SINKRON GURU ──────────────────────────────────────
    elseif ($jenis === 'guru') {
        foreach ($items as $item) {
            $nip   = trim($item['nip']          ?? $item['NIK']     ?? '');
            $nama  = trim($item['nama']         ?? $item['nm_ptk']  ?? $item['NAMA'] ?? '');
            $jk    = strtoupper(trim($item['jenis_kelamin'] ?? $item['JK'] ?? 'L'));
            $jk    = ($jk === 'PEREMPUAN' || $jk === 'P' || $jk === '2') ? 'P' : 'L';
            $tl    = trim($item['tempat_lahir'] ?? $item['tmpt_lahir'] ?? '');
            $ttl   = trim($item['tanggal_lahir']?? $item['tgl_lahir']  ?? '');
            $email = trim($item['email']        ?? '');
            $telp  = trim($item['no_hp']        ?? $item['telepon']    ?? '');

            if (empty($nama)) { $lewat++; continue; }

            $tglLahir = null;
            if ($ttl) {
                $parsed = date_create($ttl);
                if ($parsed) $tglLahir = date_format($parsed, 'Y-m-d');
            }

            // Cek existing guru by NIP atau nama
            $existingGuru = null;
            if ($nip) {
                $existingGuru = db_fetch("SELECT g.id, g.user_id FROM guru g WHERE g.nip=?", array($nip));
            }
            if (!$existingGuru) {
                $existingGuru = db_fetch("SELECT g.id, g.user_id FROM guru g WHERE g.nama=?", array($nama));
            }

            $rowGuru = array(
                'nama'           => $nama,
                'nip'            => $nip ?: null,
                'jenis_kelamin'  => $jk,
                'tempat_lahir'   => $tl ?: null,
                'tanggal_lahir'  => $tglLahir,
                'email'          => $email ?: null,
                'telepon'        => $telp ?: null,
                'status'         => 'aktif',
            );

            if ($existingGuru) {
                db_update('guru', $rowGuru, 'id = :id', array('id' => $existingGuru['id']));
                $update++;
            } else {
                // Buat user dulu
                $username = $nip ?: strtolower(str_replace(' ', '.', $nama));
                $username = preg_replace('/[^a-z0-9.]/', '', $username);
                $pwHash   = password_hash('dapodik123', PASSWORD_DEFAULT);

                // Cek duplikat username
                $uExist = db_fetch("SELECT id FROM users WHERE username=?", array($username));
                if ($uExist) $username .= rand(10,99);

                $userId = db_insert('users', array(
                    'username'     => $username,
                    'password'     => $pwHash,
                    'nama_lengkap' => $nama,
                    'role'         => 'guru',
                    'status'       => 'aktif',
                ));
                db_insert('guru', array_merge($rowGuru, array('user_id' => $userId)));
                $baru++;
            }

            if (count($preview) < 10) {
                $preview[] = array(
                    'NIP'   => $nip ?: '-',
                    'Nama'  => $nama,
                    'L/P'   => $jk,
                    'Email' => $email ?: '-',
                );
            }
        }
    }

    // ── SINKRON KELAS ─────────────────────────────────────
    elseif ($jenis === 'kelas') {
        foreach ($items as $item) {
            $namaKelas = trim($item['nama_rombel'] ?? $item['nm_rombel'] ?? $item['NAMA_ROMBEL'] ?? '');
            $tingkat   = trim($item['tingkat']     ?? $item['kelas']     ?? '');
            $kapasitas = intval($item['jumlah_siswa_max'] ?? $item['kapasitas'] ?? 32);

            if (empty($namaKelas)) { $lewat++; continue; }

            // Ekstrak tingkat dari nama kelas jika kosong (misal "9A" → "9")
            if (empty($tingkat)) {
                preg_match('/^([789])/', $namaKelas, $m);
                $tingkat = $m[1] ?? '7';
            }
            if (!in_array($tingkat, array('7','8','9'))) $tingkat = '7';

            $existing = db_fetch(
                "SELECT id FROM kelas WHERE nama_kelas=? AND tahun_ajaran=? AND semester=?",
                array($namaKelas, $ta, $sem)
            );
            $rowKelas = array(
                'nama_kelas'   => $namaKelas,
                'tingkat'      => $tingkat,
                'tahun_ajaran' => $ta,
                'semester'     => $sem,
                'kapasitas'    => $kapasitas ?: 32,
            );

            if ($existing) {
                db_update('kelas', $rowKelas, 'id = :id', array('id' => $existing['id']));
                $update++;
            } else {
                db_insert('kelas', $rowKelas);
                $baru++;
            }

            if (count($preview) < 10) {
                $preview[] = array(
                    'Nama Kelas' => $namaKelas,
                    'Tingkat'    => $tingkat,
                    'Kapasitas'  => $kapasitas,
                    'TA'         => $ta,
                );
            }
        }
    }

    // Simpan log
    simpanLog($jenis, 'sukses', $total, $baru, $update, $lewat,
        "Baru: {$baru}, Update: {$update}, Lewati: {$lewat}");

    echo json_encode(array(
        'sukses'     => true,
        'total'      => $total,
        'baru'       => $baru,
        'diperbarui' => $update,
        'dilewati'   => $lewat,
        'preview'    => $preview,
        'pesan'      => "Sinkronisasi {$jenis} selesai.",
    ));
    exit;
}

echo json_encode(array('sukses'=>false, 'pesan'=>'Action tidak dikenali.'));
