<?php
include "config.php";
session_start();
header('Content-Type: application/json');

if (!isset($_GET['code']) || empty($_GET['code'])) {
    echo json_encode(["status" => "error", "message" => "Kode QR tidak ditemukan"]);
    exit;
}

$code = mysqli_real_escape_string($conn, $_GET['code']);

// Cek apakah kode adalah NISN siswa
$siswa_query = mysqli_query($conn, "SELECT nisn FROM siswa WHERE nisn = '$code' AND status = 'aktif' LIMIT 1");
if (mysqli_num_rows($siswa_query) > 0) {
    echo json_encode([
        "status" => "success", 
        "jenis" => "siswa", 
        "code" => $code,
        "message" => "QR Code siswa terdeteksi"
    ]);
    exit;
}

// Cek apakah kode adalah NIP guru
$guru_query = mysqli_query($conn, "SELECT nip FROM guru WHERE nip = '$code' AND status = 'aktif' LIMIT 1");
if (mysqli_num_rows($guru_query) > 0) {
    echo json_encode([
        "status" => "success", 
        "jenis" => "guru", 
        "code" => $code,
        "message" => "QR Code guru terdeteksi"
    ]);
    exit;
}

// Jika tidak dikenali sebagai siswa atau guru
echo json_encode([
    "status" => "error", 
    "message" => "QR Code tidak valid. Pastikan memindai QR Code yang benar."
]);
exit;
?>