<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\SqrModel;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Writer\PngWriter;

class SqrController extends Controller
{
    public function index()
    {
        return view('sqr/index');
    }

    public function generate()
    {
        $amount = $this->request->getPost('amount');
        $phoneNumber = $this->request->getPost('phone_number');

        if (!$amount || !$phoneNumber) {
            return redirect()->back()->with('error', 'กรุณากรอกข้อมูลให้ครบถ้วน');
        }

        // สร้างข้อมูลสำหรับ QR Code
        $sqrModel = new SqrModel();
        $qrData = $sqrModel->generatePromptPayPayload($phoneNumber, $amount);

        // สร้าง QR Code
        $result = Builder::create()
        ->writer(new PngWriter())
        ->data($qrData)
        ->margin(1)
        ->size(300)
        ->build();

        $qrCodeBase64 = base64_encode($result->getString());



        return view('sqr/index', [
            'qrCode' => $qrCodeBase64,
        ]);
    }
}
