<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/functions.php';

// Cek login
cek_login();

// Cek akses
if (!cek_akses('qrcode', 'generate')) {
    header("Location: " . BASE_URL . "/index.php?access=denied");
    exit();
}

// Cek ID
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header("Location: " . BASE_URL . "/modules/qrcode/index.php?error=" . urlencode("ID karyawan tidak valid!"));
    exit();
}

$id = (int)$_GET['id'];

// Ambil data karyawan
$query = "SELECT * FROM karyawan WHERE id = $id";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) == 0) {
    header("Location: " . BASE_URL . "/modules/qrcode/index.php?error=" . urlencode("Data karyawan tidak ditemukan!"));
    exit();
}

$karyawan = mysqli_fetch_assoc($result);

// Buat direktori jika belum ada
if (!is_dir(QR_DIR)) {
    mkdir(QR_DIR, 0777, true);
}

// Kita akan menggunakan php QR code library
include $_SERVER['DOCUMENT_ROOT'] . '/yoga/vendor/phpqrcode/qrlib.php';

// Data yang akan disimpan di QR Code (JSON)
$qrdata = json_encode([
    'id' => $id,
    'nik' => $karyawan['nik'],
    'nama' => $karyawan['nama']
]);

// Nama file QR Code
$qrcode_name = 'qr_' . $karyawan['nik'] . '_' . time() . '.png';
$qrcode_path = QR_DIR . $qrcode_name;

// Generate QR Code
QRcode::png($qrdata, $qrcode_path, QR_ECLEVEL_L, 10, 2);

// Update data karyawan dengan nama file QR Code
$update_query = "UPDATE karyawan SET qrcode = '$qrcode_name' WHERE id = $id";
if (mysqli_query($conn, $update_query)) {
    header("Location: " . BASE_URL . "/modules/qrcode/index.php?success=" . urlencode("QR Code berhasil digenerate!"));
} else {
    header("Location: " . BASE_URL . "/modules/qrcode/index.php?error=" . urlencode("Gagal menyimpan data QR Code!"));
}
exit();
?>