<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use Picqer\Barcode\BarcodeGeneratorPNG;

class Barcode extends Controller
{
    public function generate($text = '123456')
    {
        helper('filesystem');

        $generator = new BarcodeGeneratorPNG();
        $barcode = $generator->getBarcode($text, $generator::TYPE_CODE_128);

        // Buat folder jika belum ada
        $folder = WRITEPATH . 'barcodes/';
        if (!is_dir($folder)) {
            mkdir($folder, 0777, true);
        }

        $filename = $folder . $text . '.png';
        write_file($filename, $barcode);

        // Output langsung ke browser jika diakses langsung
        return $this->response
            ->setHeader('Content-Type', 'image/png')
            ->setBody($barcode);
    }
}
