<?php
// ══════════════════════════════════════════
// Tambahkan fungsi ini ke router.php
// Endpoint: siswa (POST untuk tambah)
// Auto-create akun user saat tambah siswa
// ══════════════════════════════════════════

// ── FUNGSI: Auto-create akun user untuk siswa baru ──
function createAkunSiswa($pdo, $siswaId, $nis, $nama) {
    // Password default: NIS itu sendiri (siswa harus ganti nanti)
    $passwordHash = password_hash($nis, PASSWORD_BCRYPT);

    $stmt = $pdo->prepare("
        INSERT IGNORE INTO users (username, password, role, siswa_id, nama)
        VALUES (?, ?, 'siswa', ?, ?)
    ");
    return $stmt->execute([$nis, $passwordHash, $siswaId, $nama]);
}

// ── FUNGSI: Ganti password siswa ──
function gantiPassword($pdo) {
    $body     = json_decode(file_get_contents('php://input'), true);
    $siswaId  = $body['siswa_id'] ?? '';
    $oldPass  = $body['old_password'] ?? '';
    $newPass  = $body['new_password'] ?? '';

    if (empty($siswaId) || empty($oldPass) || empty($newPass)) {
        echo json_encode(['status' => 'error', 'message' => 'Data tidak lengkap']);
        return;
    }

    $stmt = $pdo->prepare("SELECT * FROM users WHERE siswa_id = ?");
    $stmt->execute([$siswaId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user || !password_verify($oldPass, $user['password'])) {
        echo json_encode(['status' => 'error', 'message' => 'Password lama salah']);
        return;
    }

    if (strlen($newPass) < 6) {
        echo json_encode(['status' => 'error', 'message' => 'Password minimal 6 karakter']);
        return;
    }

    $hash = password_hash($newPass, PASSWORD_BCRYPT);
    $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE siswa_id = ?");
    $stmt->execute([$hash, $siswaId]);

    echo json_encode(['status' => 'success', 'message' => 'Password berhasil diubah']);
}

// ── FUNGSI: Admin reset password siswa ke NIS ──
function resetPassword($pdo) {
    $body    = json_decode(file_get_contents('php://input'), true);
    $siswaId = $body['siswa_id'] ?? '';

    if (empty($siswaId)) {
        echo json_encode(['status' => 'error', 'message' => 'siswa_id wajib diisi']);
        return;
    }

    $stmt = $pdo->prepare("SELECT nis FROM siswa WHERE id = ?");
    $stmt->execute([$siswaId]);
    $siswa = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$siswa) {
        echo json_encode(['status' => 'error', 'message' => 'Siswa tidak ditemukan']);
        return;
    }

    $hash = password_hash($siswa['nis'], PASSWORD_BCRYPT);
    $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE siswa_id = ?");
    $stmt->execute([$hash, $siswaId]);

    echo json_encode(['status' => 'success', 'message' => 'Password direset ke NIS']);
}