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

// Log request untuk debugging
error_log("Scan process called: " . date('Y-m-d H:i:s'));
error_log("GET parameters: " . print_r($_GET, true));

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

$code = $_GET['code'];

// Cek apakah kode adalah numeric
if (!is_numeric($code)) {
    echo json_encode(["status" => "error", "message" => "Kode QR harus berisi angka"]);
    exit;
}

// Cek apakah kode adalah NISN siswa
$siswa_query = mysqli_query($conn, "SELECT nama, kelas FROM siswa WHERE nisn = '$code' AND status = 'aktif' LIMIT 1");
if ($siswa_query && mysqli_num_rows($siswa_query) > 0) {
    $siswa = mysqli_fetch_assoc($siswa_query);
    echo json_encode([
        "status" => "success", 
        "message" => "Siswa: " . $siswa['nama'] . " (" . $siswa['kelas'] . ") - QR Code valid"
    ]);
    exit;
}

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

// Jika tidak dikenali
echo json_encode([
    "status" => "error", 
    "message" => "Kode $code tidak terdaftar sebagai siswa atau guru aktif"
]);
exit;
?>