<?php
/**
 * SISPENRA - Import Guru dari CSV
 */
require_once '../../includes/functions.php';
requireAdmin();

$pageTitle  = 'Import Data Guru';
$activeMenu = 'guru';
$result     = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
    $file = $_FILES['csv_file'];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        setFlash('danger', 'Upload file gagal. Kode error: ' . $file['error']);
    } else {

        $tmpPath = $file['tmp_name'];
        $berhasil   = 0;
        $gagal      = 0;
        $pesanGagal = array();

        // Baca seluruh file, strip BOM UTF-8 jika ada
        $raw = file_get_contents($tmpPath);
        if (substr($raw, 0, 3) === "\xEF\xBB\xBF") {
            $raw = substr($raw, 3);
        }

        // Normalkan line ending (Windows \r\n → \n)
        $raw   = str_replace("\r\n", "\n", $raw);
        $raw   = str_replace("\r",   "\n", $raw);
        $lines = explode("\n", trim($raw));

        // Deteksi delimiter: titik koma atau koma
        $firstLine = $lines[0] ?? '';
        $delim     = (substr_count($firstLine, ';') >= substr_count($firstLine, ',')) ? ';' : ',';

        foreach ($lines as $lineNo => $line) {
            $rowNum = $lineNo + 1;

            // Lewati baris kosong
            if (trim($line) === '') continue;

            // Parse kolom
            $cols = str_getcsv($line, $delim);
            $cols = array_map('trim', $cols);

            // Lewati baris header (baris pertama atau mengandung kata "nip"/"nama")
            if ($rowNum === 1) {
                $firstCol = strtolower($cols[0]);
                if (strpos($firstCol, 'nip') !== false || strpos($firstCol, 'nama') !== false || !is_numeric($cols[0])) {
                    continue;
                }
            }

            // Minimal 2 kolom (NIP + Nama)
            if (count($cols) < 2) {
                $gagal++;
                $pesanGagal[] = "Baris $rowNum: Data kosong atau tidak terbaca";
                continue;
            }

            // Mapping kolom: NIP | Nama | JK | Tempat Lahir | Tgl Lahir | Pendidikan | Status
            $nip         = $cols[0] ?? '';
            $nama        = $cols[1] ?? '';
            $jk          = strtoupper($cols[2] ?? 'L');
            $tempatLahir = $cols[3] ?? '';
            $tglLahir    = $cols[4] ?? null;
            $pendidikan  = $cols[5] ?? '';
            $statusRaw   = strtolower($cols[6] ?? 'aktif');
            $status      = in_array($statusRaw, array('aktif','nonaktif')) ? $statusRaw : 'aktif';

            // Validasi wajib
            if (empty($nip) || empty($nama)) {
                $gagal++;
                $pesanGagal[] = "Baris $rowNum: NIP atau Nama kosong";
                continue;
            }

            // Validasi jenis kelamin
            if (!in_array($jk, array('L','P'))) $jk = 'L';

            // Validasi & normalkan tanggal lahir
            $tglLahirFinal = null;
            if (!empty($tglLahir)) {
                // Coba format YYYY-MM-DD
                if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $tglLahir)) {
                    $tglLahirFinal = $tglLahir;
                }
                // Coba format DD/MM/YYYY atau DD-MM-YYYY
                elseif (preg_match('/^(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})$/', $tglLahir, $m)) {
                    $tglLahirFinal = $m[3].'-'.str_pad($m[2],2,'0',STR_PAD_LEFT).'-'.str_pad($m[1],2,'0',STR_PAD_LEFT);
                }
            }

            // Cek duplikat NIP
            $existing = db_fetch("SELECT id FROM guru WHERE nip = ?", [$nip]);
            if ($existing) {
                $gagal++;
                $pesanGagal[] = "Baris $rowNum: NIP $nip sudah ada, dilewati";
                continue;
            }

            // Insert
            try {
                // Tabel guru butuh user_id — buat akun user dengan username & password = NIP
                $username  = $nip;
                $passHash  = password_hash($nip, PASSWORD_DEFAULT);
                $existUser = db_fetch("SELECT id FROM users WHERE username = ?", [$username]);
                if ($existUser) {
                    $userId = $existUser['id'];
                } else {
                    db_insert('users', array(
                        'username'     => $username,
                        'password'     => $passHash,
                        'nama_lengkap' => sanitize($nama),
                        'role'         => 'guru',
                    ));
                    $userId = db_fetch("SELECT id FROM users WHERE username = ?", [$username])['id'];
                }

                db_insert('guru', array(
                    'user_id'             => $userId,
                    'nip'                 => $nip,
                    'nama'                => sanitize($nama),
                    'jenis_kelamin'       => $jk,
                    'tempat_lahir'        => sanitize($tempatLahir),
                    'tanggal_lahir'       => $tglLahirFinal,
                    'pendidikan_terakhir' => sanitize($pendidikan),
                    'status'              => $status,
                ));
                $berhasil++;
            } catch (Exception $e) {
                $gagal++;
                $pesanGagal[] = "Baris $rowNum: Gagal simpan — " . $e->getMessage();
            }
        }

        $result = compact('berhasil', 'gagal', 'pesanGagal');
    }
}

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

<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;max-width:960px;">

  <!-- Form upload -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">
        <i class="fas fa-file-upload" style="color:var(--primary);margin-right:8px;"></i>Upload File CSV
      </span>
      <a href="list.php" class="btn btn-outline btn-sm"><i class="fas fa-arrow-left"></i> Kembali</a>
    </div>
    <div class="card-body">

      <?php if ($result !== null): ?>
      <div class="alert alert-<?= ($result['berhasil'] > 0 && $result['gagal'] === 0) ? 'success' : ($result['berhasil'] > 0 ? 'warning' : 'danger') ?>"
           style="margin-bottom:16px;">
        <i class="fas fa-<?= $result['berhasil'] > 0 ? 'check-circle' : 'times-circle' ?>"></i>
        <div>
          <strong>Import selesai:</strong>
          <?= $result['berhasil'] ?> berhasil,
          <?= $result['gagal'] ?> gagal.
          <?php if (!empty($result['pesanGagal'])): ?>
          <div style="margin-top:8px;max-height:160px;overflow-y:auto;">
            <?php foreach (array_slice($result['pesanGagal'], 0, 20) as $p): ?>
            <div style="font-size:12px;color:inherit;opacity:.85;">• <?= htmlspecialchars($p) ?></div>
            <?php endforeach; ?>
            <?php if (count($result['pesanGagal']) > 20): ?>
            <div style="font-size:12px;opacity:.7;">...dan <?= count($result['pesanGagal']) - 20 ?> pesan lainnya</div>
            <?php endif; ?>
          </div>
          <?php endif; ?>
        </div>
      </div>
      <?php endif; ?>

      <form method="POST" enctype="multipart/form-data">
        <div class="form-group">
          <label class="form-label">File CSV <span class="required">*</span></label>
          <input type="file" name="csv_file" class="form-control" accept=".csv,.txt" required>
          <div style="font-size:11px;color:var(--text-muted);margin-top:4px;">
            Format: .csv — pemisah koma <code>,</code> atau titik koma <code>;</code> (otomatis terdeteksi)
          </div>
        </div>
        <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center;">
          <i class="fas fa-upload"></i> Import Sekarang
        </button>
      </form>
    </div>
  </div>

  <!-- Petunjuk -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">
        <i class="fas fa-info-circle" style="color:var(--info);margin-right:8px;"></i>Petunjuk & Format
      </span>
    </div>
    <div class="card-body">
      <p style="font-size:13px;margin-bottom:10px;">Urutan kolom CSV (tanpa header, atau dengan header di baris 1):</p>

      <div style="background:var(--bg);border-radius:8px;padding:12px 14px;font-size:12px;font-family:monospace;margin-bottom:14px;line-height:2;border:1px solid var(--border);">
        <span style="color:var(--primary);font-weight:700;">Kolom 1:</span> NIP<br>
        <span style="color:var(--primary);font-weight:700;">Kolom 2:</span> Nama Lengkap<br>
        <span style="color:var(--text-muted);">Kolom 3:</span> Jenis Kelamin (L/P)<br>
        <span style="color:var(--text-muted);">Kolom 4:</span> Tempat Lahir<br>
        <span style="color:var(--text-muted);">Kolom 5:</span> Tanggal Lahir (YYYY-MM-DD)<br>
        <span style="color:var(--text-muted);">Kolom 6:</span> Pendidikan (S1, S2, dll)<br>
        <span style="color:var(--text-muted);">Kolom 7:</span> Status (Aktif / Nonaktif)
      </div>

      <div style="background:#fff8e1;border:1px solid #ffe082;border-radius:8px;padding:10px 14px;font-size:12px;color:#7c5e00;margin-bottom:14px;">
        <i class="fas fa-lightbulb"></i>
        <strong>Tips:</strong> Kolom 1 (NIP) dan Kolom 2 (Nama) wajib diisi. Kolom lainnya boleh kosong.
        Pemisah <code>;</code> maupun <code>,</code> otomatis terdeteksi. BOM UTF-8 ditangani otomatis. Setiap guru otomatis dibuatkan akun login dengan <strong>username = NIP</strong> dan <strong>password = NIP</strong>.
      </div>

      <p style="font-size:12px;color:var(--text-muted);">Contoh baris data:</p>
      <div style="background:var(--bg);border-radius:6px;padding:8px 12px;font-size:11px;font-family:monospace;border:1px solid var(--border);">
        196609091997031002;Supriyanto Ht;L;Lamongan;1966-09-09;S1;Aktif
      </div>

      <!-- Tombol unduh template -->
      <div style="margin-top:14px;">
        <a href="?download_template=1" class="btn btn-outline btn-sm">
          <i class="fas fa-download"></i> Unduh Template CSV
        </a>
      </div>
    </div>
  </div>

</div>

<?php
// Download template CSV
if (isset($_GET['download_template'])) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="template_import_guru.csv"');
    echo "\xEF\xBB\xBF"; // BOM UTF-8
    echo "NIP;Nama;JK;Tempat Lahir;Tgl Lahir;Pendidikan;Status\n";
    echo "196609091997031002;Contoh Nama Guru;L;Lamongan;1966-09-09;S1;Aktif\n";
    exit;
}
?>

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