<?php

namespace App\Models;

use CodeIgniter\Model;

class SqrModel extends Model
{
   public function generatePromptPayPayload($phoneNumber, $amount)
{
    $phoneNumber = '0066' . ltrim($phoneNumber, '0'); // ปรับหมายเลขโทรศัพท์ให้อยู่ในรูปแบบสากล

    $payload = '000201'; // Payload Format Indicator
    $payload .= '010212'; // Point of Initiation Method
    $payload .= sprintf('29370016A000000677010111011300%s', $phoneNumber); // Merchant Account Info
    $payload .= '5802TH'; // Country Code
    $payload .= '5303764'; // Transaction Currency (THB)
    $payload .= sprintf('54%02d%s', strlen(number_format($amount, 2, '.', '')), number_format($amount, 2, '.', '')); // Transaction Amount
    $payload .= '6304'; // CRC Placeholder

    return $payload . $this->generateCRC16($payload); // เพิ่ม CRC16
}


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

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

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



}
