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

// Cek login
cek_login();

// Hanya untuk role karyawan
if ($_SESSION['role'] != 'karyawan') {
    header("Location: " . BASE_URL . "/modules/qrcode/index.php");
    exit();
}

// Ambil data karyawan
$user_id = $_SESSION['user_id'];
$query = "SELECT * FROM karyawan WHERE user_id = $user_id";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) == 0) {
    header("Location: " . BASE_URL . "/index.php?error=" . urlencode("Data karyawan Anda belum terdaftar."));
    exit();
}

$karyawan = mysqli_fetch_assoc($result);
$karyawan_id = $karyawan['id'];

$error = '';
$success = '';

// Proses generate QR Code
if (isset($_POST['generate'])) {
    if (!is_dir(QR_DIR)) {
        mkdir(QR_DIR, 0777, true);
    }

    include_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/vendor/phpqrcode/qrlib.php';

    $qrdata = json_encode([
        'id' => $karyawan_id,
        'nik' => $karyawan['nik'],
        'nama' => $karyawan['nama']
    ]);

    $qrcode_name = 'qr_' . preg_replace('/[^a-zA-Z0-9]/', '', $karyawan['nik']) . '_' . time() . '.png';
    $qrcode_path = QR_DIR . $qrcode_name;

    // Hapus QR Code lama jika ada
    if (!empty($karyawan['qrcode']) && file_exists(QR_DIR . $karyawan['qrcode'])) {
        unlink(QR_DIR . $karyawan['qrcode']);
    }

    QRcode::png($qrdata, $qrcode_path, QR_ECLEVEL_L, 10, 2);

    $update_query = "UPDATE karyawan SET qrcode = '$qrcode_name' WHERE id = $karyawan_id";
    if (mysqli_query($conn, $update_query)) {
        $success = "QR Code baru berhasil di-generate!";
        $result = mysqli_query($conn, $query);
        $karyawan = mysqli_fetch_assoc($result);
    } else {
        $error = "Gagal menyimpan data QR Code!";
    }
}
?>

<!-- Main Content -->
<div class="main-content flex-1 p-8">
    <div class="flex justify-between items-center mb-6">
        <div>
            <h2 class="text-3xl font-bold text-white">QR Code Absensi Saya</h2>
            <p class="text-slate-400">Gunakan QR Code ini untuk melakukan absensi.</p>
        </div>
        <a href="<?php echo BASE_URL; ?>/index.php" class="bg-slate-700 hover:bg-slate-600 text-white font-bold py-2.5 px-6 rounded-lg transition-colors">
            Dashboard
        </a>
    </div>
    
    <?php if (!empty($error)): ?>
    <div class="bg-red-500/20 border border-red-500/30 text-red-300 px-4 py-3 rounded-lg relative mb-6 text-sm flex items-center gap-3" role="alert">
        <i class="fas fa-exclamation-circle"></i><span><?php echo htmlspecialchars($error); ?></span>
    </div>
    <?php endif; ?>
    
    <?php if (!empty($success)): ?>
    <div class="bg-green-500/20 border border-green-500/30 text-green-300 px-4 py-3 rounded-lg relative mb-6 text-sm flex items-center gap-3" role="alert">
        <i class="fas fa-check-circle"></i><span><?php echo htmlspecialchars($success); ?></span>
    </div>
    <?php endif; ?>
    
    <div class="glass-effect p-8 rounded-xl shadow-lg max-w-2xl mx-auto">
        <div class="text-center">
            <p class="text-slate-400">NIK</p>
            <p class="text-xl font-semibold text-white"><?php echo htmlspecialchars($karyawan['nik']); ?></p>
            <p class="text-slate-400 mt-2">Nama Lengkap</p>
            <h3 class="text-2xl font-bold text-white"><?php echo htmlspecialchars($karyawan['nama']); ?></h3>
            <p class="text-sky-400"><?php echo htmlspecialchars($karyawan['jabatan']); ?></p>
        </div>
        
        <div class="my-8 flex justify-center">
            <?php if (!empty($karyawan['qrcode']) && file_exists(QR_DIR . $karyawan['qrcode'])): ?>
                <div class="text-center">
                    <div class="bg-white p-4 rounded-xl shadow-lg inline-block">
                        <img src="<?php echo BASE_URL; ?>/uploads/qrcode/<?php echo htmlspecialchars($karyawan['qrcode']); ?>" alt="QR Code" class="w-64 h-64 mx-auto">
                    </div>
                    <p class="text-slate-500 text-xs mt-3">Dibuat pada: <?php echo date('d F Y, H:i', filemtime(QR_DIR . $karyawan['qrcode'])); ?></p>
                </div>
            <?php else: ?>
                <div class="w-64 h-64 mx-auto border-2 border-dashed border-slate-600 rounded-xl flex items-center justify-center bg-slate-800/50">
                    <p class="text-slate-500">QR Code belum dibuat</p>
                </div>
            <?php endif; ?>
        </div>

        <div class="flex flex-col sm:flex-row items-center justify-center gap-4">
            <?php if (!empty($karyawan['qrcode']) && file_exists(QR_DIR . $karyawan['qrcode'])): ?>
                <a href="<?php echo BASE_URL; ?>/modules/qrcode/cetak.php?id=<?php echo $karyawan_id; ?>" target="_blank" class="w-full sm:w-auto bg-teal-600 hover:bg-teal-700 text-white font-bold py-3 px-6 rounded-lg transition-colors flex items-center justify-center gap-2">
                    <i class="fas fa-print"></i> Cetak
                </a>
                <form method="POST" action="" class="w-full sm:w-auto">
                    <button type="submit" name="generate" class="w-full bg-sky-600 hover:bg-sky-700 text-white font-bold py-3 px-6 rounded-lg transition-colors flex items-center justify-center gap-2">
                        <i class="fas fa-sync-alt"></i> Generate Ulang
                    </button>
                </form>
            <?php else: ?>
                <form method="POST" action="">
                    <button type="submit" name="generate" class="bg-sky-600 hover:bg-sky-700 text-white font-bold py-3 px-8 rounded-lg transition-colors flex items-center gap-2">
                        <i class="fas fa-qrcode"></i> Generate QR Code Saya
                    </button>
                </form>
            <?php endif; ?>
        </div>
        
        <div class="mt-8 border-t border-slate-700/50 pt-6">
            <div class="bg-slate-700/50 p-4 rounded-lg border border-slate-600/80">
                <h4 class="font-bold text-sky-400 mb-2 flex items-center gap-2"><i class="fas fa-info-circle"></i>Informasi</h4>
                <ul class="list-disc list-inside space-y-1 text-sm text-slate-300">
                    <li>Gunakan QR Code ini untuk melakukan absensi masuk dan pulang.</li>
                    <li>Anda dapat mencetak QR Code untuk ditempel pada kartu identitas.</li>
                    <li>Jika mengalami kendala, gunakan tombol "Generate Ulang" untuk membuat QR Code baru.</li>
                </ul>
            </div>
        </div>
    </div>
</div>

<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/footer.php';
?>