<?php
/**
 * SisPen Snesaka - Sinkronisasi Dapodik
 * Mengambil data dari Web Service Dapodik lokal (localhost:5774)
 */
require_once '../../includes/functions.php';
requireAdmin();

$pageTitle  = 'Sinkronisasi Dapodik';
$activeMenu = 'dapodik';
$pengaturan = getPengaturan();
$ta         = $pengaturan['tahun_ajaran_aktif'];
$sem        = $pengaturan['semester_aktif'];

// ── Simpan pengaturan koneksi Dapodik ────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_koneksi'])) {
    $ip    = sanitize($_POST['dapodik_ip']    ?? 'localhost');
    $port  = sanitize($_POST['dapodik_port']  ?? '5774');
    $token = sanitize($_POST['dapodik_token'] ?? '');
    db_update('pengaturan', array(
        'dapodik_ip'    => $ip,
        'dapodik_port'  => $port,
        'dapodik_token' => $token,
    ), 'id = :id', array('id' => $pengaturan['id']));
    setFlash('success', 'Pengaturan koneksi Dapodik berhasil disimpan!');
    header('Location: sinkron.php'); exit;
}

// ── Ambil log sinkronisasi terakhir ──────────────────────
$logs = db_fetchAll(
    "SELECT * FROM dapodik_log ORDER BY created_at DESC LIMIT 10"
);

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

include '../../templates/header.php';
?>

<!-- ── Banner ─────────────────────────────────────────── -->
<div style="background:linear-gradient(135deg,#1e3a5f,#2563eb);border-radius:12px;padding:22px 28px;margin-bottom:20px;color:#fff;display:flex;align-items:center;gap:20px;flex-wrap:wrap;">
  <div style="width:54px;height:54px;background:rgba(255,255,255,.15);border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:26px;flex-shrink:0;">
    <i class="fas fa-sync-alt"></i>
  </div>
  <div>
    <h2 style="font-size:18px;font-weight:800;margin-bottom:4px;">Sinkronisasi Data Dapodik</h2>
    <p style="font-size:13px;opacity:.85;">
      Tarik data siswa, guru, dan kelas langsung dari Web Service Dapodik lokal.
      Pastikan aplikasi Dapodik sedang berjalan di komputer operator.
    </p>
  </div>
  <div style="margin-left:auto;">
    <span style="background:rgba(255,255,255,.15);border:1px solid rgba(255,255,255,.3);border-radius:20px;padding:5px 14px;font-size:12px;font-weight:700;">
      <i class="fas fa-server"></i> <?= htmlspecialchars($baseUrl) ?>
    </span>
  </div>
</div>

<div style="display:grid;grid-template-columns:320px 1fr;gap:20px;align-items:start;">

<!-- ── Panel Kiri: Pengaturan Koneksi ─────────────────── -->
<div>
  <div class="card" style="margin-bottom:16px;">
    <div class="card-header">
      <span class="card-title">
        <i class="fas fa-plug" style="color:var(--primary);margin-right:8px;"></i>
        Koneksi Dapodik
      </span>
    </div>
    <div class="card-body">
      <form method="POST">
        <input type="hidden" name="save_koneksi" value="1">

        <div class="form-group">
          <label class="form-label">IP / Host Dapodik</label>
          <input type="text" name="dapodik_ip" class="form-control"
                 value="<?= htmlspecialchars($dapodikIp) ?>"
                 placeholder="localhost atau 192.168.x.x">
          <small style="color:var(--text-muted);font-size:11px;">
            Gunakan <code>localhost</code> jika Dapodik di komputer ini,
            atau IP LAN jika komputer lain.
          </small>
        </div>

        <div class="form-group">
          <label class="form-label">Port</label>
          <input type="text" name="dapodik_port" class="form-control"
                 value="<?= htmlspecialchars($dapodikPort) ?>"
                 placeholder="5774">
        </div>

        <div class="form-group">
          <label class="form-label">Token Dapodik</label>
          <div style="position:relative;">
            <input type="password" name="dapodik_token" id="inp_token"
                   class="form-control" style="padding-right:40px;"
                   value="<?= htmlspecialchars($dapodikToken) ?>"
                   placeholder="Token dari Pengaturan → Web Service">
            <button type="button" onclick="toggleToken()"
                    style="position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:var(--text-muted);">
              <i class="fas fa-eye" id="ico_token"></i>
            </button>
          </div>
          <small style="color:var(--text-muted);font-size:11px;">
            Buka Dapodik → Pengaturan → Web Service → salin token.
          </small>
        </div>

        <button type="submit" class="btn btn-primary" style="width:100%;">
          <i class="fas fa-save"></i> Simpan Koneksi
        </button>
      </form>

      <!-- Tombol Tes Koneksi -->
      <hr style="border:none;border-top:1px solid var(--border);margin:14px 0;">
      <button type="button" class="btn btn-outline" style="width:100%;"
              onclick="tesKoneksi()">
        <i class="fas fa-wifi"></i> Tes Koneksi
      </button>
      <div id="tes-result" style="margin-top:10px;font-size:13px;display:none;"></div>
    </div>
  </div>

  <!-- Panduan -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">
        <i class="fas fa-info-circle" style="color:var(--accent);margin-right:8px;"></i>
        Panduan
      </span>
    </div>
    <div class="card-body" style="font-size:12px;color:var(--text-muted);line-height:1.8;">
      <ol style="padding-left:18px;">
        <li>Pastikan <strong>aplikasi Dapodik aktif</strong> di komputer operator</li>
        <li>Buka Dapodik → <strong>Pengaturan → Web Service</strong></li>
        <li>Tambah aplikasi baru → beri nama <strong>"SisPen Snesaka"</strong></li>
        <li>Salin <strong>Token</strong> yang dibuat otomatis</li>
        <li>Isi IP & Token di form kiri, klik <strong>Simpan</strong></li>
        <li>Klik <strong>Tes Koneksi</strong> untuk memastikan terhubung</li>
        <li>Pilih data yang ingin disinkron</li>
      </ol>
    </div>
  </div>
</div>

<!-- ── Panel Kanan: Tombol Sinkron ────────────────────── -->
<div>

  <!-- 3 kartu sinkron -->
  <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:14px;margin-bottom:20px;">

    <!-- Siswa -->
    <div style="background:linear-gradient(135deg,#064e3b,#047857);border-radius:16px;padding:22px 18px;color:#fff;position:relative;overflow:hidden;">
      <div style="position:absolute;top:-20px;right:-20px;width:80px;height:80px;border-radius:50%;background:rgba(255,255,255,.08);"></div>
      <div style="width:46px;height:46px;background:rgba(255,255,255,.2);border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:20px;margin-bottom:14px;">
        <i class="fas fa-user-graduate"></i>
      </div>
      <div style="font-size:13px;font-weight:700;opacity:.85;margin-bottom:4px;">Peserta Didik</div>
      <div style="font-size:11px;opacity:.7;margin-bottom:16px;">Nama, NIS, NISN, Kelas, L/P, TTL</div>
      <button onclick="sinkron('siswa')" class="btn" id="btn-siswa"
              style="background:rgba(255,255,255,.2);color:#fff;border:1px solid rgba(255,255,255,.4);width:100%;font-size:13px;">
        <i class="fas fa-sync-alt"></i> Sinkron Siswa
      </button>
    </div>

    <!-- Guru -->
    <div style="background:linear-gradient(135deg,#0f2544,#1e4d8c);border-radius:16px;padding:22px 18px;color:#fff;position:relative;overflow:hidden;">
      <div style="position:absolute;top:-20px;right:-20px;width:80px;height:80px;border-radius:50%;background:rgba(255,255,255,.08);"></div>
      <div style="width:46px;height:46px;background:rgba(255,255,255,.2);border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:20px;margin-bottom:14px;">
        <i class="fas fa-chalkboard-teacher"></i>
      </div>
      <div style="font-size:13px;font-weight:700;opacity:.85;margin-bottom:4px;">PTK / Guru</div>
      <div style="font-size:11px;opacity:.7;margin-bottom:16px;">Nama, NIP, Jenis Kelamin, Status</div>
      <button onclick="sinkron('guru')" class="btn" id="btn-guru"
              style="background:rgba(255,255,255,.2);color:#fff;border:1px solid rgba(255,255,255,.4);width:100%;font-size:13px;">
        <i class="fas fa-sync-alt"></i> Sinkron Guru
      </button>
    </div>

    <!-- Kelas -->
    <div style="background:linear-gradient(135deg,#78350f,#b45309);border-radius:16px;padding:22px 18px;color:#fff;position:relative;overflow:hidden;">
      <div style="position:absolute;top:-20px;right:-20px;width:80px;height:80px;border-radius:50%;background:rgba(255,255,255,.08);"></div>
      <div style="width:46px;height:46px;background:rgba(255,255,255,.2);border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:20px;margin-bottom:14px;">
        <i class="fas fa-door-open"></i>
      </div>
      <div style="font-size:13px;font-weight:700;opacity:.85;margin-bottom:4px;">Rombongan Belajar</div>
      <div style="font-size:11px;opacity:.7;margin-bottom:16px;">Nama Kelas, Tingkat, Kapasitas</div>
      <button onclick="sinkron('kelas')" class="btn" id="btn-kelas"
              style="background:rgba(255,255,255,.2);color:#fff;border:1px solid rgba(255,255,255,.4);width:100%;font-size:13px;">
        <i class="fas fa-sync-alt"></i> Sinkron Kelas
      </button>
    </div>

  </div>

  <!-- Hasil sinkron real-time -->
  <div class="card" id="result-card" style="display:none;margin-bottom:16px;">
    <div class="card-header">
      <span class="card-title" id="result-title">
        <i class="fas fa-spinner fa-spin" style="color:var(--primary);margin-right:8px;"></i>
        Memproses...
      </span>
    </div>
    <div class="card-body" id="result-body" style="font-size:13px;"></div>
  </div>

  <!-- Log sinkronisasi -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">
        <i class="fas fa-history" style="color:var(--primary);margin-right:8px;"></i>
        Riwayat Sinkronisasi
      </span>
      <?php if (!empty($logs)): ?>
      <a href="sinkron.php?clear_log=1" class="btn btn-outline btn-sm"
         onclick="return confirm('Hapus semua riwayat?')"
         style="color:var(--danger);border-color:var(--danger);">
        <i class="fas fa-trash"></i> Hapus Log
      </a>
      <?php endif; ?>
    </div>
    <?php if (empty($logs)): ?>
    <div style="padding:40px;text-align:center;color:var(--text-muted);">
      <i class="fas fa-history" style="font-size:36px;opacity:.2;display:block;margin-bottom:12px;"></i>
      <p>Belum ada riwayat sinkronisasi.</p>
    </div>
    <?php else: ?>
    <div style="overflow-x:auto;">
      <table style="width:100%;border-collapse:collapse;font-size:13px;">
        <thead>
          <tr style="background:var(--primary-dark);color:#fff;">
            <th style="padding:10px 14px;text-align:left;">Waktu</th>
            <th style="padding:10px 10px;text-align:center;">Jenis</th>
            <th style="padding:10px 10px;text-align:center;">Status</th>
            <th style="padding:10px 10px;text-align:center;">Total</th>
            <th style="padding:10px 10px;text-align:center;">Baru</th>
            <th style="padding:10px 10px;text-align:center;">Update</th>
            <th style="padding:10px 10px;text-align:center;">Lewat</th>
            <th style="padding:10px 14px;text-align:left;">Keterangan</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($logs as $i => $log): ?>
          <tr style="<?= $i%2===0?'':'background:var(--surface-2);' ?>">
            <td style="padding:8px 14px;white-space:nowrap;font-size:12px;">
              <?= date('d/m/Y H:i', strtotime($log['created_at'])) ?>
            </td>
            <td style="padding:8px 10px;text-align:center;">
              <?php
              $jBadge = array('siswa'=>array('#d1fae5','#065f46','fa-user-graduate'),
                              'guru' =>array('#dbeafe','#1e40af','fa-chalkboard-teacher'),
                              'kelas'=>array('#fef3c7','#92400e','fa-door-open'));
              $jb = $jBadge[$log['jenis']] ?? array('#f3f4f6','#374151','fa-circle');
              ?>
              <span style="background:<?= $jb[0] ?>;color:<?= $jb[1] ?>;border-radius:12px;padding:3px 10px;font-size:11px;font-weight:700;">
                <i class="fas <?= $jb[2] ?>"></i> <?= ucfirst($log['jenis']) ?>
              </span>
            </td>
            <td style="padding:8px 10px;text-align:center;">
              <?php if ($log['status'] === 'sukses'): ?>
              <span style="background:#d1fae5;color:#065f46;border-radius:12px;padding:3px 10px;font-size:11px;font-weight:700;">
                <i class="fas fa-check"></i> Sukses
              </span>
              <?php else: ?>
              <span style="background:#fee2e2;color:#991b1b;border-radius:12px;padding:3px 10px;font-size:11px;font-weight:700;">
                <i class="fas fa-times"></i> Gagal
              </span>
              <?php endif; ?>
            </td>
            <td style="padding:8px 10px;text-align:center;font-weight:700;"><?= $log['total_data'] ?></td>
            <td style="padding:8px 10px;text-align:center;color:#065f46;font-weight:700;"><?= $log['baru'] ?></td>
            <td style="padding:8px 10px;text-align:center;color:#1e40af;font-weight:700;"><?= $log['diperbarui'] ?></td>
            <td style="padding:8px 10px;text-align:center;color:var(--text-muted);"><?= $log['dilewati'] ?></td>
            <td style="padding:8px 14px;font-size:12px;color:var(--text-muted);"><?= htmlspecialchars($log['pesan'] ?? '') ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </div>

</div>
</div>

<script>
var BASE = '<?= BASE_URL ?>';

function toggleToken() {
    var inp = document.getElementById('inp_token');
    var ico = document.getElementById('ico_token');
    if (inp.type === 'password') {
        inp.type = 'text';
        ico.className = 'fas fa-eye-slash';
    } else {
        inp.type = 'password';
        ico.className = 'fas fa-eye';
    }
}

function tesKoneksi() {
    var res = document.getElementById('tes-result');
    res.style.display = 'block';
    res.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Mengecek koneksi...';
    res.style.cssText = 'margin-top:10px;font-size:13px;display:block;padding:8px 12px;border-radius:6px;background:#f0f9ff;color:#0369a1;';

    fetch(BASE + '/modules/dapodik/ajax.php?action=tes_koneksi')
        .then(function(r){ return r.json(); })
        .then(function(d){
            if (d.sukses) {
                res.style.cssText = 'margin-top:10px;font-size:13px;display:block;padding:8px 12px;border-radius:6px;background:#d1fae5;color:#065f46;font-weight:600;';
                res.innerHTML = '<i class="fas fa-check-circle"></i> Terhubung! ' + (d.pesan || '');
            } else {
                res.style.cssText = 'margin-top:10px;font-size:13px;display:block;padding:8px 12px;border-radius:6px;background:#fee2e2;color:#991b1b;font-weight:600;';
                res.innerHTML = '<i class="fas fa-times-circle"></i> Gagal: ' + (d.pesan || 'Tidak dapat terhubung ke Dapodik');
            }
        })
        .catch(function(e){
            res.style.cssText = 'margin-top:10px;font-size:13px;display:block;padding:8px 12px;border-radius:6px;background:#fee2e2;color:#991b1b;font-weight:600;';
            res.innerHTML = '<i class="fas fa-times-circle"></i> Error: ' + e.message;
        });
}

function sinkron(jenis) {
    var card  = document.getElementById('result-card');
    var title = document.getElementById('result-title');
    var body  = document.getElementById('result-body');
    var btn   = document.getElementById('btn-' + jenis);

    // Disable tombol
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Memproses...';

    card.style.display = 'block';
    title.innerHTML = '<i class="fas fa-spinner fa-spin" style="color:var(--primary);margin-right:8px;"></i> Menyinkron data ' + jenis + '...';
    body.innerHTML  = '<div style="padding:20px;text-align:center;color:var(--text-muted);">Mengambil data dari Dapodik, harap tunggu...</div>';

    // Scroll ke hasil
    card.scrollIntoView({behavior:'smooth', block:'start'});

    fetch(BASE + '/modules/dapodik/ajax.php?action=sinkron&jenis=' + jenis)
        .then(function(r){ return r.json(); })
        .then(function(d){
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-sync-alt"></i> Sinkron ' + jenis.charAt(0).toUpperCase() + jenis.slice(1);

            if (d.sukses) {
                title.innerHTML = '<i class="fas fa-check-circle" style="color:var(--success);margin-right:8px;"></i> Sinkronisasi ' + jenis + ' selesai!';
                body.innerHTML  = renderHasil(d);
            } else {
                title.innerHTML = '<i class="fas fa-times-circle" style="color:var(--danger);margin-right:8px;"></i> Sinkronisasi gagal';
                body.innerHTML  = '<div style="padding:14px;background:#fee2e2;color:#991b1b;border-radius:8px;font-weight:600;">'
                                + '<i class="fas fa-exclamation-triangle"></i> ' + (d.pesan || 'Terjadi kesalahan') + '</div>';
            }
            // Reload log setelah 1 detik
            setTimeout(function(){ location.reload(); }, 2000);
        })
        .catch(function(e){
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-sync-alt"></i> Sinkron ' + jenis;
            title.innerHTML = '<i class="fas fa-times-circle" style="color:var(--danger);margin-right:8px;"></i> Error';
            body.innerHTML  = '<div style="padding:14px;background:#fee2e2;color:#991b1b;border-radius:8px;">' + e.message + '</div>';
        });
}

function renderHasil(d) {
    var html = '<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px;">';
    var stats = [
        {label:'Total Data',  val:d.total,      color:'#1e40af', bg:'#dbeafe'},
        {label:'Data Baru',   val:d.baru,        color:'#065f46', bg:'#d1fae5'},
        {label:'Diperbarui',  val:d.diperbarui,  color:'#92400e', bg:'#fef3c7'},
        {label:'Dilewati',    val:d.dilewati,    color:'#4b5563', bg:'#f3f4f6'},
    ];
    stats.forEach(function(s){
        html += '<div style="background:'+s.bg+';border-radius:10px;padding:14px;text-align:center;">'
              + '<div style="font-size:28px;font-weight:900;color:'+s.color+';">'+s.val+'</div>'
              + '<div style="font-size:11px;font-weight:700;color:'+s.color+';opacity:.8;">'+s.label+'</div>'
              + '</div>';
    });
    html += '</div>';

    if (d.preview && d.preview.length > 0) {
        html += '<div style="font-size:12px;font-weight:700;color:var(--text-muted);margin-bottom:8px;">PREVIEW DATA (10 pertama)</div>';
        html += '<div style="overflow-x:auto;"><table style="width:100%;border-collapse:collapse;font-size:12px;">';
        // Header
        var keys = Object.keys(d.preview[0]);
        html += '<tr style="background:var(--primary-dark);color:#fff;">';
        keys.forEach(function(k){ html += '<th style="padding:6px 8px;text-align:left;">'+k+'</th>'; });
        html += '</tr>';
        // Rows
        d.preview.forEach(function(row, i){
            html += '<tr style="'+(i%2===0?'':'background:var(--surface-2);')+'">';
            keys.forEach(function(k){
                html += '<td style="padding:5px 8px;border-bottom:1px solid var(--border);">'+(row[k]||'-')+'</td>';
            });
            html += '</tr>';
        });
        html += '</table></div>';
    }
    return html;
}
</script>

<?php
// Clear log
if (isset($_GET['clear_log'])) {
    db_query("DELETE FROM dapodik_log");
    setFlash('success', 'Riwayat sinkronisasi dihapus.');
    header('Location: sinkron.php'); exit;
}
?>

<?php include '../../templates/footer.php'; ?>
