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

use chillerlan\QRCode\{QRCode, QROptions};

class Qrcoder extends CI_Controller {
    public function __construct(){
		parent::__construct();
	}

	public function index($data='')
	{
		$data  = trim($data);	

		//if the parameter value has slash
		$data = base64_decode(str_replace('-', '=', str_replace('_', '/', $data)));

		// quick and simple:
		//return '<img src="'.(new QRCode)->render($data).'" alt="QR Code" />';
		
		return (!empty($data)) ? '<img src="'.(new QRCode)->render($data).'" alt="QR Code" />' : '';		
	}
	
	public function generate($data='')
	{
		$data = trim($data);
		
		if(empty($data)) {
			// Return empty 1x1 transparent image if no data
			header('Content-Type: image/png');
			$img = imagecreate(1, 1);
			imagecolorallocatealpha($img, 0, 0, 0, 127);
			imagealphablending($img, false);
			imagesavealpha($img, true);
			imagepng($img);
			imagedestroy($img);
			return;
		}
		
		// Decode if base64 encoded
		if(strpos($data, '|') === false) {
			$data = base64_decode(str_replace('-', '=', str_replace('_', '/', $data)));
		}
		
		$options = new QROptions([
			'version'    => 5,
			'outputType' => QRCode::OUTPUT_IMAGE_PNG,
			'eccLevel'   => QRCode::ECC_L,
			'scale'      => 3,
			'imageBase64' => false,
		]);

		$qrcode = new QRCode($options);
		
		header('Content-Type: image/png');
		header('Cache-Control: max-age=3600');
		echo $qrcode->render($data);
	}
}