<?php
namespace Modules\Order\Services;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\File;
use Salla\ZATCA\GenerateQrCode;
use Salla\ZATCA\Tags\InvoiceDate;
use Salla\ZATCA\Tags\InvoiceTaxAmount;
use Salla\ZATCA\Tags\InvoiceTotalAmount;
use Salla\ZATCA\Tags\Seller;
use Salla\ZATCA\Tags\TaxNumber;


class QrCodeService extends Controller
{

    /**
     * @param $invoiceDate
     * @param $invoiceTotalAmount
     * @param $invoiceTaxAmount
     * @param bool $generateQrCodeImage
     * @return array
     */
    public static function generate($invoiceDate, $invoiceTotalAmount, $invoiceTaxAmount, bool $generateQrCodeImage = true): array
    {
        $taxNumber = settings('tax_number') ?? null;
        $seller    = settings('company_name') ?? null;
        //$dt = new \DateTime($invoiceDate);
        //$timestamp = $dt->format('Y-m-d\TH:i:s\Z'); // date as Zulu ISO8601
        $displayQRCodeAsBase64 = GenerateQrCode::fromArray([
            new Seller($seller), // seller name
            new TaxNumber($taxNumber), // seller tax number
            new InvoiceDate(date('Y-m-d\TH:i:s\Z', strtotime($invoiceDate))), // invoice date as Zulu ISO8601 @see https://en.wikipedia.org/wiki/ISO_8601
            //new InvoiceDate($timestamp), // invoice date as Zulu ISO8601 @see https://en.wikipedia.org/wiki/ISO_8601
            new InvoiceTotalAmount($invoiceTotalAmount), // invoice total amount
            new InvoiceTaxAmount($invoiceTaxAmount) // invoice tax amount
        ])->render();

        $data = ['qr_code' => $displayQRCodeAsBase64];
        $data['image_path'] = null;
        if ($generateQrCodeImage){
            $base64Str = str_replace('data:image/png;base64,', '', $displayQRCodeAsBase64);
            $decoded = base64_decode($base64Str);
            $qrCodePath = public_path('uploads/images/barcodes/');
            if (!File::exists($qrCodePath)){
                File::makeDirectory($qrCodePath);
            }
            $rand_string = str_replace(str_split('%\\/:*?"<>|.'), '', bcrypt(rand(11111,99999).time()));;
            $rand_string_other = str_replace(str_split('%\\/:*?"<>|.'), '', bcrypt(rand(11111,99999).time()));;
            $imageName = md5($rand_string).'_'.$rand_string_other.'_'.time().".png";
            $imageUrl = $qrCodePath . $imageName;
            file_put_contents($imageUrl, $decoded);
            $imagePath = 'uploads/images/barcodes/'.$imageName;
            $data['image_path'] = $imagePath;
            $data['image'] = asset($imagePath);
        }

        return $data;
    }

} //end of class
