<?php
require_once __DIR__ . '/../kkn-system/includes/auth.php';
require_once __DIR__ . '/../kkn-system/includes/mailer.php';
require_once __DIR__ . '/../kkn-system/includes/data.php';

$action  = $_GET['action'] ?? '';
$error   = '';
$success = '';

// ── AKTIVASI ──────────────────────────────────────────
if ($action === 'aktivasi' && isset($_GET['token'])) {
    $token = $_GET['token'];
    $user  = fetch("SELECT * FROM kkn_users WHERE token = ? AND token_expires > NOW() AND status = 'pending'", [$token]);

    if ($user) {
        // Ambil data pending
        $pending = json_decode($user['password'], true);

        if (is_array($pending) && isset($pending['pending'])) {
            // Hash password
            $hashed = password_hash($pending['password_plain'], PASSWORD_BCRYPT);
            query("UPDATE kkn_users SET password = ?, status = 'active', token = NULL, token_expires = NULL WHERE id = ?",
                  [$hashed, $user['id']]);

            // Update email DPL jika ada
            if ($user['role'] === 'dpl') {
                query("UPDATE kkn_dpl SET user_id = ?, email = ? WHERE nidn = ?",
                      [$user['id'], $user['email'], $pending['nidn']]);
            } else {
                // Buat record mahasiswa
                $dpl = fetch("SELECT id FROM kkn_dpl WHERE id = ?", [$pending['dpl_id']]);
                insert("INSERT INTO kkn_mahasiswa (user_id, nama, nim, prodi, email, kecamatan, kabupaten, dpl_id)
                        VALUES (?,?,?,?,?,?,?,?)",
                    [$user['id'], $pending['nama'], $pending['nim'], $pending['prodi'],
                     $user['email'], $pending['kecamatan'], $pending['kabupaten'], $pending['dpl_id']]);
            }

            // Kirim kredensial
            sendCredentialEmail($user['email'], $pending['nama'], $user['username'],
                                $pending['password_plain'], $user['role']);

            header('Location: ' . BASE_URL . '/kkn-login?msg=aktivasi_berhasil');
            exit;
        }
    }
    $error = 'Link aktivasi tidak valid atau sudah kadaluarsa.';
}

// ── REGISTER ─────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $role = $_POST['role'] ?? '';

    if ($role === 'mahasiswa') {
        $nama      = trim($_POST['nama'] ?? '');
        $nim       = trim($_POST['nim'] ?? '');
        $prodi     = trim($_POST['prodi'] ?? '');
        $email     = trim($_POST['email'] ?? '');
        $kec_idx   = (int)($_POST['kecamatan_idx'] ?? -1);
        $dpl_id    = (int)($_POST['dpl_id'] ?? 0);
        $password  = $_POST['password'] ?? '';
        $password2 = $_POST['password2'] ?? '';

        if (!$nama || !$nim || !$prodi || !$email || $kec_idx < 0 || !$dpl_id || !$password)
            $error = 'Semua field wajib diisi.';
        elseif (!filter_var($email, FILTER_VALIDATE_EMAIL))
            $error = 'Format email tidak valid.';
        elseif ($password !== $password2)
            $error = 'Password tidak cocok.';
        elseif (strlen($password) < 6)
            $error = 'Password minimal 6 karakter.';
        elseif (fetch("SELECT id FROM kkn_users WHERE email = ?", [$email]))
            $error = 'Email sudah terdaftar.';
        elseif (fetch("SELECT id FROM kkn_mahasiswa WHERE nim = ?", [$nim]))
            $error = 'NIM sudah terdaftar.';
        else {
            $kec     = $DATA_KECAMATAN[$kec_idx];
            $token   = generateToken();
            $expires = date('Y-m-d H:i:s', strtotime('+24 hours'));
            $username = 'mhs_' . strtolower(preg_replace('/\s+/','', $nim));

            // Hapus data pending lama jika ada
            $existing_pending = fetch("SELECT id, status FROM kkn_users WHERE username = ?", [$username]);
            if ($existing_pending && $existing_pending['status'] === 'pending') {
                query("DELETE FROM kkn_users WHERE username = ? AND status = 'pending'", [$username]);
            }

            // Simpan data pending sebagai JSON di field password sementara
            $pending = json_encode([
                'pending' => true, 'nama' => $nama, 'nim' => $nim,
                'prodi' => $prodi, 'kecamatan' => $kec['kecamatan'],
                'kabupaten' => $kec['kabupaten'], 'dpl_id' => $dpl_id,
                'password_plain' => $password
            ]);

            insert("INSERT INTO kkn_users (username, email, password, role, status, token, token_expires)
                    VALUES (?,?,?,?,?,?,?)",
                [$username, $email, $pending, 'mahasiswa', 'pending', $token, $expires]);

            sendActivationEmail($email, $nama, $token, 'mahasiswa');
            $success = "Link aktivasi telah dikirim ke <strong>$email</strong>. Cek inbox (dan folder spam) Anda.";
        }

    } elseif ($role === 'dpl') {
        $nidn      = trim($_POST['nidn'] ?? '');
        $email     = trim($_POST['email'] ?? '');
        $password  = $_POST['password'] ?? '';
        $password2 = $_POST['password2'] ?? '';

        // Cari data DPL berdasarkan NIDN
        $dpl_data  = fetch("SELECT * FROM kkn_dpl WHERE nidn = ?", [$nidn]);

        if (!$nidn || !$email || !$password)
            $error = 'Semua field wajib diisi.';
        elseif (!$dpl_data)
            $error = 'NIDN tidak ditemukan dalam sistem. Hubungi admin LPPM.';
        elseif (!filter_var($email, FILTER_VALIDATE_EMAIL))
            $error = 'Format email tidak valid.';
        elseif ($password !== $password2)
            $error = 'Password tidak cocok.';
        elseif (strlen($password) < 6)
            $error = 'Password minimal 6 karakter.';
        elseif (fetch("SELECT id FROM kkn_users WHERE email = ?", [$email]))
            $error = 'Email sudah terdaftar.';
        elseif ($dpl_data['user_id'])
            $error = 'NIDN ini sudah memiliki akun. Silakan login.';
        else {
            $token    = generateToken();
            $expires  = date('Y-m-d H:i:s', strtotime('+24 hours'));
            $username = 'dpl_' . strtolower(preg_replace('/[^a-z0-9]/i','', $nidn));

            // Hapus data pending lama jika ada (dari percobaan daftar sebelumnya)
            $existing_pending = fetch("SELECT id, status FROM kkn_users WHERE username = ?", [$username]);
            if ($existing_pending && $existing_pending['status'] === 'pending') {
                query("DELETE FROM kkn_users WHERE username = ? AND status = 'pending'", [$username]);
            }

            $pending = json_encode([
                'pending' => true, 'nama' => $dpl_data['nama'],
                'nidn' => $nidn, 'password_plain' => $password
            ]);

            insert("INSERT INTO kkn_users (username, email, password, role, status, token, token_expires)
                    VALUES (?,?,?,?,?,?,?)",
                [$username, $email, $pending, 'dpl', 'pending', $token, $expires]);

            sendActivationEmail($email, $dpl_data['nama'], $token, 'dpl');
            $success = "Link aktivasi telah dikirim ke <strong>$email</strong>. Cek inbox (dan folder spam) Anda.";
        }
    }
}

// Data untuk form
$dpl_list = fetchAll("SELECT id, nama, kecamatan, kabupaten FROM kkn_dpl ORDER BY nama");
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<link rel="icon" type="image/png" href="<?= BASE_URL ?>/kkn-system/assets/logo-smart-kkn.png">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Daftar Akun — Sistem KKN UMUS 2026</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Playfair+Display:wght@700&display=swap" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Inter',sans-serif;min-height:100vh;background:linear-gradient(135deg,#0D2E5C 0%,#1A56A4 100%);display:flex;align-items:flex-start;justify-content:center;padding:2rem 1rem;}
.card{background:#fff;border-radius:16px;padding:2.5rem;width:100%;max-width:520px;box-shadow:0 20px 60px rgba(0,0,0,.25);margin:auto;}
.logo{text-align:center;margin-bottom:2rem;}
.logo img{width:56px;height:56px;object-fit:contain;}
.logo h1{font-family:'Playfair Display',serif;font-size:1.2rem;color:#0D2E5C;margin-top:.5rem;}
.logo p{font-size:.75rem;color:#8A96A8;}
.tabs{display:flex;gap:.5rem;margin-bottom:1.75rem;background:#F5F7FA;border-radius:10px;padding:.3rem;}
.tab{flex:1;padding:9px;text-align:center;border-radius:8px;cursor:pointer;font-size:.85rem;font-weight:600;color:#8A96A8;transition:all .2s;border:none;background:none;font-family:'Inter',sans-serif;}
.tab.active{background:#fff;color:#0D2E5C;box-shadow:0 2px 8px rgba(0,0,0,.1);}
.form-section{display:none;}
.form-section.active{display:block;}
.form-group{margin-bottom:1.1rem;}
.form-group label{display:block;font-size:.8rem;font-weight:600;color:#2C3545;margin-bottom:.35rem;}
.form-group input,.form-group select{width:100%;padding:10px 13px;border:1.5px solid #E2E8F0;border-radius:8px;font-size:.88rem;font-family:'Inter',sans-serif;transition:border-color .2s;outline:none;background:#fff;}
.form-group input:focus,.form-group select:focus{border-color:#1A56A4;}
.form-row{display:grid;grid-template-columns:1fr 1fr;gap:.75rem;}
.btn{width:100%;padding:13px;background:#0D2E5C;color:#fff;border:none;border-radius:8px;font-size:.92rem;font-weight:700;cursor:pointer;font-family:'Inter',sans-serif;transition:background .2s;margin-top:.5rem;}
.btn:hover{background:#1A56A4;}
.error{background:#FFF5F5;border:1px solid #FED7D7;color:#C53030;padding:10px 14px;border-radius:8px;font-size:.82rem;margin-bottom:1rem;}
.success{background:#F0FFF4;border:1px solid #C6F6D5;color:#276749;padding:12px 14px;border-radius:8px;font-size:.85rem;margin-bottom:1rem;}
.links{text-align:center;margin-top:1.25rem;font-size:.82rem;color:#8A96A8;}
.links a{color:#1A56A4;font-weight:600;text-decoration:none;}
.note{font-size:.75rem;color:#8A96A8;margin-top:.3rem;}

@media(max-width:480px){
  body{padding:.5rem;}
  .card{padding:1.5rem 1.25rem;border-radius:10px;}
  .logo img{width:90px;height:90px;}
  .form-row{grid-template-columns:1fr;}
}
</style>
</head>
<body>
<div class="card">
  <div class="logo">
    <img src="<?= BASE_URL ?>/kkn-system/assets/logo-smart-kkn.png" alt="SMART-KKN" style="width:150px;height:150px;object-fit:contain;border-radius:12px;">
  </div>

  <?php if ($error): ?><div class="error">⚠ <?= htmlspecialchars($error) ?></div><?php endif; ?>
  <?php if ($success): ?><div class="success"><i aria-hidden="true" class="ti ti-check"></i> <?= $success ?></div><?php endif; ?>

  <?php if (!$success): ?>
  <div class="tabs">
    <button class="tab active" onclick="switchTab('mahasiswa')">Mahasiswa</button>
    <button class="tab" onclick="switchTab('dpl')">DPL</button>
  </div>

  <!-- FORM MAHASISWA -->
  <form method="POST" id="form-mahasiswa">
    <input type="hidden" name="role" value="mahasiswa">
    <div class="form-section active" id="section-mahasiswa">
      <div class="form-row">
        <div class="form-group">
          <label>Nama Lengkap *</label>
          <input type="text" name="nama" placeholder="Contoh: Siti Nur Aliyah (kapital di awal kata)" required value="<?= htmlspecialchars($_POST['nama'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label>NIM *</label>
          <input type="text" name="nim" placeholder="Nomor Induk Mahasiswa" required value="<?= htmlspecialchars($_POST['nim'] ?? '') ?>">
        </div>
      </div>
      <div class="form-group">
        <label>Program Studi *</label>
        <select name="prodi" required>
          <option value="">-- Pilih Prodi --</option>
          <?php foreach ($DATA_PRODI as $p): ?>
          <option value="<?= $p ?>" <?= (($_POST['prodi'] ?? '') === $p) ? 'selected' : '' ?>><?= $p ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label>Email (Gmail) *</label>
        <input type="email" name="email" placeholder="contoh@gmail.com" required value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
        <span class="note">Gunakan email Gmail aktif untuk menerima aktivasi</span>
      </div>
      <div class="form-group">
        <label>Lokasi KKN (Kecamatan) *</label>
        <select name="kecamatan_idx" required onchange="filterDPL(this.value)">
          <option value="">-- Pilih Kecamatan --</option>
          <?php foreach ($DATA_KECAMATAN as $i => $k): ?>
          <option value="<?= $i ?>" <?= (($_POST['kecamatan_idx'] ?? '') == $i) ? 'selected' : '' ?>>
            <?= $k['kecamatan'] ?> — <?= $k['kabupaten'] ?>
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label>Dosen Pembimbing Lapangan (DPL) *</label>
        <select name="dpl_id" id="select-dpl" required>
          <option value="">-- Pilih Kecamatan dulu --</option>
          <?php foreach ($dpl_list as $d): ?>
          <option value="<?= $d['id'] ?>" data-kec="<?= $d['kecamatan'] ?>" style="display:none">
            <?= htmlspecialchars($d['nama']) ?> (<?= $d['kecamatan'] ?>)
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label>Password *</label>
          <input type="password" name="password" placeholder="Min. 6 karakter" required>
        </div>
        <div class="form-group">
          <label>Ulangi Password *</label>
          <input type="password" name="password2" placeholder="Ulangi password" required>
        </div>
      </div>
      <button type="submit" class="btn">📧 Daftar & Kirim Aktivasi</button>
    </div>
  </form>

  <!-- FORM DPL -->
  <form method="POST" id="form-dpl">
    <input type="hidden" name="role" value="dpl">
    <div class="form-section" id="section-dpl">
      <div class="form-group">
        <label>NIDN *</label>
        <input type="text" name="nidn" placeholder="Nomor Induk Dosen Nasional" required value="<?= htmlspecialchars($_POST['nidn'] ?? '') ?>">
        <span class="note">NIDN harus terdaftar di sistem KKN UMUS 2026</span>
      </div>
      <div class="form-group">
        <label>Email (Gmail) *</label>
        <input type="email" name="email" placeholder="contoh@gmail.com" required value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
      </div>
      <div class="form-row">
        <div class="form-group">
          <label>Password *</label>
          <input type="password" name="password" placeholder="Min. 6 karakter" required>
        </div>
        <div class="form-group">
          <label>Ulangi Password *</label>
          <input type="password" name="password2" placeholder="Ulangi password" required>
        </div>
      </div>
      <button type="submit" class="btn">📧 Daftar & Kirim Aktivasi</button>
    </div>
  </form>
  <?php endif; ?>

  <div class="links">
    Sudah punya akun? <a href="<?= BASE_URL ?>/kkn-login">Login di sini</a>
  </div>
</div>

<script>
// Data kecamatan per DPL
var dplData = <?= json_encode(array_map(fn($d) => ['id'=>$d['id'],'kecamatan'=>$d['kecamatan']], $dpl_list)) ?>;

function switchTab(role) {
  document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
  document.querySelectorAll('.form-section').forEach(s => s.classList.remove('active'));
  event.target.classList.add('active');
  document.getElementById('section-' + role).classList.add('active');
}

function filterDPL(kecIdx) {
  var sel = document.getElementById('select-dpl');
  var kecamatan = '';
  var opts = document.querySelector('[name="kecamatan_idx"]').options;
  if (kecIdx !== '') {
    kecamatan = opts[parseInt(kecIdx)+1].text.split(' — ')[0].trim();
  }
  var allOpts = <?= json_encode(array_map(fn($d) => ['id'=>$d['id'],'nama'=>$d['nama'],'kecamatan'=>$d['kecamatan']], $dpl_list)) ?>;
  sel.innerHTML = '<option value="">-- Pilih DPL --</option>';
  allOpts.forEach(function(d) {
    if (!kecamatan || d.kecamatan === kecamatan) {
      var opt = document.createElement('option');
      opt.value = d.id;
      opt.textContent = d.nama + ' (' + d.kecamatan + ')';
      sel.appendChild(opt);
    }
  });
}
</script>
</body>
</html>
