<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class EfacturaInvoiceBuilder {
    private $data;

    public function __construct() {
        $this->data = [];
    }

    public function setContEmitent($contEmitent) {
        $this->data['cont_emitent'] = $contEmitent;
    }

    public function setBankNameEmitent($bankNameEmitent) {
        $this->data['bank_name_emitent'] = $bankNameEmitent;
    }

    public function setPaymentCode($paymentCode) {
        $this->data['payment_code'] = $paymentCode;
    }

    public function setMoneda($moneda) {
        $this->data['moneda'] = $moneda;
    }

    public function setTipPlata($tipPlata) {
        $this->data['tip_plata'] = $tipPlata;
    }

    public function setCotaTVA($total_tva, $total_ftva) {
        // Check if $total_ftva is zero to avoid division by zero
        if ($total_ftva != 0) {
            $tva_percentage = ($total_tva / $total_ftva) * 100;
            $this->data['cota_tva'] = number_format($tva_percentage, 2);
        } else {
            // Handle the case when $total_ftva is zero
            $this->data['cota_tva'] = 0.00; // or any other appropriate value
        }
    }

    public function setIdFactura($idFactura) {
        $this->data['id_factura'] = $idFactura;
    }

    public function setDataFactura($dataFactura) {
        $this->data['data_factura'] = $dataFactura;
    }

    public function setDataScadenta($dataScadenta) {
        $this->data['data_scadenta'] = $dataScadenta;
    }

    public function setDelegatEmail($delegatEmail) {
        $this->data['delegat_email'] = $delegatEmail;
    }

    public function setCodTara($codTara) {
        $this->data['cod_tara'] = $codTara;
    }

    public function setCodFiscal($codFiscal) {
        $this->data['cod_fiscal'] = $codFiscal;
    }

    public function setCuiNormalizat($cuiNormalizat) {
        // Check if the VAT number starts with "RO" and remove it if present
        if (substr($cuiNormalizat, 0, 2) === 'RO') {
            $this->data['cui_normalizat'] = substr($cuiNormalizat, 2);
        } else {
            $this->data['cui_normalizat'] = $cuiNormalizat;
        }
    }

    public function setNumeCompanie($numeCompanie) {
        $this->data['nume_companie'] = $numeCompanie;
    }

    public function setDelegatNume($delegatNume) {
        $this->data['delegat_nume'] = $delegatNume;
    }

    public function setDelegatTelefon($delegatTelefon) {
        $this->data['delegat_telefon'] = $delegatTelefon;
    }

    public function setCuiClient($cuiClient) {
        $this->data['cui_client'] = $cuiClient;
    }

    public function setCodTaraClient($codTaraClient) {
        $this->data['cod_tara_client'] = $codTaraClient;
    }

    public function setNumeClient($numeClient) {
        // Remove backslashes and double quotes from the company name
        $cleanedCompanyName = stripslashes($numeClient);
        $cleanedCompanyName = str_replace('"', '', $cleanedCompanyName);
        
        // Optionally, you can remove any additional whitespace
        $cleanedCompanyName = trim($cleanedCompanyName);
    
        $this->data['nume_client'] = $cleanedCompanyName;
    }

    public function setJudetClient($judetClient) {
        $this->data['judet_client'] = $judetClient;
    }

    public function setOrasClient($orasClient) {
        $this->data['oras_client'] = $orasClient;
    }

    public function setOras($oras) {
        $this->data['oras'] = $oras;
    }

    public function setJudet($judet) {
        $this->data['judet'] = $judet;
    }

    public function setAdresa($adresa) {
        $this->data['adresa'] = $adresa;
    }

    public function setAdresaClient($adresaClient) {
        $this->data['adresa_client'] = $adresaClient;
    }

    public function setTotalTVA($totalTVA) {
        $this->data['total_tva'] = $totalTVA;
    }

    public function setTotalFTVA($totalFTVA) {
        $this->data['total_ftva'] = $totalFTVA;
    }

    public function setTotalCTVA($totalCTVA) {
        $this->data['total_ctva'] = $totalCTVA;
    }

    public function setCompanyId($companyId) {
        $this->data['company_id'] = $companyId;
    }

    public function setRanduri($randuri) {
        $this->data['randuri'] = $randuri;
    }

    public function setUpload($upload) {
        $this->data['upload'] = $upload;
    }

    public function build() {
        return json_encode($this->data, JSON_PRETTY_PRINT);
    }

    function debug_pretty($data) {
        echo '<pre>';
        print_r($data);
        echo '</pre>';
        die;
    }

    /**
     * Builds an invoice from the given ID
     * param $id The ID of the invoice and $xml for data xml check as 0 and 1 for sending invoice
     */
    public function buildInvoiceFromId($id, $xml = 0) {
        // Load the CodeIgniter instance
        $CI =& get_instance();

        // Load the invoice model
        $CI->load->model('invoices_model');

        // Get the invoice by ID
        $invoice = $CI->invoices_model->get($id);
        //$this->debug_pretty($invoice);

        // Get staff
        $CI->load->model('staff_model');
        $staff = $CI->staff_model->get(1);
        //$this->debug_pretty($staff);
        

        // Bank account
        $CI->load->model('billing_bank_model');
        $bank = $CI->billing_bank_model->get_active()[0];

        // States
        $CI->load->model('states_model');
        $state = $CI->states_model->get_by_short_name('Covasna');
        //$this->debug_pretty($state);

        // Countries
        $CI->load->model('countries_model');
        
        
        // Set bank details
        $this->setContEmitent($bank['iban']);
        $this->setBankNameEmitent($bank['name']);
        $this->setPaymentCode(42);
        $this->setMoneda($bank['currency_name']);
        $this->setTipPlata('transfer bancar');
        $this->setCotaTVA($invoice->total_tax, $invoice->subtotal);
        $this->setIdFactura(format_invoice_number($invoice->id));
        $this->setDataFactura($invoice->date);
        $this->setDataScadenta($invoice->duedate);
        $this->setDelegatEmail($staff->email);
        $this->setCodTara(get_option('invoice_company_country_code'));
        $this->setCodFiscal(get_option('company_vat'));
        $this->setCuiNormalizat(get_option('company_vat'));
        $this->setNumeCompanie(htmlspecialchars(get_option('invoice_company_name')));
        $this->setDelegatNume($staff->full_name);
        $this->setDelegatTelefon($staff->phonenumber);
        $this->setCuiClient($invoice->client->vat);
        $this->setCodTaraClient($CI->countries_model->get_iso($invoice->client->country));
        $this->setNumeClient(htmlspecialchars($invoice->client->company));
        if (preg_match('/^\d+$/', $invoice->client->state)) {
            // If invoice client state is an integer, use get() method
            $this->setJudetClient($CI->states_model->get($invoice->client->state)->iso3166);
        } else {
            // If invoice client state is not an integer, use get_by_short_name() method
            $this->setJudetClient($CI->states_model->get_by_short_name($invoice->client->state)->iso3166);
        }
        $this->setOras(get_option('invoice_company_city'));
        $this->setJudet($CI->states_model->get($staff->state_id)->iso3166);
        $this->setAdresa(get_option('invoice_company_address'));
        $this->setAdresaClient($invoice->client->address);
        $this->setTotalTVA($invoice->total_tax);
        $this->setTotalFTVA($invoice->subtotal);
        $this->setTotalCTVA($invoice->total);
        $this->setCompanyId(get_option('instance_id'));
        $this->setOrasClient($invoice->client->city);
        $this->setUpload($xml);

        /**
         * Randuri
         */

        // Initialize randuri arr
        $randuri = [];

        // Iterate through each element of the given array
        foreach ($invoice->items as $row) {
            // Calculate the TVA percentage value
            $tva_percentage = $row['item_tax_rate'] / 100;
            
            // Calculate the pret_tva (price with TVA) and lineExtensionAmount (price_converted)
            $pret_tva = $row['price_converted'] * $tva_percentage;
            $lineExtensionAmount = $row['price_converted'];

            // Calculate the total price
            $price = $pret_tva + $lineExtensionAmount;

            // Create randuri row (product)
            $randuri[] = [
                "id" => $row['id'],
                "name" => $row['description'],
                "quantity" => (float) $row['qty'], // Cast to float
                "type" => $row['unit'],
                "pret_tva" => number_format($pret_tva, 2),
                "lineExtensionAmount" => number_format($lineExtensionAmount, 2, '.', ''),
                "price" => number_format($price, 2, '.', '') 
            ];
        }

        $this->setRanduri(json_encode($randuri));
        

        // Return the JSON invoice
        //$this->debug_pretty($this->build());
        return $this->build();
    }

    /**
     * Build post data for invoice status check
     * param $id The ID of the invoice
     */
    function buildInvoiceStatusData($id){

        // Load the CodeIgniter instance
        $CI =& get_instance();

        // Load the invoice model
        $CI->load->model('invoices_model');

        // Get the invoice by ID
        $invoice = $CI->invoices_model->get($id);

        // CHeck if we have an invoice eindex
        if(isset($invoice->eindex) && $invoice->eindex != ''){
            
            $data = [
                'upload_index' => $invoice->eindex,
                'company_id' => get_option('instance_id')
            ];

            return $data;
        } else {
            // False on no index, that means the invoice was not sent
            return false;
        }
    }

    /**
     * Build get data for archive download
     * param $id The ID of the invoice
     */
    function buildDownloadArchiveData($id){

        // Load the CodeIgniter instance
        $CI =& get_instance();

        // Load the invoice model
        $CI->load->model('invoices_model');

        // Get the invoice by ID
        $invoice = $CI->invoices_model->get($id);

        // CHeck if we have an invoice eindex
        if(isset($invoice->eindex) && $invoice->eindex != ''){

            $queryParams = array(
                'upload_index' => $invoice->eindex,
                'company_id' => get_option('instance_id')
            );

            return $queryParams;
        } else {
            // False on no index, that means the invoice was not sent
            return false;
        }
    }

    function generate_invoice_html($invoice) {

        // Initialize an empty array to store HTML snippets
        $html_snippets = array();
        
        // 1. When we have no status and no index we consider that it was not sended
        if ($invoice->estatus === null && $invoice->eindex === null) {
            
            $html_snippets[] = '<li data-toggle="tooltip" data-title="' . _l('efactura_send_invoice') . '">
                                    <a href="' . admin_url('billing/efactura/send_invoice/'.$invoice->id) . '" onclick="return sendInvoice(event, \'' . $invoice->eindex . '\');">
                                        <span>' . _l('efactura_send_invoice') . '</span>
                                    </a>
                                </li>';
        }

        // 2. We have index but no status
        if ($invoice->estatus === null && !empty($invoice->eindex) && strlen($invoice->eindex) > 0) {
            
            // Download xml sample
            $html_snippets[] = '<li data-toggle="tooltip" data-title="' . _l('efactura_download_xml_sample') . '">
                                    <a href="' . admin_url('billing/efactura/generate_xml/'.$invoice->id) . '">' . _l('efactura_download_xml_sample') . '</a>
                                </li>';

            // Check invoice status
            $html_snippets[] = '<li data-toggle="tooltip" data-title="' . _l('efactura_check_status') . '">
                                    <a href="' . admin_url('billing/efactura/invoice_status/'.$invoice->id) . '">' . _l('efactura_check_status') . '</a>
                                </li>';
        }

        // 3. We have index but status 'nok', we give option for user to download archive
        if ($invoice->estatus === 'nok' && !empty($invoice->eindex) && strlen($invoice->eindex) > 0) {
            // Add HTML snippet for downloading archive
            $html_snippets[] = '<li data-toggle="tooltip" data-title="' . _l('efactura_download_archive') . '">
                                    <a href="' . admin_url('billing/efactura/download_archive/'.$invoice->id) . '">
                                        <span>' . _l('efactura_download_archive') . '</span>
                                    </a>
                                </li>';
            // Download xml sample
            $html_snippets[] = '<li data-toggle="tooltip" data-title="' . _l('efactura_download_xml_sample') . '">
                                    <a href="' . admin_url('billing/efactura/generate_xml/'.$invoice->id) . '">' . _l('efactura_download_xml_sample') . '</a>
                                </li>';
            $html_snippets[] = '<li data-toggle="tooltip" data-title="' . _l('efactura_send_invoice') . '">
                                    <a href="' . admin_url('billing/efactura/send_invoice/'.$invoice->id) . '">
                                        <span>' . _l('efactura_send_invoice') . '</span>
                                    </a>
                                </li>';
        }

        // 4. Status in prelucrare
        if (($invoice->estatus === 'in prelucrare' || $invoice->estatus === 'trimis') && !empty($invoice->eindex) && strlen($invoice->eindex) > 0) {
            // Download xml sample
            $html_snippets[] = '<li data-toggle="tooltip" data-title="' . _l('efactura_download_xml_sample') . '">
                                    <a href="' . admin_url('billing/efactura/generate_xml/'.$invoice->id) . '">' . _l('efactura_download_xml_sample') . '</a>
                                </li>';
            // Check invoice status
            $html_snippets[] = '<li data-toggle="tooltip" data-title="' . _l('efactura_check_status') . '">
                                    <a href="' . admin_url('billing/efactura/invoice_status/'.$invoice->id) . '">' . _l('efactura_check_status') . '</a>
                                </li>';
        }

        // 5 status ok
        if ($invoice->estatus === 'ok' && !empty($invoice->eindex) && strlen($invoice->eindex) > 0) {
            // Add HTML snippet for downloading archive
            $html_snippets[] = '<li data-toggle="tooltip" data-title="' . _l('efactura_download_archive') . '">
                                    <a href="' . admin_url('billing/efactura/download_archive/'.$invoice->id) . '">
                                        <span>' . _l('efactura_download_archive') . '</span>
                                    </a>
                                </li>';
        }
        
        // Return the array of HTML snippets
        return $html_snippets;
    }
}