<?php

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

include_once(__DIR__ . '/App_pdf.php');

class Proforma_pdf extends App_pdf
{
    protected $invoice;

    private $invoice_number;

    public function __construct($invoice, $tag = '')
    {
        $invoice                = hooks()->apply_filters('invoice_html_pdf_data', $invoice);


        $GLOBALS['invoice_pdf'] = $invoice;

        parent::__construct();

        if (!class_exists('Invoices_model', false)) {
            $this->ci->load->model('invoices_model');
        }

        $this->tag            = $tag;
        $this->invoice        = $invoice;



        //Custom TMG - EDIConnect
        if(!empty($this->invoice->items)){
            foreach($this->invoice->items as $k=>$item_inv){
                $replaced_value = '';
                $inv_date = $this->invoice->date;

                if      (strpos($item_inv['description'], '[SAPTAMANA]') !== false) {
                    $replaced_value = _l('weeknumber') .' '. date("W", strtotime($inv_date));

                    $this->invoice->items[$k]['description']  = str_replace('[SAPTAMANA]',$replaced_value,$item_inv['description']); 
                    
                }else if (strpos($item_inv['description'], '[SAPTAMANA TRECUTA]') !== false) {
                    $replaced_value = _l('weeknumber') .' '. date('W', strtotime('-1 week', strtotime($inv_date)));

                    $this->invoice->items[$k]['description']  = str_replace('[SAPTAMANA TRECUTA]',$replaced_value,$item_inv['description']); 

                }else if (strpos($item_inv['description'], '[SAPTAMANA URMATOARE]') !== false) {
                    $replaced_value = _l('weeknumber') .' '. date('W', strtotime('+1 week', strtotime($inv_date)));

                    $this->invoice->items[$k]['description']  = str_replace('[SAPTAMANA URMATOARE]',$replaced_value,$item_inv['description']); 

                }else if (strpos($item_inv['description'], '[LUNA]') !== false) {
                    $replaced_value = ' '. date("M Y", strtotime($inv_date));

                    $this->invoice->items[$k]['description']  = str_replace('[LUNA]',$replaced_value,$item_inv['description']); 

                }else if (strpos($item_inv['description'], '[LUNA VIITOARE]') !== false) {
                    $replaced_value = date("M Y",mktime(0,0,0,date("m", strtotime($inv_date))+1,1,date("Y", strtotime($inv_date))));

                    $this->invoice->items[$k]['description']  = str_replace('[LUNA VIITOARE]',$replaced_value,$item_inv['description']); 

                }else if (strpos($item_inv['description'], '[LUNA TRECUTA]') !== false) {
                    $replaced_value = date("M Y",mktime(0,0,0,date("m", strtotime($inv_date))-1,1,date("Y", strtotime($inv_date))));

                    $this->invoice->items[$k]['description']  = str_replace('[LUNA TRECUTA]',$replaced_value,$item_inv['description']); 

                }else if (strpos($item_inv['description'], '[AN]') !== false) {
                    $replaced_value = ' '. date("Y", strtotime($inv_date));

                    $this->invoice->items[$k]['description']  = str_replace('[AN]',$replaced_value,$item_inv['description']); 

                }else if (strpos($item_inv['description'], '[ANUL TRECUT]') !== false) {
                    $replaced_value =  date('Y', strtotime('-1 year', strtotime($inv_date)));

                    $this->invoice->items[$k]['description']  = str_replace('[ANUL TRECUT]',$replaced_value,$item_inv['description']); 

                }else if (strpos($item_inv['description'], '[ANUL URMATOR]') !== false) {
                    $replaced_value =  date('Y', strtotime('+1 year', strtotime($inv_date)));

                    $this->invoice->items[$k]['description']  = str_replace('[ANUL URMATOR]',$replaced_value,$item_inv['description']); 

                }
                
            }
        }

        
        $this->invoice_number = format_proforma_number($this->invoice->id);
        $this->load_language($this->invoice->clientid);
        $this->SetTitle($this->invoice_number);
    }

    public function prepare()
    {
        $this->with_number_to_word($this->invoice->clientid);

        $options['invoice_logo'] = get_option('invoice_logo');
        $options['invoice_bg'] = get_option('invoice_bg');
        $options['invoice_stamp'] = get_option('invoice_stamp');
        $options['invoice_settings'] = get_option('invoice_settings');
        $options['invoice_settings'] = json_decode($options['invoice_settings'],true);

        $this->invoice->options = $options;

        $this->invoice->logo = logo_url_v2();
        $this->invoice->logoUrl = logo_url_v2();
        if($options['invoice_logo']){
            $this->invoice->logoUrl = APP_BASE_URL.'uploads/company/'.$options['invoice_logo'];
        }
        
        foreach ($this->invoice->items as $key => $item_inv) {

            $invoice_item_taxes = get_credit_note_item_taxes($item_inv['id']);
            
            // Loop trough $items
            if(!empty($invoice_item_taxes)){
                $this->invoice->items[$key]['tax_amount'] = 0;
    
                    foreach($invoice_item_taxes as $tax){
                        if($tax['taxrate'] != 0){
        
                            $this->invoice->items[$key]['tax_amount'] += round(($tax['taxrate']/100)*($item_inv['price_converted']*$item_inv['qty']), 4);

                        }
                }
            } else {
                $this->invoice->items[$key]['tax_amount'] = 0;
            }
        }


        $company = [
            'email'=>get_option('invoice_company_email'),
            'name'=>get_option('invoice_company_name'),
            'vat'=>get_option('company_vat'),
            'vat_eu'=>get_option('company_vat_eu'),
            'trade_no'=>get_option('company_trade'),
            'address'=>get_option('invoice_company_address'),
            'city'=>get_option('invoice_company_city'),
            'state'=>get_option('company_state'),
            'postal_code'=>get_option('invoice_company_postal_code'),
            'country_code'=>get_option('invoice_company_country_code'),
            'website'=>get_option('invoice_company_website'),
            'phonenumber'=>get_option('invoice_company_phonenumber'),
            'fax'=>get_option('invoice_company_fax'),
  
        ];

        $this->invoice->company =  $company;

        $settings['vat_payer'] = (int)get_option('settings_company_vat_payer');
        $settings['vat_on_collection'] = (int)get_option('settings_company_vat_on_collection');
        if($settings['vat_on_collection'] == 1){
          $display_vat_collection = '<p>'._l('invoice_notice_vat_on_collection').'</p>';
          $settings['display_vat_collection'] = $display_vat_collection ;
        }
        $settings['show_tax_per_item'] = (int)get_option('show_tax_per_item');
        $this->invoice->settings =  $settings;

        $this->set_view_vars([
            'status'         => $this->invoice->status,
            'invoice_number' => $this->invoice_number,
            'payment_modes'  => $this->get_payment_modes(),
            'invoice'        => $this->invoice,
        ]);
        
        return $this->build();
    }

    protected function type()
    {
        return 'proforma';
    }

    protected function file_path()
    {
		$customPath = APPPATH . 'views/themes/' . active_clients_theme() . '/views/my_proformapdf.php';
        $actualPath = APPPATH . 'views/themes/' . active_clients_theme() . '/views/proformapdf.php';
        //$customPath = APPPATH . 'views/themes/' . active_clients_theme() . '/views/my_invoicepdf.php';
        //$actualPath = APPPATH . 'views/themes/' . active_clients_theme() . '/views/invoicepdf.php';

        if (file_exists($customPath)) {
            $actualPath = $customPath;
        }

        return $actualPath;
    }

    private function get_payment_modes()
    {
        $this->ci->load->model('payment_modes_model');
        $payment_modes = $this->ci->payment_modes_model->get();

        // In case user want to include {invoice_number} or {client_id} in PDF offline mode description
        foreach ($payment_modes as $key => $mode) {
            if (isset($mode['description'])) {
                $payment_modes[$key]['description'] = str_replace('{invoice_number}', $this->invoice_number, $mode['description']);
                $payment_modes[$key]['description'] = str_replace('{client_id}', $this->invoice->clientid, $mode['description']);
            }
        }

        return $payment_modes;
    }
}
