<?php

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

class Invoice extends ClientsController
{
    public function __construct()
    {
        parent::__construct();

        if (!$this->app_acl->component_loaded('invoices')) {
            show_404();
        }
    }

    public function index($id, $hash)
    {
        check_invoice_restrictions($id, $hash);
        $invoice = $this->invoices_model->get($id);
        $invoice = hooks()->apply_filters('before_client_view_invoice', $invoice);
        if (!is_client_logged_in()) {
            load_client_language($invoice->clientid);
        }

        $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('website'),
            'website' => get_option('invoice_company_website'),
            'phonenumber' => get_option('invoice_company_phonenumber'),
            'fax' => get_option('invoice_company_fax'),
        ];


        // Handle Invoice PDF generator
        if ($this->input->post('invoicepdf')) {
            $this->load->library('billing/crm_invoice', $invoice);
            $data = [
                'invoice_number' => strtoupper($invoice->prefix) . ' ' . $invoice->number,
                'return_type' => 'pdf',
                'output' => 'I',
                'company' => $company,
                'invoice' => $invoice,
            ];

            $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');
            $data['settings'] = $settings;

            $data['invoice'] = $this->crm_invoice->prepare_document();


            if ($invoice->template == '') {
                /*
               $this->load->library('mpdf_lib');
               $mpdf = new MPDF\MPDF(['mode' => 'utf-8', 'format' => 'A4-P','default_font_size'=>null,'default_font'=>null,'mgl'=>0]);
               $mpdf->useFixedNormalLineHeight = true;
               $mpdf->useFixedTextBaseline = true;
               $mpdf->adjustFontDescLineheight = 1.6;
               //$filename = mb_strtoupper(slug_it($invoice->number)).'.pdf';
               $filename = format_invoice_number($invoice->id); //mb_strtoupper(slug_it(strtoupper($invoice->prefix).$invoice->number)).'.pdf';

               $html = $this->load->view('billing/templates/v2/main',$data, true);
               //echo   $html; exit;
               $mpdf->WriteHTML($html);
               $mpdf->Output($filename, 'I');
              */
                try {
                    // add company data

                    $invoice->company = $company;
                    $invoice->settings = $settings;

                    // echo '<pre>';
                    // print_r($invoice);
                    // exit;


                    $pdf = invoice_pdf($invoice);


                } catch (Exception $e) {
                    //pre($e);
                    echo $e->getMessage();
                    die;
                }
            } else {
                $invoice->company = $company;
                $invoice->settings = $settings;
                $pdf = invoice_pdf($invoice);

                /*
                $invoice->template = 'v2';
                $this->load->library('mpdf_lib');
                $mpdf = new MPDF\MPDF(['mode' => 'utf-8', 'format' => 'A4-P','default_font_size'=>null,'default_font'=>null,'mgl'=>0]);
                $filename = format_invoice_number($invoice->id); //mb_strtoupper(slug_it(strtoupper($invoice->prefix).$invoice->number)).'.pdf';
                $mpdf->useFixedNormalLineHeight = true;
                $mpdf->useFixedTextBaseline = true;
                $mpdf->adjustFontDescLineheight = 1.6;
                $html = $this->load->view('billing/templates/'.$invoice->template.'/main', $data, true);
                $mpdf->WriteHTML($html);
                $mpdf->Output($filename, 'I');
                */
            }


            /////////////////////////////

            $invoice_number = format_invoice_number($invoice->id);
            $companyname = get_option('invoice_company_name');
            if ($companyname != '') {
                $invoice_number .= '-' . mb_strtoupper(slug_it($companyname), 'UTF-8');
            }
            $pdf->Output(mb_strtoupper(slug_it($invoice_number), 'UTF-8') . '.pdf', 'D');
            die();
        }

        // Handle $_POST payment
        if ($this->input->post('make_payment')) {
            $this->load->model('payments_model');

            /*
          if ($_POST['paymentmode'] == 'mobil_pay') {
              redirect(site_url("invoice/plateste/$id/$hash"));
          } elseif ($_POST['paymentmode'] == 'eu_platesc') {
              redirect(site_url("invoice/plateste_eu_platesc/$id/$hash"));
          } else {
            */
            if (!$this->input->post('paymentmode')) {
                set_alert('warning', _l('invoice_html_payment_modes_not_selected'));
                redirect(site_url('invoice/' . $id . '/' . $hash));
            } elseif ((!$this->input->post('amount') || $this->input->post('amount') == 0) && get_option('allow_payment_amount_to_be_modified') == 1) {
                set_alert('warning', _l('invoice_html_amount_blank'));
                redirect(site_url('invoice/' . $id . '/' . $hash));
            }
            $this->payments_model->process_payment($this->input->post(), $id);
            //}
        }

        if ($this->input->post('paymentpdf')) {
            $payment = $this->payments_model->get($this->input->post('paymentpdf'));
            // Confirm that the payment is related to the invoice.
            if ($payment->invoiceid == $id) {
                $payment->invoice_data = $this->invoices_model->get($payment->invoiceid);
                $paymentpdf = payment_pdf($payment);
                $paymentpdf->Output(mb_strtoupper(slug_it(_l('payment') . '-' . $payment->paymentid), 'UTF-8') . '.pdf', 'D');
                die;
            }
        }

        $this->app_scripts->theme('sticky-js', 'assets/plugins/sticky/sticky.js');
        $this->load->library('app_number_to_word', [
            'clientid' => $invoice->clientid,
        ], 'numberword');
        $this->load->model('payment_modes_model');
        $this->load->model('payments_model');
        $data['payments'] = $this->payments_model->get_invoice_payments($id);
        $data['payment_modes'] = $this->payment_modes_model->get();
        $data['title'] = format_invoice_number($invoice->id);
        $this->disableNavigation();
        $this->disableSubMenu();
        $data['hash'] = $hash;
        $data['invoice'] = hooks()->apply_filters('invoice_html_pdf_data', $invoice);

        //Custom TMG - EDIConnect

        if (!empty($data['invoice']->items)) {
            foreach ($data['invoice']->items as $k => $item_inv) {
                $replaced_value = '';
                $inv_date = $data['invoice']->date;

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

                    $data['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)));

                    $data['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)));

                    $data['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));

                    $data['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))));

                    $data['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))));

                    $data['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));

                    $data['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)));

                    $data['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)));

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

                }

            }
        }

        $data['invoice']->options = json_decode(get_option('invoice_settings'), TRUE);
        $data['bodyclass'] = 'viewinvoice';
        $this->data($data);
        $this->view('invoicehtml');
        add_views_tracking('invoice', $id);
        hooks()->do_action('invoice_html_viewed', $id);
        no_index_customers_area();
        $this->layout();
    }

    public function plateste($id, $hash)
    {
        $this->load->model('clients_model');
        check_invoice_restrictions($id, $hash);
        $invoice = $this->invoices_model->get($id);
        $client = $this->clients_model->get($invoice->clientid);

        $data['title'] = format_invoice_number($invoice->id);
        $this->use_navigation = false;
        $this->use_submenu = false;
        $data['hash'] = $hash;
        $data['id'] = $id;
        $data['client'] = $client;
        $data['invoice'] = hooks()->do_action('invoice_html_pdf_data', $invoice);
        $data['bodyclass'] = 'viewinvoice';
        $data['billingTypes'] = [
            ['id' => 'person', 'name' => _l('billing_type_person')],
            ['id' => 'company', 'name' => _l('billing_type_company')],
        ];
//        $this->data            = $data;
//        $this->view            = 'mobil_pay_invoicehtml';
//        add_views_tracking('invoice', $id);
//        do_action('invoice_html_viewed', $id);
//        no_index_customers_area();
//        $this->data['lang'] = 'ro';
//        $this->newLayout('default/mobil_pay_invoicehtml');

        require_once 'application/vendor/mobilpay/Payment/Request/Abstract.php';
        require_once 'application/vendor/mobilpay/Payment/Request/Card.php';
        require_once 'application/vendor/mobilpay/Payment/Invoice.php';
        require_once 'application/vendor/mobilpay/Payment/Address.php';


        #for testing purposes, all payment requests will be sent to the sandbox server. Once your account will be active you must switch back to the live server https://secure.mobilpay.ro
        #in order to display the payment form in a different language, simply add the language identifier to the end of the paymentUrl, i.e https://secure.mobilpay.ro/en for English
        $data['paymentUrl'] = 'http://sandboxsecure.mobilpay.ro';
        // $data['paymentUrl'] = 'http://secure.mobilpay.ro';
        //$paymentUrl = 'https://secure.mobilpay.ro';
        // this is the path on your server to the public certificate. You may download this from Admin -> Conturi de comerciant -> Detalii -> Setari securitate
        $x509FilePath = 'sandbox.23C1-98DX-XKTY-LQ6R-NMXL.public.cer';
        try {
            srand((float)microtime() * 1000000);
            $objPmReqCard = new Mobilpay_Payment_Request_Card();
            #merchant account signature - generated by mobilpay.ro for every merchant account
            #semnatura contului de comerciant - mergi pe www.mobilpay.ro Admin -> Conturi de comerciant -> Modifica -> Setari securitate
            $objPmReqCard->signature = '23C1-98DX-XKTY-LQ6R-NMXL';
            #you should assign here the transaction ID registered by your application for this commercial operation
            #order_id should be unique for a merchant account
            $objPmReqCard->orderId = md5(uniqid(rand()));
            #below is where mobilPay will send the payment result. This URL will always be called first; mandatory
            $objPmReqCard->confirmUrl = site_url("cron/mobilPayConfirm/$id/$hash");
            #below is where mobilPay redirects the client once the payment process is finished. Not to be mistaken for a "successURL" nor "cancelURL"; mandatory
            $objPmReqCard->returnUrl = site_url("invoice/mobilPayReturn/$id/$hash");

            #detalii cu privire la plata: moneda, suma, descrierea
            #payment details: currency, amount, description
            $objPmReqCard->invoice = new Mobilpay_Payment_Invoice();
            #payment currency in ISO Code format; permitted values are RON, EUR, USD, MDL; please note that unless you have mobilPay permission to
            #process a currency different from RON, a currency exchange will occur from your currency to RON, using the official BNR exchange rate from that moment
            #and the customer will be presented with the payment amount in a dual currency in the payment page, i.e N.NN RON (e.ee EUR)
            $objPmReqCard->invoice->currency = 'RON';
            $objPmReqCard->invoice->amount = $invoice->total;
            #available installments number; if this parameter is present, only its value(s) will be available
            //$objPmReqCard->invoice->installments= '2,3';
            #selected installments number; its value should be within the available installments defined above
            //$objPmReqCard->invoice->selectedInstallments= '3';
            //platile ulterioare vor contine in request si informatiile despre token. Prima plata nu va contine linia de mai jos.
            $objPmReqCard->invoice->tokenId = $invoice->id;
            $objPmReqCard->invoice->details = 'Plata online cu cardul';

            #detalii cu privire la adresa posesorului cardului
            #details on the cardholder address (optional)
            $billingAddress = new Mobilpay_Payment_Address();
            $billingAddress->type = (int)$client->persoana_juridica === 1 ? 'company' : 'person';
            $billingAddress->firstName = $client->fist_name;
            $billingAddress->lastName = $client->last_name;
            $billingAddress->address = $client->address;
            $billingAddress->email = $client->email;
            $billingAddress->mobilePhone = $client->phonenumber;
            $objPmReqCard->invoice->setBillingAddress($billingAddress);

            #detalii cu privire la adresa de livrare
            #details on the shipping address
            $shippingAddress = new Mobilpay_Payment_Address();
            $shippingAddress->type = (int)$client->persoana_juridica === 1 ? 'company' : 'person';
            $shippingAddress->firstName = $client->fist_name;
            $shippingAddress->lastName = $client->last_name;
            $shippingAddress->address = $client->address;
            $shippingAddress->email = $client->email;
            $shippingAddress->mobilePhone = $client->phonenumber;
            $objPmReqCard->invoice->setShippingAddress($shippingAddress);

            #uncomment the line below in order to see the content of the request
//            echo "<pre>";print_r($objPmReqCard);echo "</pre>";
            $objPmReqCard->encrypt($x509FilePath);
        } catch (Exception $e) {
        }
        $data['e'] = $e;
        $data['objPmReqCard'] = $objPmReqCard;
        $this->data = $data;
        $this->view = 'mobil_pay_redirect';
        no_index_customers_area();
        $this->layout();
    }

    public function mobilPayReturn($id, $hash)
    {
        //        check_invoice_restrictions($id, $hash);
        $invoice = $this->db->get_where('tblinvoices', ['id' => $id])->row();
        if ((int)$invoice->status === 1) {
            $client = $this->clients_model->get($invoice->clientid);
            $this->db->where('id', $id);
            $this->db->update('tblinvoices', ['status' => 2]);

            $paymentData = [
                'invoiceid' => $id,
                'amount' => $invoice->total,
                'paymentmode' => 'mobil_pay',
                'date' => date('Y-m-d'),
                'daterecorded' => date('Y-m-d h:i:s'),
            ];
            $this->db->insert('tblinvoicepaymentrecords', $paymentData);
//            if((int)$client->current_invoice_id === (int)$invoice->id){
//                $this->load->model('subscriptions_model');
//                $sub = $this->subscriptions_model->get_by_id($client->subscription_id_pending);
//                $updateData = [
//                    'subscription_id_pending'=>0,
//                    'current_invoice_id'=>0,
//                    'subscription_id'=>$client->subscription_id_pending,
//                    'subscription_confirmed'=>1,
//                    'subscription_date_start'=>date('Y-m-d',time()),
//                    'subscription_date_expiration'=>date('Y-m-d',strtotime("+{$sub->valability} months")),
//                    'nr_comunicate'=>0,
//                    'nr_comunicate_stat'=>0,
//                    'nr_interviuri'=>0,
//                    'nr_stiri'=>0,
//                    'nr_evenimente'=>0,
//                    'nr_evenimente_live'=>0,
//                    'nr_jobs'=>0,
//                    'nr_stories'=>0,
//                    'nr_brands'=>0,
//                ];
//                $this->clients_model->update($updateData,$client->userid);
//            }
            $merge_fields = [
                //                'link'=>site_url('clienti/vizualizeaza_eveniment_live/'.$item['id']),
                //                    'link_name'=>$item['name'],
                //                'comunicat'=>$comunicat,
                //                'comunicatestat'=>$comunicatestat,
                //                'interviu'=>$interviu,
                //                'stiri'=>$stiri,
                //                'evenimente'=>$evenimente,
                //                'evenimentelive'=>$evenimentelive,
                //                'joburi'=>$joburi,
                '{contact_firstname}' => $client->first_name,
                'contact_firstname' => $client->first_name,
                '{contact_lastname}' => $client->last_name,
                'contact_lastname' => $client->last_name,
            ];
            $this->load->model('emails_model');
            $this->emails_model->send_email_template('client_email_invoice_paid', $client->email, $merge_fields);
        }
        redirect(site_url("invoice/$id/$hash?notify"));
    }

    public function plateste_eu_platesc($id, $hash)
    {
        $this->load->model('clients_model');
        check_invoice_restrictions($id, $hash);
        $invoice = $this->invoices_model->get($id);
        $client = $this->clients_model->get($invoice->clientid);

        $mid = '44840994178';
        $key = 'BF0641AEA759BDA44FEBACB68E29D99F0DBC2ACA';

        $data = array(
            'amount' => $invoice->total,
            'curr' => 'RON',
            'invoice_id' => $id,
            'order_desc' => $invoice->prefix . $invoice->number,
            'merch_id' => $mid,
            'timestamp' => date('YmdHis'),
            'nonce' => md5(mt_rand() . time()),
        );

        $data['fp_hash'] = strtoupper($this->euplatesc_mac($data, $key));
        $this->data = ['data' => $data];
        $this->view = 'eu_platesc_redirect';
        $this->layout();
    }

    public function euplatesc_mac($data, $key)
    {
        $str = null;
        foreach ($data as $d) {
            if ($d === null || strlen($d) == 0) {
                $str .= '-';
            } else {
                $str .= strlen($d) . $d;
            }
        }
        return hash_hmac('MD5', $str, pack('H*', $key));
    }
}
