<?php

namespace app\modules\swissqrcode\service;

use App_pdf;
use CI_Controller;

class SwissQRCode
    {
    private $data = [];
    private $pdf;
    private $qrBill;
    private $type;
    protected CI_Controller $ci;

    public function __construct($data)
        {
        $this->ci = &get_instance();
        $this->type = $data['type'];      
        $this->pdf = $data['pdf_instance'];
        }

    public function isInvoice(): bool
        {
        if($this->type === 'invoice')
            {
            return true;
            }
            
        return false;    
        }
    
    public function isSwissQrEnabled(): bool
        {   
        if(get_option('swiss_qr_code_enable') === '0')
            {
            return false;
            }
            
        return true;
        }    

    public function getCompanyData(): array
        {
        return ['company_name' => get_option('invoice_company_name'),
                'company_address' => get_option('invoice_company_address'),
                'company_city' => get_option('invoice_company_city'),
                'company_zip' => get_option('invoice_company_postal_code'),
                'company_country' => get_option('invoice_company_country_code'),
                'company_iban' => get_option('swiss_qr_code_iban')];

        }
        
    public function getBillData(): array
        {
        $this->data = json_decode(json_encode($this->pdf->get_view_vars('')['invoice']), true);
        
        return ['amount_due' => $this->data['total_left_to_pay'],
                'currency' => $this->data['currency_name'],
                'invoice_nr' => sales_number_format($this->data['number'], $this->data['number_format'], $this->data['prefix'], $this->data['date']),
                //'comment' => get_option('swiss_qr_code_bill_comment'),
                'client_company' => $this->data['client']['company'],
                'client_address' => $this->data['client']['billing_street'],
                'client_zip' => $this->data['client']['billing_zip'],
                'client_city' => $this->data['client']['billing_city'],
                'client_country' => get_country($this->data['client']['billing_country'])->iso2

                ];

        }    
        
    public function render(): void
        {    
        // load Swiss QR Code Library    
        $this->loadSwissQRBillLib();    
        
        $dataset = $this->setSwissQRData();
        
        if($dataset !== false)
            {
       
            // Add Page to PDF    
            $this->pdf->AddPage(); 
        
            // Create a full payment part for TcPDF
            $output = new \Sprain\SwissQrBill\PaymentPart\Output\TcPdfOutput\TcPdfOutput($this->qrBill, 'de', $this->pdf);
            $output->setPrintable(false)->getPaymentPart();
            }
        }

    public function loadSwissQRBillLib(): void
        {
        require __DIR__ . '/../third-party/swissqrbill/vendor/autoload.php';
        
        // Create a new instance of QrBill, containing default headers with fixed values
        $this->qrBill = \Sprain\SwissQrBill\QrBill::create();
        }
        
        
    private function setSwissQRData(): bool
        {
        $qrBill = $this->qrBill;
        // get creditor info
        $creditor = $this->getCompanyData();
        //print_r($creditor);
        
        $billData = $this->getBillData();
        //print_r($billData);
        
        if(strtolower($billData['client_country']) !== 'ch')
            {
            return false;
            }
        
        // set creditor info for QR Bill
        $qrBill->setCreditor(\Sprain\SwissQrBill\DataGroup\Element\CombinedAddress::create(
            $creditor['company_name'],
            $creditor['company_address'],
            $creditor['company_zip']. ' ' . $creditor['company_city'],
            $creditor['company_country']
             ));
        
        // set IBAN for QR Bill
        $qrBill->setCreditorInformation(\Sprain\SwissQrBill\DataGroup\Element\CreditorInformation::create(
            $creditor['company_iban']
            ));
        
        
        $qrBill->setUltimateDebtor(\Sprain\SwissQrBill\DataGroup\Element\CombinedAddress::create(
            $billData['client_company'],
            $billData['client_address'],
            $billData['client_zip']. ' ' . $billData['client_city'],
            $billData['client_country']
            ));
        
        // What amount is to be paid?
        $qrBill->setPaymentAmountInformation(\Sprain\SwissQrBill\DataGroup\Element\PaymentAmountInformation::create(
            $billData['currency'],
            $billData['amount_due']
           ));
        
        // Add payment reference
        // Explicitly define that no reference number will be used by setting TYPE_NON.
        $qrBill->setPaymentReference(\Sprain\SwissQrBill\DataGroup\Element\PaymentReference::create(
            \Sprain\SwissQrBill\DataGroup\Element\PaymentReference::TYPE_NON));
        
        // add some human-readable information about what the bill is for.
        $qrBill->setAdditionalInformation(\Sprain\SwissQrBill\DataGroup\Element\AdditionalInformation::create(
            $billData['invoice_nr']));
        
        return true;    
        }
    }

