<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Qr extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        // Load library QR Code manual
        require_once APPPATH . 'libraries/phpqrcode/qrlib.php';

        // Cek apakah user sudah login
        if (!$this->session->userdata('logged_in')) {
            redirect('login');
        }
    }

    // Tampilkan QR (dengan margin kecil)
    public function show($text = "contoh")
    {
        header("Content-Type: image/png");

        // Param: text, outfile, ECC, size, margin
        QRcode::png($text, null, QR_ECLEVEL_H, 8, 1);
    }

    // Download QR Code
    public function download($text = "contoh")
    {
        $fileName = "QR_" . time() . ".png";
        $tempDir = FCPATH . "downloads/";

        if (!is_dir($tempDir)) {
            mkdir($tempDir, 0777, true);
        }

        $filePath = $tempDir . $fileName;

        // Generate QR ke file (margin diperkecil)
        QRcode::png($text, $filePath, QR_ECLEVEL_H, 8, 1);

        // Force download
        header('Content-Type: image/png');
        header('Content-Disposition: attachment; filename="'.$fileName.'"');
        readfile($filePath);

        // Hapus setelah download
        unlink($filePath);
    }
}
