<?php

namespace App\Helpers;

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 QrCode extends Controller
{

    public static function generate($seller, $invoiceDate, $invoiceTotalAmount, $invoiceTaxAmount, $generateQrCodeImage = false)
    {
        $taxNumber = settings('tax_number');
        $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 InvoiceTotalAmount($invoiceTotalAmount), // invoice total amount
            new InvoiceTaxAmount($invoiceTaxAmount) // invoice tax amount
        ])->render();


        $data = ['qr_code' => $displayQRCodeAsBase64];
        if ($generateQrCodeImage){
            $base64Str = str_replace('data:image/png;base64,', '', $displayQRCodeAsBase64);
            $decoded = base64_decode($base64Str);
            $qrCodePath = public_path('uploads/qr_code/');
            if (!File::exists($qrCodePath)){
                File::makeDirectory($qrCodePath);
            }
            $imageName = md5(str_random()).'_'.str_random().'_'.time().".png";
            $imageUrl = $qrCodePath . $imageName;
            file_put_contents($imageUrl, $decoded);
            $data['image'] = asset('uploads/qr_code/'.$imageName);
        }

        return $data;

    }

}
