AnonSec Shell
Server IP : 162.214.74.102  /  Your IP : 216.73.217.111
Web Server : Apache
System : Linux dedi-4363141.lrsys.com.br 3.10.0-1160.119.1.el7.tuxcare.els25.x86_64 #1 SMP Wed Oct 1 17:37:27 UTC 2025 x86_64
User : lrsys ( 1015)
PHP Version : 5.6.40
Disable Function : exec,passthru,shell_exec,system
MySQL : ON  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /home/lrsys/public_html/lrsys_apps/imobles/application/controllers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/public_html/lrsys_apps/imobles/application/controllers/invoices.php
<?php

// *************************************************************************
// *                                                                       *
// * iBilling -  Accounting, Billing Software                              *
// * Copyright (c) Sadia Sharmin. All Rights Reserved                      *
// *                                                                       *
// *************************************************************************
// *                                                                       *
// * Email: sadiasharmin3139@gmail.com                                                *
// * Website: http://www.sadiasharmin.com                                  *
// *                                                                       *
// *************************************************************************
// *                                                                       *
// * This software is furnished under a license and may be used and copied *
// * only  in  accordance  with  the  terms  of such  lic
// ense and with the *
// * inclusion of the above copyright notice.                              *
// * If you Purchased from Codecanyon, Please read the full License from   *
// * here- http://codecanyon.net/licenses/standard                         *
// *                                                                       *
// *************************************************************************
_auth();
$ui->assign('_application_menu', 'invoices');
$ui->assign('_st', $_L['Invoices']);
$ui->assign('_title', $_L['Sales'] . '- ' . $config['CompanyName']);
$action = $routes['1'];
$user = User::_info();
$ui->assign('user', $user);

Event::trigger('invoices');

switch ($action) {
    case 'add':
//find all clients.

        Event::trigger('invoices/add/');

        $extra_fields = '';
        $extra_jq = '';

        Event::trigger('add_invoice');

        $ui->assign('extra_fields', $extra_fields);

        if (isset($routes['2']) AND ( $routes['2'] == 'recurring')) {
            $recurring = true;
        } else {
            $recurring = false;
        }


        $currencies = Model::factory('Models_Currency')->find_array();


        $ui->assign('recurring', $recurring);
        $ui->assign('currencies', $currencies);



        if (isset($routes['3']) AND ( $routes['3'] != '')) {
            $p_cid = $routes['3'];
            $p_d = ORM::for_table('crm_accounts')->find_one($p_cid);
            if ($p_d) {
                $ui->assign('p_cid', $p_cid);
            }
        } else {
            $ui->assign('p_cid', '');
        }

        $ui->assign('_st', $_L['Add Invoice']);
//        $c = ORM::for_table('crm_accounts')->select('id')->select('account')->select('company')->select('email')->order_by_desc('id')->find_many();
//        $ui->assign('c', $c);

        $t = ORM::for_table('sys_tax')->find_many();
        $ui->assign('t', $t);

        $ui->assign('idate', date('Y-m-d'));


        if ($config['i_driver'] == 'default') {
            $js_file = 'invoice';
            $tpl_file = 'add-invoice.tpl';
        } elseif ($config['i_driver'] == 'v2') {
            $js_file = 'invoice_add_v2';
            $tpl_file = 'add_invoice_v2.tpl';
        } else {
            $js_file = 'invoice';
            $tpl_file = 'add-invoice.tpl';
        }

        $css_arr = array('s2/css/select2.min', 'modal', 'dp/dist/datepicker.min', 'redactor/redactor');
        $js_arr = array('redactor/redactor.min', 's2/js/select2.min', 's2/js/i18n/' . lan(), 'dp/dist/datepicker.min', 'dp/i18n/' . $config['language'], 'numeric', 'modal', 'modal-add-contact', 'modal_edit_contact_address', $js_file);

        Event::trigger('add_invoice_rendering_form');

        $ui->assign('xheader', Asset::css($css_arr));
        $ui->assign('xfooter', Asset::js($js_arr));


        $ui->assign('xjq', '

 $(\'.amount\').autoNumeric(\'init\', {

    aSign: \'' . $config['currency_code'] . ' \',
    dGroup: ' . $config['thousand_separator_placement'] . ',
    aPad: ' . $config['currency_decimal_digits'] . ',
    pSign: \'' . $config['currency_symbol_position'] . '\',
    aDec: \'' . $config['dec_point'] . '\',
    aSep: \'' . $config['thousands_sep'] . '\'

    });


 ' .
                $extra_jq);

        //ADICIONA os dados para exibir nas mensagens em JS DO MODAL
        $ui->assign('jsvar', '
        _L[\'CPF Invalid\'] = \'' . $_L['CPF Invalid'] . '\';
        _L[\'CNPJ Invalid\'] = \'' . $_L['CNPJ Invalid'] . '\';
         ');

        // Busca os meios de pagamentos
        $pmethods = ORM::for_table('sys_pmethods')
                ->order_by_asc('sorder')
                ->find_array();
        $ui->assign('payment_methods', $pmethods);


        // Busca as contas
        $accounts = ORM::for_table('sys_accounts')
                ->table_alias('acc')
                ->select('acc.id')
                ->select('acc.account')
                ->select('acc.description')
                ->select('bfv.field')
                ->select('bfv.value')
                ->join('sys_accounts_banks_fields_values', 'acc.id = bfv.id_account', 'bfv')
                ->group_by('acc.id')
                ->find_array();


        $ui->assign('accounts', $accounts);

        $ui->display($tpl_file);


        break;


    case 'edit':

        Event::trigger('invoices/edit/');

        $id = $routes['2'];
        $d = ORM::for_table('sys_invoices')->find_one($id);
        if ($d) {

            $currencies = Model::factory('Models_Currency')->find_array();
            $ui->assign('currencies', $currencies);

            $ui->assign('i', $d);
            $items = ORM::for_table('sys_invoiceitems')->where('invoiceid', $id)->order_by_asc('id')->find_many();
            // $ui->assign('items', $items);
            //lpillon 28/01/2017
            $itens_passar = 0;
            foreach ($items as $value) {
                if ($itens_passar == 0)
                    $itens_passar = $value['sys_item_id'];
                else
                    $itens_passar .= "," . $value['sys_item_id'];
            }
            //carrega as imagens dos produtos
            for ($i = 0; $i < count($items); $i++) {
                $product_images = ORM::for_table('sys_items_images')->where('sys_items_id', $items[$i]['sys_item_id'])->find_many();
                if (count($product_images) > 0) {
                    $items[$i]['image'] = APP_URL . '/application/storage/product/img/' . $product_images[0]->src;
                } else {
                    $items[$i]['image'] = APP_URL . '/ui/theme/lrsys/img/sem-imagem.jpg';
                }
            }

            $ui->assign('items', $items);

            $itensUnit = ORM::for_table('sys_items')->where_raw("id in(" . $itens_passar . ")")->find_many();
            $ui->assign('itensUnit', $itensUnit);
            $undades = ORM::for_table('sys_items_unit')->find_many();
            $ui->assign('undades', $undades);

//find the user
            $a = ORM::for_table('crm_accounts')->find_one($d['userid']);
            $ui->assign('a', $a);
            $ui->assign('d', $d);
            $ui->assign('_st', $_L['Add Invoice']);
            $c = ORM::for_table('crm_accounts')->select('id')->select('account')->select('company')->find_many();
            $ui->assign('c', $c);

            $t = ORM::for_table('sys_tax')->find_many();
            $ui->assign('t', $t);

//default idate ddate
            $ui->assign('idate', date('Y-m-d'));

            if ($config['i_driver'] == 'default') {
                $js_file = 'edit-invoice-v2';
                $tpl_file = 'edit-invoice.tpl';
            } elseif ($config['i_driver'] == 'v2') {
                $js_file = 'edit_invoice_v2n';
                $tpl_file = 'edit_invoice_v2.tpl';
            } else {
                $js_file = 'edit-invoice-v2';
                $tpl_file = 'edit-invoice.tpl';
            }

            $ui->assign('xheader', Asset::css(array('s2/css/select2.min', 'modal', 'dp/dist/datepicker.min', 'redactor/redactor')));
            $ui->assign('xfooter', Asset::js(array('redactor/redactor.min', 's2/js/select2.min', 's2/js/i18n/' . lan(), 'dp/dist/datepicker.min', 'dp/i18n/' . $config['language'], 'numeric', 'modal', 'modal-add-contact', 'modal_edit_contact_address', $js_file)));

            $ui->assign('xjq', '

 $(\'.amount\').autoNumeric(\'init\', {

    aSign: \'' . $config['currency_code'] . ' \',
    dGroup: ' . $config['thousand_separator_placement'] . ',
    aPad: ' . $config['currency_decimal_digits'] . ',
    pSign: \'' . $config['currency_symbol_position'] . '\',
    aDec: \'' . $config['dec_point'] . '\',
    aSep: \'' . $config['thousands_sep'] . '\'

    });

 ');

            //ADICIONA os dados para exibir nas mensagens em JS do MODAL
            $ui->assign('jsvar', '
        _L[\'CPF Invalid\'] = \'' . $_L['CPF Invalid'] . '\';
        _L[\'CNPJ Invalid\'] = \'' . $_L['CNPJ Invalid'] . '\';
         ');

            // Busca os meios de pagamentos
            $pmethods = ORM::for_table('sys_pmethods')
                    ->order_by_asc('sorder')
                    ->find_array();
            $ui->assign('payment_methods', $pmethods);

            // Busca as contas
            $accounts = ORM::for_table('sys_accounts')
                    ->table_alias('acc')
                    ->select('acc.id')
                    ->select('acc.account')
                    ->select('acc.description')
                    ->select('bfv.field')
                    ->select('bfv.value')
                    ->join('sys_accounts_banks_fields_values', 'acc.id = bfv.id_account', 'bfv')
                    ->group_by('acc.id')
                    ->find_array();
            $ui->assign('accounts', $accounts);

            $ui->display($tpl_file);
        } else {
            echo 'Invoice Not Found';
        }
//find all clients.

        break;


    case 'view':

        Event::trigger('invoices/view/');

        $id = $routes['2'];
        $d = ORM::for_table('sys_invoices')->find_one($id);
        if ($d) {
            
            // Pego os dados da empresa fiscais para saber se uso NFSe ou NFe
            $listaConfigApp = ORM::for_table('app_fiscal_config')->find_many();
            foreach ($listaConfigApp as $da) {
                $dadosEmpresa[$da['key']] = $da['value'];
            }
            $ui->assign('dadosEmpresa', $dadosEmpresa);
                    
            //find all activity for this user
            $items = ORM::for_table('sys_invoiceitems')->where('invoiceid', $id)->order_by_asc('id')->find_many();
            $ui->assign('items', $items);
            //find related transactions
            $trs_c = ORM::for_table('sys_transactions')->where('iid', $id)->count();

            $trs = ORM::for_table('sys_transactions')->where('iid', $id)->order_by_desc('id')->find_many();


            $ui->assign('trs', $trs);
            $ui->assign('trs_c', $trs_c);

            $emls_c = ORM::for_table('sys_email_logs')->where('iid', $id)->count();

            $emls = ORM::for_table('sys_email_logs')->where('iid', $id)->order_by_desc('id')->find_many();


            $ui->assign('emls', $emls);
            $ui->assign('emls_c', $emls_c);
//find the user
            $a = ORM::for_table('crm_accounts')->find_one($d['userid']);

            //busca os endereços para o contato
            if ($a->billing_address == 'Y') {
                $account_address = ORM::for_table('crm_accounts_address')->where('crm_account_id', $d['userid'])->where('type_address', 'billing_address')->find_many();
                $ui->assign('account_address', $account_address[0]);
            } else {
                $account_address = ORM::for_table('crm_accounts_address')->where('crm_account_id', $d['userid'])->where('type_address', 'tax_address')->find_many();
            }

            if (count($account_address) > 0) {
                $ui->assign('account_address', $account_address[0]);
                if (!empty($account_address[0]->state_id)) {
                    $stateContact = ORM::for_table('state')->find_one($account_address[0]->state_id);
                    $ui->assign('account_address_state', $stateContact);
                } else {
                    $ui->assign('account_address_state', null);
                }
                if (!empty($account_address[0]->city_id)) {
                    $stateContact = ORM::for_table('city')->find_one($account_address[0]->city_id);
                    $ui->assign('account_address_city', $stateContact);
                } else {
                    $ui->assign('account_address_city', null);
                }
            } else {
                $ui->assign('account_address', null);
                $ui->assign('account_address_city', null);
                $ui->assign('account_address_state', null);
            }

            $ui->assign('a', $a);

            $ui->assign('d', $d);

            $i_credit = $d['credit'];
            $i_due = '0.00';
            $i_total = $d['total'];
            if ($d['credit'] != '0.00') {
                $i_due = $i_total - $i_credit;
            } else {
                $i_due = $d['total'];
            }

            $i_due = number_format($i_due, 2, $config['dec_point'], $config['thousands_sep']);

            $ui->assign('i_due', $i_due);


            //find all custom fields

            $cf = ORM::for_table('crm_customfields')->where('showinvoice', 'Yes')->order_by_asc('id')->find_many();
            $ui->assign('cf', $cf);

//            $ui->assign('xheader', '
//            <link rel="stylesheet" type="text/css" href="' . $_theme . '/lib/select2/select2.css"/>
//<link rel="stylesheet" type="text/css" href="' . $_theme . '/lib/dp/dist/datepicker.min.css"/>
//
//<link rel="stylesheet" type="text/css" href="ui/lib/sn/summernote.css"/>
//<link rel="stylesheet" type="text/css" href="ui/lib/sn/summernote-bs3.css"/>
//<link rel="stylesheet" type="text/css" href="' . $_theme . '/css/modal.css"/>
//<link rel="stylesheet" type="text/css" href="ui/lib/sn/summernote-application.css"/>
//');

            $ui->assign('xheader', Asset::css(array('s2/css/select2.min', 'dp/dist/datepicker.min', 'sn/summernote', 'sn/summernote-bs3', 'modal', 'sn/summernote-application')));

//            $ui->assign('xfooter', '
//            <script type="text/javascript" src="' . $_theme . '/lib/select2/select2.min.js"></script>
//<script type="text/javascript" src="' . $_theme . '/lib/dp/dist/datepicker.min.js"></script>
//<script type="text/javascript" src="' . $_theme . '/lib/numeric.js"></script>
// <script type="text/javascript" src="' . $_theme . '/lib/modal.js"></script>
// <script type="text/javascript" src="ui/lib/sn/summernote.min.js"></script>
//<script type="text/javascript" src="ui/lib/jslib/invoice-view.js"></script>
//');

            $ui->assign('xfooter', Asset::js(array('s2/js/select2.min', 's2/js/i18n/' . lan(), 'dp/dist/datepicker.min', 'dp/i18n/' . $config['language'], 'numeric', 'modal', 'sn/summernote.min', 'jslib/invoice-view')));

            $x_html = '';

            Event::trigger('view_invoice');


            $ui->assign('x_html', $x_html);

            $ui->assign('xjq', ' $(\'.amount\').autoNumeric(\'init\', {

   
    dGroup: ' . $config['thousand_separator_placement'] . ',
    aPad: ' . $config['currency_decimal_digits'] . ',
    pSign: \'' . $config['currency_symbol_position'] . '\',
    aDec: \'' . $config['dec_point'] . '\',
    aSep: \'' . $config['thousands_sep'] . '\'

    });');

            //verifica se o modulo_fiscal_está instalado
            $pluginModuleFiscal = ORM::for_table('sys_pl')->where('c', "modulo_fiscal")->find_one();
            $moduleFiscal = false;
            if ($pluginModuleFiscal) {
                if ($pluginModuleFiscal['status'] == 1) {
                    $moduleFiscal = true;
                }
            }
            $ui->assign('moduleFiscal', $moduleFiscal);
            $ui->display('invoice-view.tpl');
        } else {
            r2(U . 'customers/list', 'e', $_L['Account_Not_Found']);
        }

        break;

    case 'add-post':

        Event::trigger('invoices/add-post/');
        $msg = '';

        if (isset($_POST['amount'])) {
            $amount = $_POST['amount'];
        } else {
            $msg .= $_L['at_least_one_item_required'] . ' <br> ';
        }

        $cid = _post('cid');
        //find user with cid
        $u = ORM::for_table('crm_accounts')->find_one($cid);


        if ($cid == '') {
            $msg .= $_L['select_a_contact'] . ' <br> ';
        }

        $notes = _post('notes');

        // find currency

        $currency_id = _post('currency');

        $currency_find = Model::factory('Models_Currency')->find_one($currency_id);

        if ($currency_find) {

            $currency = $currency_id;
            $currency_symbol = $currency_find->symbol;
            $currency_rate = $currency_find->rate;
        } else {

            $currency = 0;
            $currency_symbol = $config['currency_code'];
            $currency_rate = 1.0000;
        }


        $idate = _postDate('idate', $_c);
        $its = strtotime($idate);
        $duedate = _post('duedate');
        $dd = '';
        if ($duedate == 'due_on_receipt') {
            $dd = $idate;
        } elseif ($duedate == 'days3') {
            $dd = date('Y-m-d', strtotime('+3 days', $its));
        } elseif ($duedate == 'days5') {
            $dd = date('Y-m-d', strtotime('+5 days', $its));
        } elseif ($duedate == 'days7') {
            $dd = date('Y-m-d', strtotime('+7 days', $its));
        } elseif ($duedate == 'days10') {
            $dd = date('Y-m-d', strtotime('+10 days', $its));
        } elseif ($duedate == 'days15') {
            $dd = date('Y-m-d', strtotime('+15 days', $its));
        } elseif ($duedate == 'days30') {
            $dd = date('Y-m-d', strtotime('+30 days', $its));
        } elseif ($duedate == 'days45') {
            $dd = date('Y-m-d', strtotime('+45 days', $its));
        } elseif ($duedate == 'days60') {
            $dd = date('Y-m-d', strtotime('+60 days', $its));
        } else {

            $msg .= 'Invalid Date <br> ';
        }
        if (!$dd) {
            $msg .= 'Date Parsing Error <br> ';
        }


        $repeat = _post('repeat');
        $nd = $idate;
        if ($repeat == '0') {
            $r = '0';
        } elseif ($repeat == 'week1') {
            $r = '+1 week';
            $nd = date('Y-m-d', strtotime('+1 week', $its));
        } elseif ($repeat == 'weeks2') {
            $r = '+2 weeks';
            $nd = date('Y-m-d', strtotime('+2 weeks', $its));
        } elseif ($repeat == 'month1') {


            $r = '+1 month';
            $nd = date('Y-m-d', strtotime('+1 month', $its));
        } elseif ($repeat == 'months2') {
            $r = '+2 months';
            $nd = date('Y-m-d', strtotime('+2 months', $its));
        } elseif ($repeat == 'months3') {
            $r = '+3 months';
            $nd = date('Y-m-d', strtotime('+3 months', $its));
        } elseif ($repeat == 'months6') {
            $r = '+6 months';
            $nd = date('Y-m-d', strtotime('+6 months', $its));
        } elseif ($repeat == 'year1') {
            $r = '+1 year';
            $nd = date('Y-m-d', strtotime('+1 year', $its));
        } elseif ($repeat == 'years2') {
            $r = '+2 years';
            $nd = date('Y-m-d', strtotime('+2 years', $its));
        } elseif ($repeat == 'years3') {
            $r = '+3 years';
            $nd = date('Y-m-d', strtotime('+3 years', $its));
        } else {
            $msg .= 'Date Parsing Error <br> ';
        }


        //lpillon 18_01_2017
//        if(! _post('mtdopgto')){
//            $msg .= $_L['Payment Method Invoice-Error'].'<br>';
//        }

        if (!_post('cdtpgto')) {
            $msg .= $_L['Payment Condition Invoice-Error'] . '<br>';
        }

        if ($msg == '') {

            $qty = $_POST['qtdBe'];

            if (isset($_POST['taxed'])) {
                $taxed = $_POST['taxed'];
            } else {
                $taxed = false;
            }

            $sTotal = '0';
            $taxTotal = '0';
            $i = '0';
            $a = array();

            $taxval = '0.00';
            $taxname = '';
            $taxrate = '0.00';
            $tax = _post('tid');
            $taxed_type = _post('taxed_type');
            if ($tax != '') {
                $dt = ORM::for_table('sys_tax')->find_one($tax);
                $taxrate = $dt['rate'];
                $taxname = $dt['name'];
                $taxtype = $dt['type'];
                //
            }

            $taxed_amount = 0.00;
            $lamount = 0.00;

            foreach ($amount as $samount) {
                $samount = Finance::amount_fix($samount);
                $a[$i] = $samount;
                /* @since v 2.0 */
                $sqty = $qty[$i];
                $sqty = number_format((float) $sqty, 3, '.', '');
                //$sqty = Finance::amount_fix($sqty);
//                if (($config['dec_point']) == ',') {
//                    $samount = str_replace(',', '.', $samount);
//                    $sqty = str_replace(',', '.', $sqty);
//
//                }

                $sTotal += $samount * ($sqty);
                $lamount = $samount * ($sqty);

                if ($taxed) {
                    $c_tax = $taxed[$i];
                } else {
                    $c_tax = 'No';
                }




                if ($c_tax == 'Yes') {
                    // $a_tax = ($samount * $taxrate) / 100;

                    $taxed_amount += $lamount;
                } else {
                    $a_tax = 0.00;
                }

                //   $taxval += $a_tax;




                $i++;
            }


            $invoicenum = _post('invoicenum');
            $cn = _post('cn');


            $fTotal = $sTotal;



            // calculate discount

            $discount_amount = _post('discount_amount');
            $discount_type = _post('discount_type');
            $discount_value = '0.00';


            if ($discount_amount == '0' OR $discount_amount == '') {
                $actual_discount = '0.00';
            } else {
                if ($discount_type == 'f') {

                    $actual_discount = $discount_amount;
                    $discount_value = $discount_amount;
                } else {

                    $discount_type = 'p';
                    $actual_discount = ($sTotal * $discount_amount) / 100;
                    $discount_value = $discount_amount;
                }
            }


            $actual_discount = number_format((float) $actual_discount, 2, '.', '');



            $fTotal = $fTotal - $actual_discount;

            $actual_taxed_amount = $taxed_amount - $actual_discount;

            if ($actual_taxed_amount > 0) {
                $taxval = ($actual_taxed_amount * $taxrate) / 100;
            }




            if (($taxed_type != 'individual') AND ( $tax != '')) {

                $taxval = ($fTotal * $taxrate) / 100;
            }


            $fTotal = $fTotal + $taxval;

            $freight_by = _post('freight_by');
            if ($freight_by == 'Free shipping') {
                $freight = 0;
            } else {
                $freight = Finance::amount_fix(_post('freight'));
            }
            $fTotal+=$freight;

            //

            $datetime = date("Y-m-d H:i:s");

            $vtoken = _raid(10);
            $ptoken = _raid(10);
            $d = ORM::for_table('sys_invoices')->create();
            $d->userid = $cid;
            $d->account = $u['account'];
            $d->date = $idate;
            $d->duedate = $dd;
            $d->datepaid = $datetime;
            $d->subtotal = $sTotal;
            $d->discount_type = $discount_type;
            $d->discount_value = $discount_value;
            $d->discount = $actual_discount;
            $d->total = $fTotal;
            $d->tax = $taxval;
            $d->taxname = $taxname;
            $d->taxrate = $taxrate;
            $d->vtoken = $vtoken;
            $d->ptoken = $ptoken;
            $d->status = 'Unpaid';
            $d->notes = $notes;
            $d->r = $r;
            $d->nd = $nd;
            //others
            $d->invoicenum = $invoicenum;
            $d->cn = $cn;
            $d->tax2 = '0.00';
            $d->taxrate2 = '0.00';

            // Build 4550

            $d->currency = $currency;
            $d->currency_symbol = $currency_symbol;
            $d->currency_rate = $currency_rate;

            //lpillon 18_01_2017
            $d->paymentmethod = _post('mtdopgto');
            $d->paymentcondition = _post('cdtpgto');

            // Cleberson Falk 22_03_2017
            $d->sys_accounts_id = _post('account');
            //André CAMARGO, FRETE 29/03/2017
            $d->freight_by = $freight_by;
            $d->freight = $freight;


            //
            $d->save();
            $invoiceid = $d->id();
            $description = $_POST['desc'];
            //  $qty = $_POST['qty'];
            //  $taxed = $_POST['taxed'];

            $i = '0';
            //recebe os id dos iten, necessário para nfe 
            $item_id = $_POST['item_id'];

            foreach ($description as $item) {

                $samount = $a[$i];
                $samount = Finance::amount_fix($samount);

                if ($item == '' && $samount == '0.00') {
                    $i++;
                    continue;
                }
                /* @since v 2.0 */
                $sqty = $qty[$i];
                //$sqty = Finance::amount_fix($sqty);
                $sqty = number_format((float) $sqty, 3, '.', '');

//                echo $samount;
//                echo 'dd';
//                exit;
//                if (($config['dec_point']) == ',') {
//                    $samount = str_replace(',', '.', $samount);
//                    $sqty = str_replace(',', '.', $sqty);
//
//                }
                $ltotal = ($samount) * ($sqty);
                $d = ORM::for_table('sys_invoiceitems')->create();
                $d->invoiceid = $invoiceid;
                $d->userid = $cid;
                $d->description = $item;
                $d->qty = $sqty;
                $d->amount = $samount;
                $d->total = $ltotal;
                //atribui o id do item
                $d->sys_item_id = $item_id[$i];


                if ($taxed) {

                    if (($taxed[$i]) == 'Yes') {
                        $d->taxed = '1';
                    } else {
                        $d->taxed = '0';
                    }
                } else {
                    $d->taxed = '0';
                }


                //others
                $d->type = '';
                $d->relid = '0';
                $d->itemcode = '';
                $d->taxamount = '0.00';
                $d->duedate = date('Y-m-d');
                $d->paymentmethod = '';
                $d->notes = '';

                $d->save();
                $i++;
            }

            Event::trigger('add_invoice_posted');

            echo $invoiceid;
        } else {
            echo $msg;
        }


        break;

    case 'list':
        $where = '';
        if (_post('filter') == 'Y') {
            $_SESSION['filter_invoice_id_payment_method'] = _post('id_payment_method');
            $_SESSION['filter_invoice_situation'] = _post('situation');
            $_SESSION['filter_invoice_search'] = _post('search');
            $_SESSION['filter_invoice_period'] = _post('period');
            if ($_SESSION['filter_invoice_period'] == 'interval') {
                $_SESSION['filter_invoice_period_ini'] = _postDate('period_ini', $_c);
                $_SESSION['filter_invoice_period_end'] = _postDate('period_end', $_c);
            } else {
                $_SESSION['filter_invoice_period_ini'] = '';
                $_SESSION['filter_invoice_period_end'] = '';
            }
        }

        if (isset($_SESSION['filter_invoice_situation']) && $_SESSION['filter_invoice_situation'] != 'All' && !empty($_SESSION['filter_invoice_situation'])) {
            $where.=" AND s.status='" . $_SESSION['filter_invoice_situation'] . "'";
            $filter['filter_invoice_situation'] = $_SESSION['filter_invoice_situation'];
        } else {
            $filter['filter_invoice_situation'] = null;
        }

        if (isset($_SESSION['filter_invoice_id_payment_method']) && intval($_SESSION['filter_invoice_id_payment_method']) > 0) {
            $where.=' AND s.paymentmethod=' . $_SESSION['filter_invoice_id_payment_method'];
            $filter['id_payment_method'] = $_SESSION['filter_invoice_id_payment_method'];
        } else {
            $filter['id_payment_method'] = '';
        }

        if (isset($_SESSION['filter_invoice_search']) && !empty($_SESSION['filter_invoice_search'])) {
            $where.=" AND (s.account like '%" . $_SESSION['filter_invoice_search'] . "%' or CAST(s.id as CHAR) like '%" . $_SESSION['filter_invoice_search'] . "%')";
            $filter['filter_invoice_search'] = $_SESSION['filter_invoice_search'];
        } else {
            $filter['filter_invoice_search'] = '';
        }

        if (isset($_SESSION['filter_invoice_period']) && $_SESSION['filter_invoice_period'] != 'all' && !empty($_SESSION['filter_invoice_period'])) {

            if ($_SESSION['filter_invoice_period'] == 'day')
                $where .= " AND s.duedate = '" . date('Y-m-d') . "'";
            if ($_SESSION['filter_invoice_period'] == 'week')
                $where .= " AND WEEK(s.duedate) = WEEK('" . date('Y-m-d') . "')";
            if ($_SESSION['filter_invoice_period'] == 'month')
                $where .= " AND MONTH(s.duedate) = MONTH('" . date('Y-m-d') . "')";

            if (!empty($_SESSION['filter_invoice_period_ini'])) {
                $where .= " AND s.duedate >='" . date('Y-m-d', strtotime($_SESSION['filter_invoice_period_ini'])) . "'";
                $filter['filter_invoice_period_ini'] = $_SESSION['filter_invoice_period_ini'];
            } else {
                $filter['filter_invoice_period_ini'] = '';
            }
            if (!empty($_SESSION['filter_invoice_period_end'])) {
                $where .= " AND s.duedate <='" . date('Y-m-d', strtotime($_SESSION['filter_invoice_period_end'])) . "'";
                $filter['filter_invoice_period_end'] = $_SESSION['filter_invoice_period_end'];
            } else {
                $filter['filter_invoice_period_end'] = '';
            }


            $filter['filter_invoice_period'] = $_SESSION['filter_invoice_period'];
        } else {
            $filter['filter_invoice_period'] = '';
        }




        Event::trigger('invoices/list/');
        $view_type = 'default';
        $css_arr = array(
            'dp/dist/datepicker.min',
            's2/css/select2.min');
        $js_arr = array(
            's2/js/select2.min',
            'numeric', 'invoice-list',
            'dp/dist/datepicker.min');


        $assets_css = Asset::css($css_arr);
        $assets_js = Asset::js($js_arr);


        $sql = 'Select COUNT(s.id) as total from sys_invoices s ' . (empty($where) ? '' : " Where " . substr($where, 4));

        $c = ORM::for_table('sys_invoices')
                ->raw_query($sql)->find_one();
        $paginator = Paginator::raw_bootstrap($c->total);

        $limit = $paginator['limit'];
        $offset = $paginator['startpoint'];

        $sql = 'Select s.* from sys_invoices s ' . (empty($where) ? '' : " Where " . substr($where, 4));
        $sql .='
            LIMIT ' . $limit . ' OFFSET ' . $offset;
        $d = ORM::for_table('sys_invoices')->raw_query($sql)->find_many();



        $ui->assign('_st', $_L['Invoices'] . '<div class="btn-group pull-right" style="padding-right: 10px;">
            <a class="btn btn-success btn-xs" href="' . U . 'invoices/export_csv/' . '" style="box-shadow: none;"><i class="fa fa-download"></i></a>
        </div>');

        $ui->assign('xheader', $assets_css);
        $ui->assign('xfooter', $assets_js);
        $ui->assign('view_type', $view_type);
        $ui->assign('filter', $filter);

        $pmethods = ORM::for_table('sys_pmethods')
                ->order_by_asc('sorder')
                ->find_array();
        $ui->assign('payment_methods', $pmethods);
        $ui->assign('xjq', '
         $(\'.amount\').autoNumeric(\'init\', {

   
    dGroup: ' . $config['thousand_separator_placement'] . ',
    aPad: ' . $config['currency_decimal_digits'] . ',
    pSign: \'' . $config['currency_symbol_position'] . '\',
    aDec: \'' . $config['dec_point'] . '\',
    aSep: \'' . $config['thousands_sep'] . '\'

    });
$(".cdelete").click(function (e) {
        e.preventDefault();
        var id = this.id;
        bootbox.confirm("' . $_L['are_you_sure'] . '", function(result) {
           if(result){
               var _url = $("#_url").val();
               window.location.href = _url + "delete/invoice/" + id;
           }
        });
    });
 ');

        //bottom bar com as informações
        $total_value_invoice = 0;
        $total_value_paid = 0;
        foreach ($d as $index => $inv) {
            $total_value_invoice+=$inv['total'];
            $total_value_paid+=$inv['credit'];
            //  $tota
            
            // Vefico se tem NF
            $nota = ORM::for_table('app_fiscal_note')->where('invoice_id', $inv['id'])->find_many();
            if(count($nota) > 0)
            {
                $d[$index]['nota_fiscal'] == $nota;
            }
            else
            {
                $d[$index]['nota_fiscal'] = '';
            }
            
        }
        $ui->assign('d', $d);
        $ui->assign('paginator', $paginator);
        
        
        //verifica se o modulo_fiscal_está instalado
        $pluginModuleFiscal = ORM::for_table('sys_pl')->where('c', "modulo_fiscal")->find_one();
        $moduleFiscal = false;
        if ($pluginModuleFiscal) {
            if ($pluginModuleFiscal['status'] == 1) {
                $moduleFiscal = true;
            }
        }
        $ui->assign('moduleFiscal', $moduleFiscal);
        
        // Pego os dados da empresa fiscais para saber se uso NFSe ou NFe
        $listaConfigApp = ORM::for_table('app_fiscal_config')->find_many();
        foreach ($listaConfigApp as $da) {
            $dadosEmpresa[$da['key']] = $da['value'];
        }
        $ui->assign('dadosEmpresa', $dadosEmpresa);
        

        $bottomBar = array(
            array('type' => 'monetary', 'info' => $_L['Total Pending'], 'value' => ($total_value_invoice - $total_value_paid)),
            array('type' => 'monetary', 'info' => $_L['Total Paid'], 'value' => $total_value_paid),
            array('type' => 'monetary', 'info' => $_L['Total'], 'value' => $total_value_invoice),
            array('type' => 'int', 'info' => $_L['Total number of invoices generated'], 'value' => count($d))
        );
        $ui->assign('bottomBar', $bottomBar);

        $ui->display('list-invoices.tpl');
        break;

    case 'list-recurring':

        $d = ORM::for_table('sys_invoices')->where_not_equal('r', '0')->order_by_desc('id')->find_many();
        $ui->assign('d', $d);
        $ui->assign('xjq', '
$(".cdelete").click(function (e) {
        e.preventDefault();
        var id = this.id;
        bootbox.confirm("' . $_L['are_you_sure'] . '", function(result) {
           if(result){
               var _url = $("#_url").val();
               window.location.href = _url + "delete/invoice/" + id;
           }
        });
    });

     $(".cstop").click(function (e) {
        e.preventDefault();
        var id = this.id;
        bootbox.confirm("Are you sure? This will prevent future invoice generation from this invoice.", function(result) {
           if(result){
               var _url = $("#_url").val();
               window.location.href = _url + "invoices/stop_recurring/" + id;
           }
        });
    });

 ');
        $ui->display('list-recurring-invoices.tpl');
        break;

    case 'edit-post':

        Event::trigger('invoices/edit-post/');

        $cid = _post('cid');
        $iid = _post('iid');
        //find user with cid
        $u = ORM::for_table('crm_accounts')->find_one($cid);

        $msg = '';
        if ($cid == '') {
            $msg .= $_L['select_a_contact'] . ' <br> ';
        }

        $notes = _post('notes');


        if (isset($_POST['amount'])) {
            $amount = $_POST['amount'];
        } else {
            $msg .= $_L['at_least_one_item_required'] . ' <br> ';
        }


        // find currency

        $currency_id = _post('currency');

        $currency_find = Model::factory('Models_Currency')->find_one($currency_id);

        if ($currency_find) {

            $currency = $currency_id;
            $currency_symbol = $currency_find->symbol;
            $currency_rate = $currency_find->rate;
        } else {

            $currency = 0;
            $currency_symbol = $config['currency_code'];
            $currency_rate = 1.0000;
        }

        $idate = _postDate('idate', $_c);
        $its = strtotime($idate);
        $duedate = _postDate('ddate', $_c);
        $repeat = _post('repeat');
        $nd = $idate;
        if ($repeat == '0') {
            $r = '0';
        } elseif ($repeat == 'week1') {
            $r = '+1 week';
            $nd = date('Y-m-d', strtotime('+1 week', $its));
        } elseif ($repeat == 'weeks2') {
            $r = '+2 weeks';
            $nd = date('Y-m-d', strtotime('+2 weeks', $its));
        } elseif ($repeat == 'month1') {


            $r = '+1 month';
            $nd = date('Y-m-d', strtotime('+1 month', $its));
        } elseif ($repeat == 'months2') {
            $r = '+2 months';
            $nd = date('Y-m-d', strtotime('+2 months', $its));
        } elseif ($repeat == 'months3') {
            $r = '+3 months';
            $nd = date('Y-m-d', strtotime('+3 months', $its));
        } elseif ($repeat == 'months6') {
            $r = '+6 months';
            $nd = date('Y-m-d', strtotime('+6 months', $its));
        } elseif ($repeat == 'year1') {
            $r = '+1 year';
            $nd = date('Y-m-d', strtotime('+1 year', $its));
        } elseif ($repeat == 'years2') {
            $r = '+2 years';
            $nd = date('Y-m-d', strtotime('+2 years', $its));
        } elseif ($repeat == 'years3') {
            $r = '+3 years';
            $nd = date('Y-m-d', strtotime('+3 years', $its));
        } else {
            $msg .= 'Date Parsing Error <br> ';
        }


        if ($msg == '') {


            $qty = $_POST['qtdBe'];


            if (isset($_POST['taxed'])) {
                $taxed = $_POST['taxed'];
            } else {
                $taxed = false;
            }

            $sTotal = '0';
            $taxTotal = '0';
            $i = '0';
            $a = array();

            $taxval = '0.00';
            $taxname = '';
            $taxrate = '0.00';
            $tax = _post('tid');
            $taxed_type = _post('taxed_type');
            if ($tax != '') {
                $dt = ORM::for_table('sys_tax')->find_one($tax);
                $taxrate = $dt['rate'];
                $taxname = $dt['name'];
                $taxtype = $dt['type'];
                //
            }


            $taxed_amount = 0.00;

            $lamount = 0.00;

            foreach ($amount as $samount) {
                $samount = Finance::amount_fix($samount);

                $a[$i] = $samount;
                /* @since v 2.0 */
                $sqty = $qty[$i];

                //$sqty = Finance::amount_fix($sqty);
                $sqty = number_format((float) $sqty, 3, '.', '');
//                if (($config['dec_point']) == ',') {
//                    $samount = str_replace(',', '.', $samount);
//                    $sqty = str_replace(',', '.', $sqty);
//
//                }

                $sTotal += $samount * ($sqty);
                $lamount = $samount * ($sqty);

                if ($taxed) {
                    $c_tax = $taxed[$i];
                } else {
                    $c_tax = 'No';
                }


                if ($c_tax == 'Yes') {
                    // $a_tax = ($samount * $taxrate) / 100;
                    $taxed_amount += $lamount;
                } else {
                    $a_tax = 0.00;
                }



                $i++;
            }


            $invoicenum = _post('invoicenum');
            $cn = _post('cn');


            $fTotal = $sTotal;



            // calculate discount

            $discount_amount = _post('discount_amount');
            $discount_type = _post('discount_type');
            $discount_value = '0.00';


            if ($discount_amount == '0' OR $discount_amount == '') {
                $actual_discount = '0.00';
            } else {
                if ($discount_type == 'f') {

                    $actual_discount = $discount_amount;
                    $discount_value = $discount_amount;
                } else {

                    $discount_type = 'p';
                    $actual_discount = ($sTotal * $discount_amount) / 100;
                    $discount_value = $discount_amount;
                }
            }


            $actual_discount = number_format((float) $actual_discount, 2, '.', '');



            $fTotal = $fTotal - $actual_discount;

            if ($taxed_amount != 0.00) {
                $taxval = ($taxed_amount * $taxrate) / 100;
            }




            if (($taxed_type != 'individual') AND ( $tax != '')) {

                $taxval = ($fTotal * $taxrate) / 100;
            }




            $fTotal = $fTotal + $taxval;

            $freight_by = _post('freight_by');
            if ($freight_by == 'Free shipping') {
                $freight = 0;
            } else {
                $freight = Finance::amount_fix(_post('freight'));
            }
            $fTotal+=$freight;


            //
            // $vtoken = _raid(10);
            // $ptoken = _raid(10);
            $d = ORM::for_table('sys_invoices')->find_one($iid);
            if ($d) {
                $d->userid = $cid;
                $d->account = $u['account'];
                $d->date = $idate;
                $d->duedate = $duedate;
                $d->discount_type = $discount_type;
                $d->discount_value = $discount_value;
                $d->discount = $actual_discount;
                $d->subtotal = $sTotal;
                $d->total = $fTotal;
                $d->tax = $taxval;
                $d->taxname = $taxname;
                $d->taxrate = $taxrate;
                $d->notes = $notes;
                $d->r = $r;
                $d->nd = $nd;
                $d->invoicenum = $invoicenum;
                $d->cn = $cn;
                /*
                 * $d->userid = $cid;
                  $d->account = $u['account'];
                  $d->date = $idate;
                  $d->duedate = $dd;
                  $d->subtotal = $sTotal;
                  $d->total = $fTotal;
                  $d->tax = $taxval;
                  $d->taxname = $taxname;
                  $d->taxrate = $taxrate;
                  $d->vtoken = $vtoken;
                  $d->ptoken = $ptoken;
                  $d->status = 'Unpaid';
                  $d->notes = $notes;
                  $d->r = $r;
                  $d->nd = $nd;
                 */

                //  $d->status = 'Unpaid';
                // Build 4550
                // Cleberson Falk 22_03_2017
                $d->paymentmethod = _post('mtdopgto');
                $d->paymentcondition = _post('cdtpgto');

                // Cleberson Falk 22_03_2017
                $d->sys_accounts_id = (_post('mtdopgto') == 10) ? _post('account') : null;
                //FRETE ANDRÉ CAMARGO 29/03/2017
                $d->freight_by = $freight_by;
                $d->freight = $freight;

                $d->currency = $currency;
                $d->currency_symbol = $currency_symbol;
                $d->currency_rate = $currency_rate;

                $d->save();
                $invoiceid = $iid;
                $description = $_POST['desc'];
                //recebe os id dos itens
                $item_id = $_POST['item_id'];

                // $taxed = $_POST['taxed'];
                //   $taxed = '0';
                $i = '0';
// first delete all related items
                $x = ORM::for_table('sys_invoiceitems')->where('invoiceid', $iid)->delete_many();
                foreach ($description as $item) {



                    $samount = $a[$i];
                    $samount = Finance::amount_fix($samount);

                    if ($item == '' && $samount == '0.00') {

                        $i++;
                        continue;
                    }

                    /* @since v 2.0 */

                    $sqty = $qty[$i];
                    $sqty = number_format((float) $sqty, 3, '.', '');
                    //$sqty = Finance::amount_fix($sqty);

                    $ltotal = ($samount) * ($sqty);
                    $d = ORM::for_table('sys_invoiceitems')->create();
                    $d->invoiceid = $invoiceid;
                    $d->userid = $cid;
                    $d->description = $item;
                    $d->qty = $sqty;
                    $d->amount = $samount;
                    $d->total = $ltotal;
                    //atribui o id do item
                    $d->sys_item_id = $item_id[$i];
//                    if (($taxed[$i]) == 'Yes') {
//                        $d->taxed = '1';
//                    } else {
//                        $d->taxed = '0';
//                    }


                    if ($taxed) {

                        if (($taxed[$i]) == 'Yes') {
                            $d->taxed = '1';
                        } else {
                            $d->taxed = '0';
                        }
                    } else {
                        $d->taxed = '0';
                    }

                    //others
                    $d->type = '';
                    $d->relid = '0';
                    $d->itemcode = '';
                    $d->taxamount = '0.00';
                    $d->duedate = date('Y-m-d');
                    $d->paymentmethod = '';
                    $d->notes = '';
                    $d->save();
                    $i++;
                }

                echo $invoiceid;
            } else {

                // invoice not found
            }
        } else {
            echo $msg;
        }

        break;

    case 'delete':

        Event::trigger('invoices/delete/');

        $id = $routes['2'];
        if ($_app_stage == 'Demo') {
            r2(U . 'accounts/list', 'e', 'Sorry! Deleting Account is disabled in the demo mode.');
        }
        $d = ORM::for_table('crm_accounts')->find_one($id);
        if ($d) {
            $d->delete();
            r2(U . 'accounts/list', 's', $_L['account_delete_successful']);
        }

        break;


    case 'print':

        Event::trigger('invoices/print/');

        $id = $routes['2'];
        $d = ORM::for_table('sys_invoices')->find_one($id);
        if ($d) {

            //find all activity for this user
            $items = ORM::for_table('sys_invoiceitems')->where('invoiceid', $id)->order_by_asc('id')->find_many();

//find the user
            $a = ORM::for_table('crm_accounts')->find_one($d['userid']);

            require 'application/lib/invoices/render.php';
        } else {
            r2(U . 'customers/list', 'e', $_L['Account_Not_Found']);
        }

        break;

    case 'pdf':

        Event::trigger('invoices/pdf/');


        $id = $routes['2'];


        $d = ORM::for_table('sys_invoices')->find_one($id);
        if ($d) {

            //find all activity for this user
            $items = ORM::for_table('sys_invoiceitems')->where('invoiceid', $id)->order_by_asc('id')->find_many();

            $trs_c = ORM::for_table('sys_transactions')->where('iid', $id)->count();

            $trs = ORM::for_table('sys_transactions')->where('iid', $id)->order_by_desc('id')->find_many();

//find the user
            $a = ORM::for_table('crm_accounts')->find_one($d['userid']);
            $i_credit = $d['credit'];
            $i_due = '0.00';
            $i_total = $d['total'];
            if ($d['credit'] != '0.00') {
                $i_due = $i_total - $i_credit;
            } else {
                $i_due = $d['total'];
            }

            $i_due = number_format($i_due, 2, $config['dec_point'], $config['thousands_sep']);
            $cf = ORM::for_table('crm_customfields')->where('showinvoice', 'Yes')->order_by_asc('id')->find_many();
//            ob_start();
//            require 'application/lib/invoices/pdf-default.php';
//            $html = ob_get_contents();
//            ob_end_clean();
//            echo $html;
//            exit;
//            require('application/lib/tcpdf/config/lang/eng.php');
//            require('application/lib/tcpdf/tcpdf.php');
//            // create new PDF document
//            $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
//
//// set document information
//            $pdf->SetCreator('application');
//            $pdf->SetAuthor('application.com');
//            $pdf->SetTitle('invoice titla');
//            $pdf->SetSubject('invoice subject');
//
//            $pdf->SetPrintHeader(false);
//// set default header data
//            //   $pdf->SetHeaderData('', '', $title, "Generated on ".date('d/m/Y')." \nby ".$aadmin);
//
//// set header and footer fonts
//            //   $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
//            //   $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
////$pdf->SetFont('freesans', '', 10);
//// set default monospaced font
//            //   $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
//
////set margins
////            $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
////        //    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
////         //   $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
////
//////set auto page breaks
////            $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
////
//////set image scale factor
////            $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
//
////set some language-dependent strings
//            //  $pdf->setLanguageArray();
//
//// ---------------------------------------------------------
//
//// set font
//            $pdf->AddPage();
//            require 'application/lib/invoices/pdf-x1.php';
//
//            // $pdf->writeHTML($html, true, false, true, false, '');
//
//// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
//// reset pointer to the last page
//            //   $pdf->lastPage();
//
//// ---------------------------------------------------------
//
////Close and output PDF document
//            if (isset($routes['3']) AND ($routes['3'] == 'dl')) {
//                $pdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'D'); # D
//            } else {
//                $pdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'I'); # D
//            }
//
//        } else {
//            r2(U . 'customers/list', 'e', $_L['Account_Not_Found']);
//        }


            if ($d['cn'] != '') {
                $dispid = $d['cn'];
            } else {
                $dispid = $d['id'];
            }

            $in = $d['invoicenum'] . $dispid;

            define('_MPDF_PATH', 'application/lib/mpdf/');

            require('application/lib/mpdf/mpdf.php');

            $pdf_c = '';
            $ib_w_font = 'dejavusanscondensed';
            if ($config['pdf_font'] == 'default') {
                $pdf_c = 'c';
                $ib_w_font = 'Helvetica';
            }

            $mpdf = new mPDF($pdf_c, 'A4', '', '', 20, 15, 15, 25, 10, 10);
            $mpdf->SetProtection(array('print'));
            $mpdf->SetTitle($config['CompanyName'] . ' Invoice');
            $mpdf->SetAuthor($config['CompanyName']);
            $mpdf->SetWatermarkText(ib_lan_get_line($d['status']));
            $mpdf->showWatermarkText = true;
            $mpdf->watermark_font = $ib_w_font;
            $mpdf->watermarkTextAlpha = 0.1;
            $mpdf->SetDisplayMode('fullpage');

            if ($config['pdf_font'] == 'AdobeCJK') {
                $mpdf->useAdobeCJK = true;
                $mpdf->autoScriptToLang = true;
                $mpdf->autoLangToFont = true;
            }

            Event::trigger('invoices/before_pdf_render/');

            ob_start();

            require 'application/lib/invoices/pdf-x2.php';

            $html = ob_get_contents();


            ob_end_clean();

            $mpdf->WriteHTML($html);

            $pdf_return = 'inline';

            if (isset($routes[3])) {

                $r_type = $routes[3];
            } else {
                $r_type = 'inline';
            }

            if ($r_type == 'dl') {
                $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'D'); # D
            } elseif ($r_type == 'inline') {
                $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'I'); # D
            } elseif ($r_type == 'store') {

                $mpdf->Output('application/storage/temp/Invoice_' . $in . '.pdf', 'F'); # D
            } else {
                $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'I'); # D
            }
        }



        break;

    case 'markpaid':



        $iid = _post('iid');
        $d = ORM::for_table('sys_invoices')->find_one($iid);
        if ($d) {
            $d->status = 'Paid';
            $d->save();
            Event::trigger('invoices/markpaid/', $invoice = $d);
            _msglog('s', 'Invoice marked as Paid');
        } else {
            _msglog('e', 'Invoice not found');
        }
        break;

    case 'markunpaid':

        Event::trigger('invoices/markunpaid/');

        $iid = _post('iid');
        $d = ORM::for_table('sys_invoices')->find_one($iid);
        if ($d) {
            $d->status = 'Unpaid';
            $d->save();
            _msglog('s', 'Invoice marked as Un Paid');
        } else {
            _msglog('e', 'Invoice not found');
        }
        break;

    case 'markcancelled':

        Event::trigger('invoices/markcancelled/');


        $iid = _post('iid');
        $d = ORM::for_table('sys_invoices')->find_one($iid);
        if ($d) {
            $d->status = 'Cancelled';
            $d->save();
            _msglog('s', 'Invoice marked as Cancelled');
        } else {
            _msglog('e', 'Invoice not found');
        }
        break;

    case 'markpartiallypaid':

        Event::trigger('invoices/markpartiallypaid/');


        $iid = _post('iid');
        $d = ORM::for_table('sys_invoices')->find_one($iid);
        if ($d) {
            $d->status = 'Partially Paid';
            $d->save();
            _msglog('s', 'Invoice marked as Partially Paid');
        } else {
            _msglog('e', 'Invoice not found');
        }
        break;


    case 'add-payment':

        Event::trigger('invoices/add-payment/');

        $sid = $routes['2'];
        $d = ORM::for_table('sys_invoices')->find_one($sid);

        if ($d) {

            $itotal = $d['total'];
            $ic = $d['credit'];
            $np = $itotal - $ic;
            $a_opt = '';
            // <option value="{$ds['account']}">{$ds['account']}</option>
            $a = ORM::for_table('sys_accounts')->find_many();

            foreach ($a as $acs) {
                $a_opt .= '<option value="' . $acs['account'] . '">' . $acs['account'] . '</option>';
            }

            $pms_opt = '';
            // <option value="{$pm['name']}">{$pm['name']}</option>
            $pms = ORM::for_table('sys_pmethods')->order_by_asc('sorder')->find_many();
            foreach ($pms as $pm) {
                $pms_opt .= '<option value="' . $pm['name'] . '">' . $pm['name'] . '</option>';
            }

            $cats_opt = '';

            $cats = ORM::for_table('sys_cats')->where('type', 'Income')->order_by_asc('sorder')->find_many();

            foreach ($cats as $cat) {
                $cats_opt .= '<option value="' . $cat['name'] . '">' . $cat['name'] . '</option>';
            }


            echo '
<div class="modal-header">
	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
	<h3>' . $_L['Invoice'] . ' #' . $d['id'] . '</h3>
</div>
<div class="modal-body">

<form class="form-horizontal" role="form" id="form_add_payment" method="post">
<div class="form-group">
    <label for="subject" class="col-sm-2 control-label">' . $_L['SYS_ACCOUNT'] . '</label>
    <div class="col-sm-10">
       <select id="account" name="account">
                            <option value="">' . $_L['Choose an Account'] . '</option>

' . $a_opt . '

                        </select>
    </div>
  </div>

<div class="form-group">
    <label for="date" class="col-sm-2 control-label">' . $_L['Date'] . '</label>
    <div class="col-sm-10">
      <input type="text" class="form-control datepicker"  value="' . date('Y-m-d') . '" name="date" id="date" datepicker data-date-format="yyyy-mm-dd" data-auto-close="true">
    </div>
  </div>

<div class="form-group">
    <label for="description" class="col-sm-2 control-label">' . $_L['Description'] . '</label>
    <div class="col-sm-10">
      <input type="text" id="description" name="description" class="form-control" value="' . $_L['Invoice'] . ' ' . $d['id'] . ' ' . $_L['Payment'] . '">
    </div>
  </div>
<div class="form-group">
    <label for="amount" class="col-sm-2 control-label">' . $_L['Amount'] . '</label>
    <div class="col-sm-10">
      <input type="text" id="amount" name="amount" class="form-control amount"   data-a-sign="' . $config['currency_code'] . ' " data-a-dec="' . $config['dec_point'] . '" data-a-sep="' . $config['thousands_sep'] . '"
data-d-group="2" value="' . $np . '">
    </div>
  </div>
<div class="form-group">
    <label for="cats" class="col-sm-2 control-label">' . $_L['Category'] . '</label>
    <div class="col-sm-10">
       <select id="cats" name="cats">
                             <option value="Uncategorized">' . $_L['Uncategorized'] . '</option>

' . $cats_opt . '

                        </select>
    </div>
  </div>
  <div class="form-group">
    <label for="payer_name" class="col-sm-2 control-label">' . $_L['Payer'] . '</label>
    <div class="col-sm-10">
      <input type="text" id="payer_name" name="payer_name" class="form-control" value="' . $d['account'] . '" disabled>
    </div>
  </div>

   <div class="form-group">
    <label for="subject" class="col-sm-2 control-label">' . $_L['Method'] . '</label>
    <div class="col-sm-10">
      <select id="pmethod" name="pmethod">
                                <option value="">' . $_L['Select Payment Method'] . '</option>


                                ' . $pms_opt . '


                            </select>
    </div>
  </div>


</form>

</div>
<div class="modal-footer">
<input type="hidden" id="payer" name="payer" value="' . $d['userid'] . '">
	<button id="save_payment" class="btn btn-primary">' . $_L['Save'] . '</button>

		<button type="button" data-dismiss="modal" class="btn">' . $_L['Close'] . '</button>
</div>';
        } else {
            exit('Invoice Not Found');
        }


        break;


    case 'mail_invoice_':

        Event::trigger('invoices/mail_invoice_/');

        $sid = $routes['2'];
        $etpl = $routes['3'];

        $d = ORM::for_table('sys_invoices')->find_one($sid);


        if ($d) {

            $a = ORM::for_table('crm_accounts')->find_one($d['userid']);

            $msg = Invoice::gen_email($sid, $etpl);



            if ($msg) {
                $subj = $msg['subject'];
                $message_o = $msg['body'];
                $email = $msg['email'];
                $name = $msg['name'];
            } else {
                $subj = '';
                $message_o = '';
                $email = '';
                $name = '';
            }




            if ($d['cn'] != '') {
                $dispid = $d['cn'];
            } else {
                $dispid = $d['id'];
            }

            $in = $d['invoicenum'] . $dispid;


            echo '
<div class="modal-header">
	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
	<h3>Invoice #' . $d['id'] . '</h3>
</div>
<div class="modal-body">

<form class="form-horizontal" role="form" id="email_form" method="post">


<div class="form-group">
    <label for="toemail" class="col-sm-2 control-label">' . $_L['To'] . '</label>
    <div class="col-sm-10">
      <input type="email" id="toemail" name="toemail" class="form-control" value="' . $email . '">
    </div>
  </div>

  <div class="form-group">
    <label for="ccemail" class="col-sm-2 control-label">' . $_L['Cc'] . '</label>
    <div class="col-sm-10">
      <input type="email" id="ccemail" name="ccemail" class="form-control" value="">
    </div>
  </div>

  <div class="form-group">
    <label for="bccemail" class="col-sm-2 control-label">' . $_L['Bcc'] . '</label>
    <div class="col-sm-10">
      <input type="email" id="bccemail" name="bccemail" class="form-control" value="">
      <span class="help-block"><a href="#" id="send_bcc_to_admin">' . $_L['Send Bcc to Admin'] . '</a></span>
    </div>
  </div>

    <div class="form-group">
    <label for="subject" class="col-sm-2 control-label">' . $_L['Subject'] . '</label>
    <div class="col-sm-10">
      <input type="text" id="subject" name="subject" class="form-control" value="' . $subj . '">
    </div>
  </div>

  <div class="form-group">
    <label for="subject" class="col-sm-2 control-label">' . $_L['Message Body'] . '</label>
    <div class="col-sm-10">
      <textarea class="form-control sysedit" rows="3" name="message" id="message">' . $message_o . '</textarea>
      <input type="hidden" id="toname" name="toname" value="' . $name . '">
      <input type="hidden" id="i_cid" name="i_cid" value="' . $a['id'] . '">
      <input type="hidden" id="i_iid" name="i_iid" value="' . $d['id'] . '">
    </div>
  </div>


<div class="form-group">
    <label for="attach_pdf" class="col-sm-2 control-label">' . $_L['Attach PDF'] . '</label>
    <div class="col-sm-10">
      <div class="checkbox c-checkbox">
                          <label>
                            <input type="checkbox" name="attach_pdf" id="attach_pdf" value="Yes" checked><span class="fa fa-check"></span>  <i class="fa fa-paperclip"></i> Invoice_' . $in . '.pdf
                          </label>
                        </div>
    </div>
  </div>


</form>

</div>
<div class="modal-footer">
	<button id="send" class="btn btn-primary">' . $_L['Send'] . '</button>

		<button type="button" data-dismiss="modal" class="btn">' . $_L['Close'] . '</button>
</div>';
        } else {
            exit('Invoice Not Found');
        }


        break;


    case 'send_email':

        Event::trigger('invoices/send_email/');

        $msg = '';
        $email = _post('toemail');
        $cc = _post('ccemail');
        $bcc = _post('bccemail');
        $subject = _post('subject');
        $toname = _post('toname');
        $cid = _post('i_cid');
        $iid = _post('i_iid');

        $d = ORM::for_table('sys_invoices')->find_one($iid);

        if ($d['cn'] != '') {
            $dispid = $d['cn'];
        } else {
            $dispid = $d['id'];
        }

        $in = $d['invoicenum'] . $dispid;

        $message = $_POST['message'];

        $attach_pdf = _post('attach_pdf');

        $attachment_path = '';
        $attachment_file = '';

        if ($attach_pdf == 'Yes') {

            Invoice::pdf($iid, 'store');

            $attachment_path = 'application/storage/temp/Invoice_' . $in . '.pdf';
            $attachment_file = 'Invoice_' . $in . '.pdf';
        }

        if (!Validator::Email($email)) {
            $msg .= 'Invalid Email <br>';
        }

        if (!Validator::Email($cc)) {
            $cc = '';
        }

        if (!Validator::Email($bcc)) {
            $bcc = '';
        }


        if ($subject == '') {
            $msg .= 'Subject is Required <br>';
        }

        if ($message == '') {
            $msg .= 'Message is Required <br>';
        }

        if ($msg == '') {

            //now send email

            Notify_Email::_send($toname, $email, $subject, $message, $cid, $iid, $cc, $bcc, $attachment_path, $attachment_file);

            // Now check for

            echo '<div class="alert alert-success fade in">Mail Sent!</div>';
        } else {
            echo '<div class="alert alert-danger fade in">' . $msg . '</div>';
        }


        break;

    case 'stop_recurring':

        Event::trigger('invoices/stop_recurring/');


        $id = $routes['2'];
        $id = str_replace('sid', '', $id);
        $d = ORM::for_table('sys_invoices')->find_one($id);
        if ($d) {

            $d->r = '0';
            $d->save();
            r2(U . 'invoices/list-recurring', 's', 'Recurring Disabled for Invoice: ' . $id);
        } else {
            echo 'Invoice not found';
        }
        break;


    case 'add-payment-post':

        Event::trigger('invoices/add-payment-post/');

        $msg = '';
        $account = _post('account');
        $date = _post('date');
        $amount = _post('amount');
        $amount = Finance::amount_fix($amount);
        $payerid = _post('payer');
        $pmethod = _post('pmethod');
        $ref = _post('ref');
        if ($payerid == '') {
            $payerid = '0';
        }
        $amount = str_replace($config['currency_code'], '', $amount);
        $amount = str_replace(',', '', $amount);
        if (!is_numeric($amount)) {
            $msg .= 'Invalid Amount' . '<br>';
        }
        $cat = _post('cats');
        $iid = _post('iid');


        if ($payerid == '') {
            $msg .= 'Payer Not Found' . '<br>';
        }
        $description = _post('description');
        $msg = '';
        if ($description == '') {
            $msg .= $_L['description_error'] . '<br>';
        }

        if (Validator::Length($account, 100, 1) == false) {
            $msg .= 'Please choose an Account' . '<br>';
        }


        if (is_numeric($amount) == false) {
            $msg .= $_L['amount_error'] . '<br>';
        }

        // Bloquear o pagamento de uma fatura pela view da fatura. Toda fatura deve ser paga pelo Contas a Receber
        $msg = 'REALIZE A BAIXA DA FATURA ATRAVÉS DO CONTAS A RECEBER';
        if ($msg == '') {

            //find the current balance for this account
            $a = ORM::for_table('sys_accounts')->where('account', $account)->find_one();
            $cbal = $a['balance'];
            $nbal = $cbal + $amount;
            $a->balance = $nbal;
            $a->save();
            $d = ORM::for_table('sys_transactions')->create();
            $d->account = $account;
            $d->type = 'Income';
            $d->payerid = $payerid;

            $d->amount = $amount;
            $d->category = $cat;
            $d->method = $pmethod;
            $d->ref = $ref;
            $d->tags = '';


            $d->description = $description;
            $d->date = $date;
            $d->dr = '0.00';
            $d->cr = $amount;
            $d->bal = $nbal;
            $d->iid = $iid;


            //others
            $d->payer = '';
            $d->payee = '';
            $d->payeeid = '0';
            $d->status = 'Cleared';
            $d->tax = '0.00';

            $d->aid = 0;
            $d->updated_at = date('Y-m-d H:i:s');
            //


            $d->save();
            $tid = $d->id();
            _log('New Deposit: ' . $description . ' [TrID: ' . $tid . ' | Amount: ' . $amount . ']', 'Admin', $user['id']);
            _msglog('s', $_L['Transaction Added Successfully']);
            //now work with invoice
            $i = ORM::for_table('sys_invoices')->find_one($iid);
            if ($i) {
                $pc = $i['credit'];
                $it = $i['total'];
                $dp = $it - $pc;
                if (($dp == $amount) OR ( ($dp < $amount))) {
                    $i->status = 'Paid';
                } else {

                    $i->status = 'Partially Paid';
                }
                $i->credit = $pc + $amount;
                $i->save();
            }
            echo $tid;
        } else {
            echo '<div class="alert alert-danger fade in">' . $msg . '</div>';
        }

        break;

    case 'export_csv':

        $fileName = 'transactions_' . time() . '.csv';

        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header('Content-Description: File Transfer');
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename={$fileName}");
        header("Expires: 0");
        header("Pragma: public");

        $fh = @fopen('php://output', 'w');

        $headerDisplayed = false;

        // $results = ORM::for_table('crm_Accounts')->find_array();
        $results = db_find_array('sys_invoices');

        foreach ($results as $data) {
            // Add a header row if it hasn't been added yet
            if (!$headerDisplayed) {
                // Use the keys from $data as the titles
                fputcsv($fh, array_keys($data));
                $headerDisplayed = true;
            }

            // Put the data into the stream
            fputcsv($fh, $data);
        }
// Close the file
        fclose($fh);



        break;

    case 'payments':

        $mode_css = Asset::css('footable/css/footable.core.min');

        $mode_js = Asset::js(array('numeric', 'footable/js/footable.all.min'));

        $d = ORM::for_table('sys_transactions')->where_not_equal('iid', '0')->limit(500)->find_array();

        $ui->assign('d', $d);

        $ui->assign('xheader', $mode_css);
        $ui->assign('xfooter', $mode_js);

        $ui->assign('xjq', '
        
        $(\'.footable\').footable();
        
         $(\'.amount\').autoNumeric(\'init\', {

    aSign: \'' . $config['currency_code'] . ' \',
    dGroup: ' . $config['thousand_separator_placement'] . ',
    aPad: ' . $config['currency_decimal_digits'] . ',
    pSign: \'' . $config['currency_symbol_position'] . '\',
    aDec: \'' . $config['dec_point'] . '\',
    aSep: \'' . $config['thousands_sep'] . '\'

    });
$(".cdelete").click(function (e) {
        e.preventDefault();
        var id = this.id;
        bootbox.confirm("' . $_L['are_you_sure'] . '", function(result) {
           if(result){
               var _url = $("#_url").val();
               window.location.href = _url + "delete/invoice/" + id;
           }
        });
    });



 ');

        $ui->display('payments.tpl');


        break;

    case 'bank-slips':
        Event::trigger('invoices/bank-slips/');

        $params = array();
        $params['items_per_page'] = 20;
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $params['search'] = filter_var(_post('search'), FILTER_SANITIZE_STRING);
        } else {
            if ($i = array_search('search', $routes))
                $params['search'] = filter_var($routes[$i + 1], FILTER_SANITIZE_STRING);
            if ($i = array_search('items_per_page', $routes))
                $params['items_per_page'] = filter_var($routes[$i + 1], FILTER_SANITIZE_STRING);
        }

        $page = isset($routes['2']) ? $routes['2'] : 1;

        $select = "
			SELECT
				tic.*,
				pmet.name AS payment_method,
				acc.account AS customer
			FROM
				sys_invoices_tickets tic
				INNER JOIN sys_invoices inv ON(tic.id_invoice = inv.id)
				INNER JOIN sys_pmethods pmet ON(inv.paymentmethod = pmet.id)
				INNER JOIN crm_accounts acc ON(inv.userid = acc.id)";

        $where = '';
        if (isset($params['search']) && $params['search'] != '') {
            $where .= ' WHERE ';
            $where .= "acc.account LIKE '%" . $params['search'] .
                    "%' OR acc.cpf_cnpj LIKE '%" . $params['search'] .
                    "%' OR tic.ref_tran LIKE '%" . $params['search'] . "%'";
        }

        $order = " ORDER BY tic.due_date DESC";
        $query = $select . $where . $order;

        $paginator = new ModulePaginator('sys_invoices_tickets', $query, $params);
        $tickets = $paginator->setItemsPerPage($params['items_per_page'])
                ->setCurrentPageNumber($page)
                ->run();

        $ui->assign('tickets', $tickets);
        $ui->assign('paginator', $paginator);
        $ui->assign('params', $params);

        $ui->assign('xheader', Asset::css(array('s2/css/select2.min', 'dp/dist/datepicker.min', 'modal', 'dropzone/dropzone')));
        $ui->assign('xfooter', Asset::js(array('s2/js/select2.min', 's2/js/i18n/'
                    . lan(), 'dp/dist/datepicker.min', 'dp/i18n/'
                    . $config['language'], 'numeric', 'modal', 'dropzone/dropzone', 'bank_slips_return_file')));

        $ui->assign('jsvar', '
			_L[\'Remove\'] = \'' . $_L['Remove'] . '\';    
			_L[\'Cancel\'] = \'' . $_L['Cancel'] . '\';
			_L[\'Return file import to this bank has not yet been implemented\'] = \'' . $_L['Return file import to this bank has not yet been implemented'] . '\';
		');

        $banks = ORM::for_table('crm_banks')->find_array();
        $ui->assign('banks', $banks);

        $ui->assign('_st', $_L['Bank slips']);
        $ui->display('bank-slips.tpl');

        break;

    case 'bank-slip-confirm-payment':
        $id = filter_var($routes['2'], FILTER_SANITIZE_NUMBER_INT);
        ($id == '') ? r2(U . 'invoices/bank-slips', 'e', $_L['Item Not Found']) : '';

        $slip = ORM::for_table('sys_invoices_tickets')->find_one($id);
        $slip->status = 'PAGO';
        $slip->save();

        echo '0';
//		r2(U.'invoices/add-payment/' .$slip->id_invoice. '/' , '', '');

        break;

    /**
     * Importação do arquivo de retorno da Credisis
     */
    case 'add-returnfile-credisis':
//        $id = '';
//        if(isset($routes[3]) && $routes[3] > 0) {
//            $id = $routes[3];
//        }

        $dir = "application/storage/invoices/return_files/";

        $uploader = new Uploader();
        $uploader->setDir($dir);
        $uploader->sameName(false);
        $uploader->setExtensions(array('ret'));

        if ($uploader->uploadFile('file')) {
            $uploaded = $uploader->getUploadName();
            $file = $uploaded;
            $msg = $_L['Uploaded Successfully'];
            $success = 'Yes';

            $header = array();
            $detail = array();
            $trail = array();

            $temp = file_get_contents($dir . $uploaded);
            $lines = explode(PHP_EOL, trim($temp));

            $iH = 0;
            $iD = 0;
            $iT = 0;
            $file_handle = fopen($dir . $uploaded, 'r');
            if ($file_handle) {
                $i = 0;
                while (($buffer = fgets($file_handle, 4096)) != false) {
                    $line = preg_replace('/\s+/', '', $buffer);
                    if ($i == 0) {
                        $header['A1'] = substr($line, 0, 1);
                        $header['A2'] = substr($line, 1, 1);
                        $header['A3'] = substr($line, 2, 7);
                        $header['A4'] = substr($line, 9, 2);
                        $header['A5'] = substr($line, 11, 8);
                        $header['A6'] = substr($line, 19, 7);
                        $header['A7'] = substr($line, 26, 4);
                        $header['A8'] = substr($line, 30, 1);
                        $header['A9'] = substr($line, 31, 8);
                        $header['A10'] = substr($line, 39, 1);
                        $header['A11'] = substr($line, 40, 6);
                        $header['A12'] = substr($line, 46, 30);
                        $header['A13'] = substr($line, 76, 18);
                        $header['A14'] = substr($line, 94, 6);
                        $header['A15'] = substr($line, 100, 7);
                        $header['A16'] = substr($line, 107, 42);
                        $header['A17'] = substr($line, 149, 7);
                        $header['A18'] = substr($line, 156, 238);
                        $header['A19'] = substr($line, 394, 6);
                    }
                    if ($i > 0 && ($i + 1) < count($lines)) {
                        $detail[$i]['D1'] = substr($line, 0, 1);
                        $detail[$i]['D2'] = substr($line, 1, 2);
                        $detail[$i]['D3'] = substr($line, 2, 14);
                        $detail[$i]['D4'] = substr($line, 16, 4);
                        $detail[$i]['D5'] = substr($line, 20, 1);
                        $detail[$i]['D6'] = substr($line, 21, 8);
                        $detail[$i]['D7'] = substr($line, 29, 1);
                        $detail[$i]['D8'] = substr($line, 30, 7);
                        $detail[$i]['D9'] = substr($line, 37, 25);
                        $detail[$i]['D10'] = substr($line, 63, 17);
                        $detail[$i]['D11'] = substr($line, 80, 1);
                        $detail[$i]['D12'] = substr($line, 81, 1);
                        $detail[$i]['D13'] = substr($line, 82, 4);
                        $detail[$i]['D14'] = substr($line, 86, 2);
                        $detail[$i]['D15'] = substr($line, 87, 3);
                        $detail[$i]['D16'] = substr($line, 90, 3);
                        $detail[$i]['D17'] = substr($line, 94, 1);
                        $detail[$i]['D18'] = substr($line, 95, 5);
                        $detail[$i]['D19'] = substr($line, 100, 4);
                        $detail[$i]['D20'] = substr($line, 105, 1);
                        $detail[$i]['D21'] = substr($line, 106, 2);
                        $detail[$i]['D22'] = substr($line, 108, 2);
                        $detail[$i]['D23'] = substr($line, 110, 6);
                        $detail[$i]['D24'] = substr($line, 116, 10);
                        $detail[$i]['D25'] = substr($line, 126, 20);
                        $detail[$i]['D26'] = substr($line, 146, 6);
                        $detail[$i]['D27'] = substr($line, 152, 11);
                        $detail[$i]['D28'] = substr($line, 165, 3);
                        $detail[$i]['D29'] = substr($line, 168, 4);
                        $detail[$i]['D30'] = substr($line, 172, 1);
                        $detail[$i]['D31'] = substr($line, 173, 2);
                        $detail[$i]['D32'] = substr($line, 175, 6);
                        $detail[$i]['D33'] = substr($line, 181, 5);
                        $detail[$i]['D34'] = substr($line, 188, 11);
                        $detail[$i]['D35'] = substr($line, 201, 11);
                        $detail[$i]['D36'] = substr($line, 214, 11);
                        $detail[$i]['D37'] = substr($line, 227, 11);
                        $detail[$i]['D38'] = substr($line, 240, 11);
                        $detail[$i]['D39'] = substr($line, 253, 11);
                        $detail[$i]['D40'] = substr($line, 266, 11);
                        $detail[$i]['D41'] = substr($line, 279, 11);
                        $detail[$i]['D42'] = substr($line, 292, 11);
                        $detail[$i]['D43'] = substr($line, 305, 11);
                        $detail[$i]['D44'] = substr($line, 318, 1);
                        $detail[$i]['D45'] = substr($line, 319, 1);
                        $detail[$i]['D46'] = substr($line, 320, 10);
                        $detail[$i]['D47'] = substr($line, 332, 1);
                        $detail[$i]['D48'] = substr($line, 333, 9);
                        $detail[$i]['D49'] = substr($line, 342, 7);
                        $detail[$i]['D50'] = substr($line, 349, 9);
                        $detail[$i]['D51'] = substr($line, 358, 7);
                        $detail[$i]['D52'] = substr($line, 365, 9);
                        $detail[$i]['D53'] = substr($line, 374, 7);
                        $detail[$i]['D54'] = substr($line, 381, 9);
                        $detail[$i]['D55'] = substr($line, 390, 1);
                        $detail[$i]['D56'] = substr($line, 391, 1);
                        $detail[$i]['D57'] = substr($line, 392, 2);
                        $detail[$i]['D58'] = substr($line, 394, 6);
                    }
                    // trail
                    if (($i + 1) == count($lines)) {
                        $trail['T1'] = substr($line, 0, 1);
                        $trail['T2'] = substr($line, 1, 2);
                        $trail['T3'] = substr($line, 2, 2);
                        $trail['T4'] = substr($line, 4, 3);
                        $trail['T5'] = substr($line, 7, 10);
                        $trail['T6'] = substr($line, 17, 8);
                        $trail['T7'] = substr($line, 25, 13);
                        $trail['T8'] = substr($line, 39, 8);
                        $trail['T9'] = substr($line, 47, 10);
                        $trail['T10'] = substr($line, 57, 8);
                        $trail['T11'] = substr($line, 65, 13);
                        $trail['T12'] = substr($line, 79, 8);
                        $trail['T13'] = substr($line, 87, 10);
                        $trail['T14'] = substr($line, 97, 8);
                        $trail['T15'] = substr($line, 105, 13);
                        $trail['T16'] = substr($line, 119, 8);
                        $trail['T17'] = substr($line, 127, 10);
                        $trail['T18'] = substr($line, 137, 8);
                        $trail['T19'] = substr($line, 145, 13);
                        $trail['T20'] = substr($line, 159, 8);
                        $trail['T21'] = substr($line, 167, 50);
                        $trail['T22'] = substr($line, 217, 8);
                        $trail['T23'] = substr($line, 225, 13);
                        $trail['T24'] = substr($line, 239, 8);
                        $trail['T25'] = substr($line, 247, 147);
                        $trail['T26'] = substr($line, 394, 6);
                    }

                    $i++;
                }
            }

            fclose($file_handle);

//            if ($id > 0) {
//                $record = ORM::for_table('module_billing_records')->find_one($id);
//                $record->attachment = $uploaded;
//                $record->save();
//                $id_record = $record->id();
//            }
//            list($width, $height, $type, $attr) = getimagesize('application/storage/billing/records/img/' . $uploaded);
//            $image = new Image();
//            $image->source_path = 'application/storage/billing/records/img/' . $uploaded;
//            $image->target_path = 'application/storage/billing/records/img/' . $uploaded;
//
//            if ($width > $height && $width > 800) {
//                $image->resize(800);
//            } else if ($height > $width && $height > 800) {
//                $image->resize(null, 800);
//            }
        } else {
            $file = '';
            $msg = $uploader->getMessage();
            $success = 'No';
            $id = '';
        }

        $response = array(
            'success' => $success,
            'msg' => $msg,
            'file' => $file,
            'id' => '' // $id_record
        );

        header('Content-Type: application/json');
        echo json_encode($response);

        break;

    case 'remove-returnfile-credisis':
        die('remove-returnfile-credisis');

        break;

    case 'get-returnfile-credisis':
        die('get-returnfile-credisis');

        break;

    /**
     * TODO: Falta concluir a extração dos dados de arquivos de retorno,
     * o arquivo CBR64324902904201620822.ret que estavamos usando para testes
     * tem grandes chances de estar com valores incorretos.
     */
    case 'add-returnfile-bancodobrasil':
//        $id = '';
//        if(isset($routes[3]) && $routes[3] > 0) {
//            $id = $routes[3];
//        }

        $dir = "application/storage/invoices/return_files/";

        $uploader = new Uploader();
        $uploader->setDir($dir);
        $uploader->sameName(false);
        $uploader->setExtensions(array('ret'));

        if ($uploader->uploadFile('file')) {
            $uploaded = $uploader->getUploadName();
            $file = $uploaded;
            $msg = $_L['Uploaded Successfully'];
            $success = 'Yes';

            $header = array();
            $detail = array();
            $trail = array();

            $temp = file_get_contents($dir . $uploaded);
            $lines = explode(PHP_EOL, trim($temp));

//            echo '<pre>';
//            var_dump(count($lines), $lines);
//            die;

            $iH = 0;
            $iD = 0;
            $iT = 0;
            $file_handle = fopen($dir . $uploaded, 'r');
            if ($file_handle) {
                $i = 0;
                while (($buffer = fgets($file_handle, 4096)) != false) {
                    $line = preg_replace('/\s+/', '', $buffer);
                    if ($i == 0) {
                        $header['A1'] = substr($line, 0, 1);
                        $header['A2'] = substr($line, 1, 1);
                        $header['A3'] = substr($line, 2, 7);
                        $header['A4'] = substr($line, 9, 2);
                        $header['A5'] = substr($line, 11, 8);
                        $header['A6'] = substr($line, 19, 7);
                        $header['A7'] = substr($line, 26, 4);
                        $header['A8'] = substr($line, 30, 1);
                        $header['A9'] = substr($line, 31, 8);
                        $header['A10'] = substr($line, 39, 1);
                        $header['A11'] = substr($line, 40, 6);
                        $header['A12'] = substr($line, 46, 30);
                        $header['A13'] = substr($line, 76, 18);
                        $header['A14'] = substr($line, 94, 6);
                        $header['A15'] = substr($line, 100, 7);
                        $header['A16'] = substr($line, 107, 42);
                        $header['A17'] = substr($line, 149, 7);
                        $header['A18'] = substr($line, 156, 238);
                        $header['A19'] = substr($line, 394, 6);
                    }
                    if ($i > 0 && ($i + 1) < count($lines)) {
                        $detail[$i]['D1'] = substr($line, 0, 1);
                        $detail[$i]['D2'] = substr($line, 1, 2);
                        $detail[$i]['D3'] = substr($line, 2, 14);
                        $detail[$i]['D4'] = substr($line, 16, 4);
                        $detail[$i]['D5'] = substr($line, 20, 1);
                        $detail[$i]['D6'] = substr($line, 21, 8);
                        $detail[$i]['D7'] = substr($line, 29, 1);
                        $detail[$i]['D8'] = substr($line, 30, 7);
                        $detail[$i]['D9'] = substr($line, 37, 25);
                        $detail[$i]['D10'] = substr($line, 63, 17);
                        $detail[$i]['D11'] = substr($line, 80, 1);
                        $detail[$i]['D12'] = substr($line, 81, 1);
                        $detail[$i]['D13'] = substr($line, 82, 4);
                        $detail[$i]['D14'] = substr($line, 86, 2);
                        $detail[$i]['D15'] = substr($line, 87, 3);
                        $detail[$i]['D16'] = substr($line, 90, 3);
                        $detail[$i]['D17'] = substr($line, 94, 1);
                        $detail[$i]['D18'] = substr($line, 95, 5);
                        $detail[$i]['D19'] = substr($line, 100, 4);
                        $detail[$i]['D20'] = substr($line, 105, 1);
                        $detail[$i]['D21'] = substr($line, 106, 2);
                        $detail[$i]['D22'] = substr($line, 108, 2);
                        $detail[$i]['D23'] = substr($line, 110, 6);
                        $detail[$i]['D24'] = substr($line, 116, 10);
                        $detail[$i]['D25'] = substr($line, 126, 20);
                        $detail[$i]['D26'] = substr($line, 146, 6);
                        $detail[$i]['D27'] = substr($line, 152, 11);
                        $detail[$i]['D28'] = substr($line, 165, 3);
                        $detail[$i]['D29'] = substr($line, 168, 4);
                        $detail[$i]['D30'] = substr($line, 172, 1);
                        $detail[$i]['D31'] = substr($line, 173, 2);
                        $detail[$i]['D32'] = substr($line, 175, 6);
                        $detail[$i]['D33'] = substr($line, 181, 5);
                        $detail[$i]['D34'] = substr($line, 188, 11);
                        $detail[$i]['D35'] = substr($line, 201, 11);
                        $detail[$i]['D36'] = substr($line, 214, 11);
                        $detail[$i]['D37'] = substr($line, 227, 11);
                        $detail[$i]['D38'] = substr($line, 240, 11);
                        $detail[$i]['D39'] = substr($line, 253, 11);
                        $detail[$i]['D40'] = substr($line, 266, 11);
                        $detail[$i]['D41'] = substr($line, 279, 11);
                        $detail[$i]['D42'] = substr($line, 292, 11);
                        $detail[$i]['D43'] = substr($line, 305, 11);
                        $detail[$i]['D44'] = substr($line, 318, 1);
                        $detail[$i]['D45'] = substr($line, 319, 1);
                        $detail[$i]['D46'] = substr($line, 320, 10);
                        $detail[$i]['D47'] = substr($line, 332, 1);
                        $detail[$i]['D48'] = substr($line, 333, 9);
                        $detail[$i]['D49'] = substr($line, 342, 7);
                        $detail[$i]['D50'] = substr($line, 349, 9);
                        $detail[$i]['D51'] = substr($line, 358, 7);
                        $detail[$i]['D52'] = substr($line, 365, 9);
                        $detail[$i]['D53'] = substr($line, 374, 7);
                        $detail[$i]['D54'] = substr($line, 381, 9);
                        $detail[$i]['D55'] = substr($line, 390, 1);
                        $detail[$i]['D56'] = substr($line, 391, 1);
                        $detail[$i]['D57'] = substr($line, 392, 2);
                        $detail[$i]['D58'] = substr($line, 394, 6);
                    }
                    // trail
                    if (($i + 1) == count($lines)) {
                        $trail['T1'] = substr($line, 0, 1);
                        $trail['T2'] = substr($line, 1, 2);
                        $trail['T3'] = substr($line, 2, 2);
                        $trail['T4'] = substr($line, 4, 3);
                        $trail['T5'] = substr($line, 7, 10);
                        $trail['T6'] = substr($line, 17, 8);
                        $trail['T7'] = substr($line, 25, 13);
                        $trail['T8'] = substr($line, 39, 8);
                        $trail['T9'] = substr($line, 47, 10);
                        $trail['T10'] = substr($line, 57, 8);
                        $trail['T11'] = substr($line, 65, 13);
                        $trail['T12'] = substr($line, 79, 8);
                        $trail['T13'] = substr($line, 87, 10);
                        $trail['T14'] = substr($line, 97, 8);
                        $trail['T15'] = substr($line, 105, 13);
                        $trail['T16'] = substr($line, 119, 8);
                        $trail['T17'] = substr($line, 127, 10);
                        $trail['T18'] = substr($line, 137, 8);
                        $trail['T19'] = substr($line, 145, 13);
                        $trail['T20'] = substr($line, 159, 8);
                        $trail['T21'] = substr($line, 167, 50);
                        $trail['T22'] = substr($line, 217, 8);
                        $trail['T23'] = substr($line, 225, 13);
                        $trail['T24'] = substr($line, 239, 8);
                        $trail['T25'] = substr($line, 247, 147);
                        $trail['T26'] = substr($line, 394, 6);
                    }

                    $i++;
                }
            }

            fclose($file_handle);

//            var_dump(
//                $header,
//                $detail,
//                $trail
//            );die;
//            if ($id > 0) {
//                $record = ORM::for_table('module_billing_records')->find_one($id);
//                $record->attachment = $uploaded;
//                $record->save();
//                $id_record = $record->id();
//            }
//            list($width, $height, $type, $attr) = getimagesize('application/storage/billing/records/img/' . $uploaded);
//            $image = new Image();
//            $image->source_path = 'application/storage/billing/records/img/' . $uploaded;
//            $image->target_path = 'application/storage/billing/records/img/' . $uploaded;
//
//            if ($width > $height && $width > 800) {
//                $image->resize(800);
//            } else if ($height > $width && $height > 800) {
//                $image->resize(null, 800);
//            }
        } else {
            $file = '';
            $msg = $uploader->getMessage();
            $success = 'No';
            $id = '';
        }

        $response = array(
            'success' => $success,
            'msg' => $msg,
            'file' => $file,
            'id' => '' // $id_record
        );

        header('Content-Type: application/json');
        echo json_encode($response);

        break;

    case 'remove-returnfile-bancodobrasil':
        die('2');

        break;

    case 'get-returnfile-bancodobrasil':
        die('3');

        break;

    case 'report':
        $ui->assign('_st', $_L['Sales per client']);
        $d = filterReport($ui);

        Event::trigger('invoices/list/');
        $view_type = 'default';
        $css_arr = array(
            'dp/dist/datepicker.min',
            's2/css/select2.min');
        $js_arr = array(
            's2/js/select2.min',
            'numeric', 'invoice-report',
            'dp/dist/datepicker.min');


        $assets_css = Asset::css($css_arr);
        $assets_js = Asset::js($js_arr);
        $ui->assign('xheader', $assets_css);
        $ui->assign('xfooter', $assets_js);
        $ui->assign('view_type', $view_type);

        /*         * $pmethods = ORM::for_table('sys_pmethods')
          ->order_by_asc('sorder')
          ->find_array();
          $ui->assign('payment_methods', $pmethods);
         * */
        //bottom bar com as informações
        $total_value_invoice = 0;
        $total_value_paid = 0;
        for ($i = 0; $i < count($d); $i++) {
            //atribui os itens
            $d[$i]['itens'] = ORM::for_table('sys_invoiceitems')->where('invoiceid', $d[$i]['id'])->order_by_asc('id')->find_many();
            $total_value_invoice+=$d[$i]['total'];
            $total_value_paid+=$d[$i]['credit'];
        }


        $ui->assign('d', $d);
        $ui->assign('xjq', '
            $(\'.amount\').autoNumeric(\'init\', {
            dGroup: ' . $config['thousand_separator_placement'] . ',
            aPad: ' . $config['currency_decimal_digits'] . ',
            pSign: \'' . $config['currency_symbol_position'] . '\',
            aDec: \'' . $config['dec_point'] . '\',
            aSep: \'' . $config['thousands_sep'] . '\'
            });
        ');

        $bottomBar = array(
            //   array('type' => 'monetary', 'info' => $_L['Total Pending'], 'value' => ($total_value_invoice - $total_value_paid)),
            //   array('type' => 'monetary', 'info' => $_L['Total Paid'], 'value' => $total_value_paid),
            array('type' => 'monetary', 'info' => $_L['Total'], 'value' => $total_value_invoice),
            array('type' => 'int', 'info' => $_L['Total'] . " " . $_L['Invoices'], 'value' => count($d))
        );
        $ui->assign('bottomBar', $bottomBar);

        $ui->display('report-invoices.tpl');
        break;
        
    case 'report-product':
        $ui->assign('_st', $_L['Sales per product']);
        $d = filterReportProducts($ui);
//        var_dump($d[0]);exit;

        Event::trigger('invoices/list/');
        $view_type = 'default';
        $css_arr = array(
            'dp/dist/datepicker.min',
            's2/css/select2.min');
        $js_arr = array(
            's2/js/select2.min',
            'numeric', 'invoice-report',
            'dp/dist/datepicker.min');


        $assets_css = Asset::css($css_arr);
        $assets_js = Asset::js($js_arr);
        $ui->assign('xheader', $assets_css);
        $ui->assign('xfooter', $assets_js);
        $ui->assign('view_type', $view_type);

        /*         * $pmethods = ORM::for_table('sys_pmethods')
          ->order_by_asc('sorder')
          ->find_array();
          $ui->assign('payment_methods', $pmethods);
         * */
        //bottom bar com as informações
        $total_value_invoice = 0;
        $total_value_paid = 0;
        $total_produtos = 0;
        $total_aux = 0;
        $arr_total_produtos = array();
        for ($i = 0; $i < count($d); $i++) {
            $total_value_invoice += $d[$i]['total'];
            $total_produtos += $d[$i]['qty'];
            $total_aux = isset($arr_total_produtos[$d[$i]['description']])? intval($arr_total_produtos[$d[$i]['description']]):0;
            $arr_total_produtos[$d[$i]['description']] = $total_aux + $d[$i]['qty'];
        }


        $ui->assign('d', $d);
        $ui->assign('d_products', $arr_total_produtos);
        $ui->assign('xjq', '
            $(\'.amount\').autoNumeric(\'init\', {
            dGroup: ' . $config['thousand_separator_placement'] . ',
            aPad: ' . $config['currency_decimal_digits'] . ',
            pSign: \'' . $config['currency_symbol_position'] . '\',
            aDec: \'' . $config['dec_point'] . '\',
            aSep: \'' . $config['thousands_sep'] . '\'
            });
        ');

        $bottomBar = array(
            //   array('type' => 'monetary', 'info' => $_L['Total Pending'], 'value' => ($total_value_invoice - $total_value_paid)),
            //   array('type' => 'monetary', 'info' => $_L['Total Paid'], 'value' => $total_value_paid),
            array('type' => 'monetary', 'info' => $_L['Total'], 'value' => $total_value_invoice),
            array('type' => 'int', 'info' => $_L['Total'] . " " . $_L['Invoices'], 'value' => count($d)),
            array('type' => 'int', 'info' => $_L['Qty'] . " " . $_L['Products'], 'value' => $total_produtos)
        );
        $ui->assign('bottomBar', $bottomBar);

        $ui->display('report-invoices-products.tpl');
        break;
        
    case 'report-pdf':
        @ini_set('memory_limit', '512M');
        @ini_set('max_execution_time', 0);
        @set_time_limit(0);
        $d = filterReport($ui);

        if (isset($_SESSION['filter_report_invoice_search_contact'])&& !empty($_SESSION['filter_report_invoice_search_contact'])) {
            $contato = ORM::for_table('crm_accounts')->find_one($_SESSION['filter_report_invoice_search_contact']);
            $nomeContato = $contato->account;
        } else {
            $nomeContato = '';
        }


        $productss = array();
        $total_value_invoice = 0;
        $total_value_paid = 0;
        for ($i = 0; $i < count($d); $i++) {
            //atribui os itens
            $d[$i]['itens'] = ORM::for_table('sys_invoiceitems')->where('invoiceid', $d[$i]['id'])->order_by_asc('id')->find_many();
            foreach ($d[$i]['itens'] as $item) {
                if (isset($product[$item->sys_item_id])) {
                    $products[$item->sys_item_id]['qty']+=$item->qty;
                    $products[$item->sys_item_id]['total']+=$item->total;
                } else {
                    $products[$item->sys_item_id]['description'] = $item->description;
                    $products[$item->sys_item_id]['qty'] = $item->qty;
                    $products[$item->sys_item_id]['total'] = $item->total;
                }
            }

            $total_value_invoice+=$d[$i]['total'];
            $total_value_paid+=$d[$i]['credit'];
        }


        define('_MPDF_PATH', 'application/lib/mpdf/');

        require('application/lib/mpdf/mpdf.php');

        $pdf_c = '';
        $ib_w_font = 'dejavusanscondensed';
        if ($config['pdf_font'] == 'default') {
            $pdf_c = 'c';
            $ib_w_font = 'Helvetica';
        }

        $mpdf = new mPDF($pdf_c, 'A4', '', '', 20, 15, 15, 25, 10, 10);
//            $mpdf->SetProtection(array('print'));
        $mpdf->SetTitle($config['CompanyName'] . $_L['Sales per client']);
        $mpdf->SetAuthor($config['CompanyName']);
        //  $mpdf->SetWatermarkText(ib_lan_get_line($d['status']));
        $mpdf->showWatermarkText = true;
        $mpdf->watermark_font = $ib_w_font;
        $mpdf->watermarkTextAlpha = 0.1;
        $mpdf->SetDisplayMode('fullpage');
        $mpdf->SetFooter('{DATE d/m/Y H:i:s}|' . $config['CompanyName'] . '|Página {PAGENO} de {nb}');
        if ($config['pdf_font'] == 'AdobeCJK') {
            $mpdf->useAdobeCJK = true;
            $mpdf->autoScriptToLang = true;
            $mpdf->autoLangToFont = true;
        }

        $pdf_tpl = 'application/lib/invoices/report-pdf.php';

        ob_start();

        require $pdf_tpl;

        $html = ob_get_contents();


        ob_end_clean();

        $mpdf->WriteHTML($html);


        if ($r_type == 'dl') {
            $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'D'); # D
        } elseif ($r_type == 'inline') {
            $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'I'); # D
        } elseif ($r_type == 'store') {
            $mpdf->Output('application/storage/temp/Invoice_' . $in . '.pdf', 'F'); # D
        } else {
            $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'I'); # D
        }
        break;

    case 'report-pdf-c':
        @ini_set('memory_limit', '512M');
        @ini_set('max_execution_time', 0);
        @set_time_limit(0);
        $d = filterReport($ui);

        if (isset($_SESSION['filter_report_invoice_search_contact']) && !empty($_SESSION['filter_report_invoice_search_contact'])) {
            $contato = ORM::for_table('crm_accounts')->find_one($_SESSION['filter_report_invoice_search_contact']);
            $nomeContato = $contato->account;
        } else {
            $nomeContato = '';
        }

        $total_value_invoice = 0;
        for ($i = 0; $i < count($d); $i++) {
            $total_value_invoice+=$d[$i]['total'];
        }


        define('_MPDF_PATH', 'application/lib/mpdf/');

        require('application/lib/mpdf/mpdf.php');

        $pdf_c = '';
        $ib_w_font = 'dejavusanscondensed';
        if ($config['pdf_font'] == 'default') {
            $pdf_c = 'c';
            $ib_w_font = 'Helvetica';
        }

        $mpdf = new mPDF($pdf_c, 'A4', '', '', 20, 15, 15, 25, 10, 10);
//            $mpdf->SetProtection(array('print'));
        $mpdf->SetTitle($config['CompanyName'] . $_L['Sales per client']);
        $mpdf->SetAuthor($config['CompanyName']);
        //  $mpdf->SetWatermarkText(ib_lan_get_line($d['status']));
        $mpdf->showWatermarkText = true;
        $mpdf->watermark_font = $ib_w_font;
        $mpdf->watermarkTextAlpha = 0.1;
        $mpdf->SetDisplayMode('fullpage');
        $mpdf->SetFooter('{DATE d/m/Y H:i:s}|' . $config['CompanyName'] . '|Página {PAGENO} de {nb}');
        if ($config['pdf_font'] == 'AdobeCJK') {
            $mpdf->useAdobeCJK = true;
            $mpdf->autoScriptToLang = true;
            $mpdf->autoLangToFont = true;
        }

        $pdf_tpl = 'application/lib/invoices/report-pdf-c.php';

        ob_start();

        require $pdf_tpl;

        $html = ob_get_contents();


        ob_end_clean();

        $mpdf->WriteHTML($html);


        if ($r_type == 'dl') {
            $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'D'); # D
        } elseif ($r_type == 'inline') {
            $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'I'); # D
        } elseif ($r_type == 'store') {
            $mpdf->Output('application/storage/temp/Invoice_' . $in . '.pdf', 'F'); # D
        } else {
            $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'I'); # D
        }
        break;
        
    case 'report-product-pdf':
        @ini_set('memory_limit', '512M');
        @ini_set('max_execution_time', 0);
        @set_time_limit(0);
        $d = filterReportProducts($ui);

        if (isset($_SESSION['filter_report_invoice_search_contact']) && !empty($_SESSION['filter_report_invoice_search_contact'])) {
            $contato = ORM::for_table('crm_accounts')->find_one($_SESSION['filter_report_invoice_search_contact']);
            $nomeContato = $contato->account;
        } else {
            $nomeContato = '';
        }

        $total_value_invoice = 0;
        for ($i = 0; $i < count($d); $i++) {
            $total_value_invoice+=$d[$i]['total'];
        }
        
        //bottom bar com as informações
        $total_value_invoice = 0;
        $total_value_paid = 0;
        $total_produtos = 0;
        $total_aux = 0;
        $arr_total_produtos = array();
        for ($i = 0; $i < count($d); $i++) {
            $total_value_invoice += $d[$i]['total'];
            $total_produtos += $d[$i]['qty'];
            $total_aux = isset($arr_total_produtos[$d[$i]['description']])? intval($arr_total_produtos[$d[$i]['description']]):0;
            $arr_total_produtos[$d[$i]['description']] = $total_aux + $d[$i]['qty'];
        }
        $d_products = $arr_total_produtos;

        define('_MPDF_PATH', 'application/lib/mpdf/');

        require('application/lib/mpdf/mpdf.php');

        $pdf_c = '';
        $ib_w_font = 'dejavusanscondensed';
        if ($config['pdf_font'] == 'default') {
            $pdf_c = 'c';
            $ib_w_font = 'Helvetica';
        }

        $mpdf = new mPDF($pdf_c, 'A4', '', '', 20, 15, 15, 25, 10, 10);
//            $mpdf->SetProtection(array('print'));
        $mpdf->SetTitle($config['CompanyName'] . $_L['Sales per client']);
        $mpdf->SetAuthor($config['CompanyName']);
        //  $mpdf->SetWatermarkText(ib_lan_get_line($d['status']));
        $mpdf->showWatermarkText = true;
        $mpdf->watermark_font = $ib_w_font;
        $mpdf->watermarkTextAlpha = 0.1;
        $mpdf->SetDisplayMode('fullpage');
        $mpdf->SetFooter('{DATE d/m/Y H:i:s}|' . $config['CompanyName'] . '|Página {PAGENO} de {nb}');
        if ($config['pdf_font'] == 'AdobeCJK') {
            $mpdf->useAdobeCJK = true;
            $mpdf->autoScriptToLang = true;
            $mpdf->autoLangToFont = true;
        }

        $pdf_tpl = 'application/lib/invoices/report-product-pdf.php';

        ob_start();

        require $pdf_tpl;

        $html = ob_get_contents();


        ob_end_clean();

        $mpdf->WriteHTML($html);


        if ($r_type == 'dl') {
            $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'D'); # D
        } elseif ($r_type == 'inline') {
            $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'I'); # D
        } elseif ($r_type == 'store') {
            $mpdf->Output('application/storage/temp/Invoice_' . $in . '.pdf', 'F'); # D
        } else {
            $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'I'); # D
        }
        break;    
    default:
        echo 'action not defined';
}

function filterReport($ui) {
    $where = '';
    if (_post('filter') == 'Y') {
        $_SESSION['filter_report_invoice_id_payment_method'] = _post('id_payment_method');
        $_SESSION['filter_report_invoice_situation'] = _post('situation');
        $_SESSION['filter_report_invoice_search_contact'] = _post('search_contact');
        $_SESSION['filter_report_invoice_period'] = _post('period');
        if ($_SESSION['filter_report_invoice_period'] == 'interval') {
            $_SESSION['filter_report_invoice_period_ini'] = _postDate('period_ini', $_c);
            $_SESSION['filter_report_invoice_period_end'] = _postDate('period_end', $_c);
        } else {
            $_SESSION['filter_report_invoice_period_ini'] = '';
            $_SESSION['filter_report_invoice_period_end'] = '';
        }
    }

    if (isset($_SESSION['filter_report_invoice_situation']) && $_SESSION['filter_report_invoice_situation'] != 'All' && !empty($_SESSION['filter_report_invoice_situation'])) {
        $where.=" AND s.status='" . $_SESSION['filter_report_invoice_situation'] . "'";
        $filter['filter_report_invoice_situation'] = $_SESSION['filter_report_invoice_situation'];
    } else {
        $filter['filter_report_invoice_situation'] = null;
    }
    if (isset($_SESSION['filter_report_invoice_search_contact']) && !empty($_SESSION['filter_report_invoice_search_contact'])) {
        $where.=" AND s.userid =" . $_SESSION['filter_report_invoice_search_contact'];
        $filter['filter_report_invoice_search_contact'] = $_SESSION['filter_report_invoice_search_contact'];
    } else {
        $filter['filter_report_invoice_search_contact'] = '';
    }

    if (isset($_SESSION['filter_report_invoice_period']) && $_SESSION['filter_report_invoice_period'] != 'all' && !empty($_SESSION['filter_report_invoice_period'])) {

        if ($_SESSION['filter_report_invoice_period'] == 'day')
            $where .= " AND s.duedate = '" . date('Y-m-d') . "'";
        if ($_SESSION['filter_report_invoice_period'] == 'week')
            $where .= " AND WEEK(s.duedate) = WEEK('" . date('Y-m-d') . "')";
        if ($_SESSION['filter_report_invoice_period'] == 'month')
            $where .= " AND MONTH(s.duedate) = MONTH('" . date('Y-m-d') . "')";

        if (!empty($_SESSION['filter_report_invoice_period_ini'])) {
            $where .= " AND s.duedate >='" . date('Y-m-d', strtotime($_SESSION['filter_report_invoice_period_ini'])) . "'";
            $filter['filter_report_invoice_period_ini'] = $_SESSION['filter_report_invoice_period_ini'];
        } else {
            $filter['filter_report_invoice_period_ini'] = '';
        }
        if (!empty($_SESSION['filter_report_invoice_period_end'])) {
            $where .= " AND s.duedate <='" . date('Y-m-d', strtotime($_SESSION['filter_report_invoice_period_end'])) . "'";
            $filter['filter_report_invoice_period_end'] = $_SESSION['filter_report_invoice_period_end'];
        } else {
            $filter['filter_report_invoice_period_end'] = '';
        }


        $filter['filter_report_invoice_period'] = $_SESSION['filter_report_invoice_period'];
    } else {
        $filter['filter_report_invoice_period'] = '';
    }
    /**
      if (isset($_SESSION['filter_report_invoice_id_payment_method']) && intval($_SESSION['filter_report_invoice_id_payment_method']) > 0) {
      $where.=' AND s.paymentmethod=' . $_SESSION['filter_report_invoice_id_payment_method'];
      $filter['id_payment_method'] = $_SESSION['filter_report_invoice_id_payment_method'];
      } else {
      $filter['id_payment_method'] = '';
      }
     * */
    $sql = 'Select s.*,sp.name as pmethod from sys_invoices s left join sys_pmethods sp on (s.paymentmethod=sp.id)' . (empty($where) ? '' : " Where " . substr($where, 4));

    $c = ORM::for_table('sys_invoices')
            ->raw_query($sql);
    $d = $c->find_many();
    if (!empty($ui)) {
        $ui->assign('filter', $filter);
    }
    return $d;
}

function filterReportProducts($ui) {
    $where = '';
    if (_post('filter') == 'Y') {
        $_SESSION['filter_report_invoice_id_payment_method'] = _post('id_payment_method');
        $_SESSION['filter_report_invoice_situation'] = _post('situation');
        $_SESSION['filter_report_invoice_search_product'] = _post('search_product');
        $_SESSION['filter_report_invoice_period'] = _post('period');
        if ($_SESSION['filter_report_invoice_period'] == 'interval') {
            $_SESSION['filter_report_invoice_period_ini'] = _postDate('period_ini', $_c);
            $_SESSION['filter_report_invoice_period_end'] = _postDate('period_end', $_c);
        } else {
            $_SESSION['filter_report_invoice_period_ini'] = '';
            $_SESSION['filter_report_invoice_period_end'] = '';
        }
    }

    if (isset($_SESSION['filter_report_invoice_situation']) && $_SESSION['filter_report_invoice_situation'] != 'All' && !empty($_SESSION['filter_report_invoice_situation'])) {
        $where.=" AND s.status='" . $_SESSION['filter_report_invoice_situation'] . "'";
        $filter['filter_report_invoice_situation'] = $_SESSION['filter_report_invoice_situation'];
    } else {
        $filter['filter_report_invoice_situation'] = null;
    }
    
    // filtro por produto
    if (isset($_SESSION['filter_report_invoice_search_product']) && !empty($_SESSION['filter_report_invoice_search_product'])) {
        $where.=" AND si.sys_item_id =" . $_SESSION['filter_report_invoice_search_product'];
        $filter['filter_report_invoice_search_product'] = $_SESSION['filter_report_invoice_search_product'];
    } else {
        $filter['filter_report_invoice_search_product'] = '';
    }

    if (isset($_SESSION['filter_report_invoice_period']) && $_SESSION['filter_report_invoice_period'] != 'all' && !empty($_SESSION['filter_report_invoice_period'])) {

        if ($_SESSION['filter_report_invoice_period'] == 'day')
            $where .= " AND s.duedate = '" . date('Y-m-d') . "'";
        if ($_SESSION['filter_report_invoice_period'] == 'week')
            $where .= " AND WEEK(s.duedate) = WEEK('" . date('Y-m-d') . "')";
        if ($_SESSION['filter_report_invoice_period'] == 'month')
            $where .= " AND MONTH(s.duedate) = MONTH('" . date('Y-m-d') . "')";

        if (!empty($_SESSION['filter_report_invoice_period_ini'])) {
            $where .= " AND s.duedate >='" . date('Y-m-d', strtotime($_SESSION['filter_report_invoice_period_ini'])) . "'";
            $filter['filter_report_invoice_period_ini'] = $_SESSION['filter_report_invoice_period_ini'];
        } else {
            $filter['filter_report_invoice_period_ini'] = '';
        }
        if (!empty($_SESSION['filter_report_invoice_period_end'])) {
            $where .= " AND s.duedate <='" . date('Y-m-d', strtotime($_SESSION['filter_report_invoice_period_end'])) . "'";
            $filter['filter_report_invoice_period_end'] = $_SESSION['filter_report_invoice_period_end'];
        } else {
            $filter['filter_report_invoice_period_end'] = '';
        }


        $filter['filter_report_invoice_period'] = $_SESSION['filter_report_invoice_period'];
    } else {
        $filter['filter_report_invoice_period'] = '';
    }
    /**
      if (isset($_SESSION['filter_report_invoice_id_payment_method']) && intval($_SESSION['filter_report_invoice_id_payment_method']) > 0) {
      $where.=' AND s.paymentmethod=' . $_SESSION['filter_report_invoice_id_payment_method'];
      $filter['id_payment_method'] = $_SESSION['filter_report_invoice_id_payment_method'];
      } else {
      $filter['id_payment_method'] = '';
      }
     * */
    $sql = 'Select s.id, s.account, s.date, s.duedate, s.status, si.description, si.qty, si.amount, si.discount, si.total, sp.name as pmethod '
            . 'from sys_invoices s '
            . 'left join sys_pmethods sp on (s.paymentmethod=sp.id)' 
            . 'left join sys_invoiceitems si on (s.id=si.invoiceid)' 
            . (empty($where) ? '' : " Where " . substr($where, 4))
            . ' ORDER BY s.id';

    $c = ORM::for_table('sys_invoices')
            ->raw_query($sql);
    $d = $c->find_many();
    if (!empty($ui)) {
        $ui->assign('filter', $filter);
    }
    return $d;
}

Anon7 - 2022
AnonSec Team