<?php

namespace App\Controllers;

use App\Models\QrTransactionModel;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;

class QrCodeController extends BaseController
{
    public function index()
    {
        return view('qrcode_form');
    }

   public function generate()
{
    // Generate QR Code Text
    $amountFormatted = number_format($this->request->getPost('amount'), 2, '.', '');
    $qrCodeText = $this->generatePromptPayQR($this->request->getPost('promptpay_number'), $amountFormatted);

    // Generate QR Code Image
    $qrCode = new \Endroid\QrCode\QrCode($qrCodeText);
    $writer = new \Endroid\QrCode\Writer\PngWriter();

    // Save QR Code to 'public/uploads'
    $path = FCPATH . 'uploads/qr_code.png'; // Path ใน public/uploads
    $result = $writer->write($qrCode);
    $result->saveToFile($path);

    // ส่ง URL สำหรับแสดง QR Code
    return view('qrcode_display', [
        'qrImagePath' => base_url('uploads/qr_code.png')
    ]);
}


    private function generatePromptPayQR($promptpayNumber, $amount)
    {
        $payload = "00020101021129370016A0000006770101110113{$promptpayNumber}5802TH5303764";
        $payload .= sprintf("54%02d%s", strlen($amount), $amount);
        $crc16 = $this->calculateCRC16($payload . '6304');
        return $payload . $crc16;
    }

    private function calculateCRC16($payload)
    {
        $crc = 0xFFFF;
        $polynomial = 0x1021;

        for ($i = 0; $i < strlen($payload); $i++) {
            $crc ^= ord($payload[$i]) << 8;
            for ($j = 0; $j < 8; $j++) {
                if (($crc & 0x8000) != 0) {
                    $crc = ($crc << 1) ^ $polynomial;
                } else {
                    $crc = $crc << 1;
                }
            }
        }

        return strtoupper(dechex($crc & 0xFFFF));
    }
}
