<?php

namespace App\Controllers;

use Mpdf\Mpdf;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Builder\Builder;
use App\Controllers\AdminController;
use Endroid\QrCode\Writer\PngWriter;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\RoundBlockSizeMode;
use Endroid\QrCode\ErrorCorrectionLevel;


class QrCodeController extends AdminController
{
    public function generate($id)
    {
        // Define the product URL
        $url = base_url("products/show/$id");

        // if (class_exists(class: \Endroid\QrCode\Builder\Builder::class)) {
        //     echo "Builder class is available!";
        // } else {
        //     echo "Builder class NOT found!";
        // }
        // exit;

        // Create QR Code
        $result = \Endroid\QrCode\Builder\Builder::create()
        ->writer(new PngWriter())
        ->data($url)
        ->encoding(new Encoding('UTF-8'))
        ->errorCorrectionLevel(ErrorCorrectionLevel::High)
        ->size(300)
        ->margin(10)
        ->roundBlockSizeMode(RoundBlockSizeMode::Margin)
        ->foregroundColor(new Color(0, 0, 0)) // Black
        ->backgroundColor(new Color(255, 255, 255)) // White
        ->build();

        // Get QR Code as PNG string
        $qrCodeImage = $result->getString();

die(var_dump($url));
        // Convert QR Code image to Base64 for embedding in PDF
        $base64Qr = base64_encode($qrCodeImage);

        // Generate PDF using mPDF
        $mpdf = new Mpdf();
        $mpdf->WriteHTML('<h1 style="text-align: center;">QR Code for Product</h1>');
        $mpdf->WriteHTML('<p style="text-align: center;">Scan this QR code to view the product:</p>');
        $mpdf->WriteHTML('<div style="text-align: center;"><img src="data:image/png;base64,' . $base64Qr . '" /></div>');

        // Output PDF as download
        return $mpdf->Output('QRCode_Product_' . $id . '.pdf', 'D');
    }
}
