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

$pageTitle  = 'Import Siswa';
$activeMenu = 'siswa';

$pengaturan = getPengaturan();
$kelasList  = db_fetchAll(
    "SELECT * FROM kelas WHERE tahun_ajaran=? AND semester=? ORDER BY tingkat, nama_kelas",
    [$pengaturan['tahun_ajaran_aktif'], $pengaturan['semester_aktif']]
);

$result = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
    $file    = $_FILES['csv_file'];
    $kelasId = intval($_POST['kelas_id'] ?? 0);

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

        // Baca langsung dari tmp_name — tidak perlu folder uploads
        $raw = file_get_contents($file['tmp_name']);

        // Strip BOM UTF-8
        if (substr($raw, 0, 3) === "\xEF\xBB\xBF") {
            $raw = substr($raw, 3);
        }

        // Normalkan line ending
        $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, ',')) ? ';' : ',';

        $berhasil   = 0;
        $gagal      = 0;
        $pesanGagal = array();

        foreach ($lines as $lineNo => $line) {
            $rowNum = $lineNo + 1;
            if (trim($line) === '') continue;

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

            // Lewati baris header
            if ($rowNum === 1) {
                $firstCol = strtolower($cols[0] ?? '');
                if (!is_numeric($cols[0]) ||
                    strpos($firstCol, 'nis') !== false ||
                    strpos($firstCol, 'no') !== false) {
                    continue;
                }
            }

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

            // Mapping: NIS | Nama | JK | Tempat Lahir | Tgl Lahir | Nama Ayah | Nama Ibu | NISN
            $nis         = $cols[0] ?? '';
            $nama        = $cols[1] ?? '';
            $jk          = strtoupper($cols[2] ?? 'L');
            $tempatLahir = $cols[3] ?? '';
            $tglLahir    = $cols[4] ?? '';
            $namaAyah    = $cols[5] ?? '';
            $namaIbu     = $cols[6] ?? '';
            $nisn        = $cols[7] ?? '';

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

            if (!in_array($jk, array('L','P'))) $jk = 'L';

            // Normalkan tanggal
            $tglLahirFinal = null;
            if (!empty($tglLahir)) {
                if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $tglLahir)) {
                    $tglLahirFinal = $tglLahir;
                } 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);
                }
            }

            // NISN: kosong → NULL
            $nisnFinal = (!empty($nisn) && is_numeric($nisn)) ? $nisn : null;

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

            try {
                db_insert('siswa', array(
                    'nis'           => $nis,
                    'nisn'          => $nisnFinal,
                    'nama'          => sanitize($nama),
                    'jenis_kelamin' => $jk,
                    'tempat_lahir'  => sanitize($tempatLahir),
                    'tanggal_lahir' => $tglLahirFinal,
                    'nama_ayah'     => sanitize($namaAyah),
                    'nama_ibu'      => sanitize($namaIbu),
                    'kelas_id'      => $kelasId ?: null,
                    'tahun_masuk'   => date('Y'),
                    'status'        => 'aktif',
                ));
                $berhasil++;
            } catch (Exception $e) {
                $gagal++;
                $pesanGagal[] = "Baris $rowNum: Gagal simpan — " . $e->getMessage();
            }
        }

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

// Download template
if (isset($_GET['download_template'])) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="template_import_siswa.csv"');
    echo "\xEF\xBB\xBF";
    echo "NIS;Nama;JK;Tempat Lahir;Tgl Lahir;Nama Ayah;Nama Ibu;NISN\n";
    echo "2024001;Ahmad Fadhil;L;Lamongan;2010-05-15;Bapak Contoh;Ibu Contoh;1234567890\n";
    echo "2024002;Siti Aminah;P;Gresik;2010-08-20;Bapak Contoh;Ibu Contoh;\n";
    exit;
}

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;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;">
            Pemisah <code>;</code> atau <code>,</code> otomatis terdeteksi. BOM UTF-8 ditangani otomatis.
          </div>
        </div>
        <div class="form-group">
          <label class="form-label">Kelas Tujuan</label>
          <select name="kelas_id" class="form-control">
            <option value="">-- Pilih Kelas (opsional) --</option>
            <?php foreach ($kelasList as $k): ?>
            <option value="<?= $k['id'] ?>"><?= htmlspecialchars($k['nama_kelas']) ?></option>
            <?php endforeach; ?>
          </select>
        </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:</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> NIS<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> Nama Ayah<br>
        <span style="color:var(--text-muted);">Kolom 7:</span> Nama Ibu<br>
        <span style="color:var(--text-muted);">Kolom 8:</span> NISN
      </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>
        Kolom 1 (NIS) dan Kolom 2 (Nama) <strong>wajib</strong>. Kolom lain boleh kosong.
        NIS yang sudah ada di database akan dilewati.
      </div>
      <a href="?download_template=1" class="btn btn-outline btn-sm">
        <i class="fas fa-download"></i> Unduh Template CSV
      </a>
    </div>
  </div>

</div>

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