<?php
session_start();
require_once '../config/koneksi.php';

$jenis_login = $_POST['jenis_login'] ?? 'pegawai';

if ($jenis_login === 'siswa') {
    $no_ujian = trim($_POST['no_ujian'] ?? '');

    if ($no_ujian === '') {
        header('Location: ../index.php?error=siswa');
        exit;
    }

    $stmt = $conn->prepare('SELECT * FROM siswa WHERE no_ujian=? LIMIT 1');
    $stmt->bind_param('s', $no_ujian);
    $stmt->execute();
    $siswa = $stmt->get_result()->fetch_assoc();

    if ($siswa) {
        $_SESSION['login'] = true;
        $_SESSION['role'] = 'siswa';
        $_SESSION['siswa_id'] = $siswa['id'];
        $_SESSION['nama_siswa'] = $siswa['nama'];
        $_SESSION['no_ujian'] = $siswa['no_ujian'];
        header('Location: ../siswa/status_lulus.php');
        exit;
    }

    header('Location: ../index.php?error=siswa');
    exit;
}

$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';

$stmt = $conn->prepare('SELECT * FROM users WHERE username=? LIMIT 1');
$stmt->bind_param('s', $username);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if ($user && password_verify($password, $user['password'])) {
    $_SESSION['login'] = true;
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['role'] = $user['role'] ?? 'admin';
    $_SESSION['nama_admin'] = $user['nama_lengkap'];
    header('Location: ../admin/dashboard.php');
    exit;
}

header('Location: ../index.php?error=pegawai');
exit;
