<?php

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

class Proformas extends AdminController
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('proformas_model');
        $this->load->model('credit_notes_model');

        $this->app_scripts->add('crm-js', 'assets/js/crm.js');
        $this->app_css->add('item_documents', 'assets/css/item_documents.css');

        $this->load->model('billing/billing_series_model');


        // Tailwind
        $this->app_css->add('defStyle', 'assets/css/defStyle.css');

        // Rxjs
        $this->app_scripts->add('rxjs', 'https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.4.0/rxjs.umd.min.js');
    }

    /* Get all proformas in case user go on index page */
    public function index($id = '')
    {
        $this->list_proformas($id);
    }

    /* List all proformas datatables */
    public function list_proformas($id = '')
    {
        if (!has_permission('proformas', '', 'view')
            && !has_permission('proformas', '', 'view_own')
            && get_option('allow_staff_view_proformas_assigned') == '0') {
            access_denied('proformas');
        }

        close_setup_menu();

        $this->load->model('payment_modes_model');
        $data['payment_modes'] = $this->payment_modes_model->get('', [], true);
        $data['proformaid'] = $id;
        $data['title'] = _l('proformas');
        $data['proformas_years'] = $this->proformas_model->get_proformas_years();
        $data['proformas_sale_agents'] = $this->proformas_model->get_sale_agents();
        $data['proformas_statuses'] = $this->proformas_model->get_statuses();
        $data['bodyclass'] = 'proformas-total-manual';

        $settings['vat_payer'] = (int)get_option('settings_company_vat_payer');
        $settings['vat_on_collection'] = (int)get_option('settings_company_vat_on_collection');
        if ($settings['vat_on_collection'] == 1) {
            $display_vat_collection = '<p>' . _l('invoice_notice_vat_on_collection') . '</p>';
            $settings['display_vat_collection'] = $display_vat_collection;
        }
        $settings['show_tax_per_item'] = (int)get_option('show_tax_per_item');
        $data['invoice_settings'] = get_option('invoice_settings');
        $data['invoice_settings'] = json_decode($data['invoice_settings'], true);

        $data['settings'] = $settings;
        $this->load->model('currencies_model');
        $data['currencies'] = $this->currencies_model->get();
        $data['base_currency'] = $this->currencies_model->get_base_currency();

        $this->load->view('admin/proformas/manage', $data);
    }

    /* List all recurring proformas */
    public function recurring($id = '')
    {
        if (!has_permission('proformas', '', 'view')
            && !has_permission('proformas', '', 'view_own')
            && get_option('allow_staff_view_proformas_assigned') == '0') {
            access_denied('proformas');
        }

        close_setup_menu();

        $this->load->model('payment_modes_model');
        $data['payment_modes'] = $this->payment_modes_model->get('', [], true);
        $data['proformaid'] = $id;
        $data['title'] = _l('proformas_list_recurring');
        $data['proformas_years'] = $this->proformas_model->get_proformas_years();
        $data['proformas_sale_agents'] = $this->proformas_model->get_sale_agents();
        $data['proformas_statuses'] = $this->proformas_model->get_statuses();
        $data['bodyclass'] = 'proformas-total-manual';

        $settings['vat_payer'] = (int)get_option('settings_company_vat_payer');
        $settings['vat_on_collection'] = (int)get_option('settings_company_vat_on_collection');
        if ($settings['vat_on_collection'] == 1) {
            $display_vat_collection = '<p>' . _l('invoice_notice_vat_on_collection') . '</p>';
            $settings['display_vat_collection'] = $display_vat_collection;
        }
        $settings['show_tax_per_item'] = (int)get_option('show_tax_per_item');
        $data['invoice_settings'] = get_option('invoice_settings');
        $data['invoice_settings'] = json_decode($data['invoice_settings'], true);

        $data['settings'] = $settings;

        $this->load->view('admin/proformas/recurring/list', $data);
    }

    public function table($clientid = '')
    {
        if (!has_permission('proformas', '', 'view')
            && !has_permission('proformas', '', 'view_own')
            && get_option('allow_staff_view_proformas_assigned') == '0') {
            ajax_access_denied();
        }

        $this->load->model('payment_modes_model');
        $data['payment_modes'] = $this->payment_modes_model->get('', [], true);

        $this->app->get_table_data(($this->input->get('recurring') ? 'recurring_proformas' : 'proformas'), [
            'clientid' => $clientid,
            'data' => $data,
        ]);
    }

    public function client_change_data($customer_id, $current_proforma = '')
    {
        if ($this->input->is_ajax_request()) {
            $this->load->model('projects_model');
            $data = [];
            $data['billing_shipping'] = $this->clients_model->get_customer_billing_and_shipping_details($customer_id);
            $data['client_currency'] = $this->clients_model->get_customer_default_currency($customer_id);

            $data['customer_has_projects'] = customer_has_projects($customer_id);
            $data['billable_tasks'] = $this->tasks_model->get_billable_tasks($customer_id);

            if ($current_proforma != '') {
                $this->db->select('status');
                $this->db->where('id', $current_proforma);
                $current_proforma_status = $this->db->get(db_prefix() . 'proformas')->row()->status;
            }

            $_data['proformas_to_merge'] = !isset($current_proforma_status) || (isset($current_proforma_status) && $current_proforma_status != Invoices_model::STATUS_CANCELLED) ? $this->proformas_model->check_for_merge_proforma($customer_id, $current_proforma) : [];

            $data['merge_info'] = $this->load->view('admin/proformas/merge_proforma', $_data, true);

            $this->load->model('currencies_model');

            $__data['expenses_to_bill'] = !isset($current_proforma_status) || (isset($current_proforma_status) && $current_proforma_status != Invoices_model::STATUS_CANCELLED) ? $this->proformas_model->get_expenses_to_bill($customer_id) : [];

            $data['expenses_bill_info'] = $this->load->view('admin/proformas/bill_expenses', $__data, true);
            echo json_encode($data);
        }
    }

    public function get_seria()
    {

        $seria = $this->input->post('seria');
        $seria_data = $this->invoices_model->get_seria($seria);
        $seria_data['next_number'] = ((int)$seria_data['current_number'] + 1);
        echo json_encode($seria_data);
        die;
    }

    public function update_number_settings($id)
    {
        $response = [
            'success' => false,
            'message' => '',
        ];
        if (has_permission('proformas', '', 'edit')) {
            $affected_rows = 0;

            $this->db->where('id', $id);
            $this->db->update(db_prefix() . 'proformas', [
                'prefix' => $this->input->post('prefix'),
            ]);
            if ($this->db->affected_rows() > 0) {
                $affected_rows++;
            }

            if ($affected_rows > 0) {
                $response['success'] = true;
                $response['message'] = _l('updated_successfully', _l('proforma'));
            }
        }
        echo json_encode($response);
        die;
    }

    public function validate_proforma_number()
    {
        $isedit = $this->input->post('isedit');
        $number = $this->input->post('number');
        $date = $this->input->post('date');
        $original_number = $this->input->post('original_number');
        $number = trim($number);
        $number = ltrim($number, '0');

        if ($isedit == 'true') {
            if ($number == $original_number) {
                echo json_encode(true);
                die;
            }
        }

        if (total_rows(db_prefix() . 'proformas', [
                'YEAR(date)' => date('Y', strtotime(to_sql_date($date))),
                'number' => $number,
                'status !=' => Proformas_model::STATUS_DRAFT,
            ]) > 0) {
            echo 'false';
        } else {
            echo 'true';
        }
    }

    public function validate_invoice_number_seria()
    {
        $isedit = $this->input->post('isedit');
        $number = $this->input->post('number');
        $seria = $this->input->post('seria');
        $date = $this->input->post('date');
        $original_number = $this->input->post('original_number');
        $number = trim($number);
        $number = ltrim($number, '0');

        if ($isedit == 'true') {
            if ($number == $original_number) {
                echo json_encode(true);
                die;
            }
        }

        if (total_rows(db_prefix() . 'billing_series', [
                //'YEAR(date)' => date('Y', strtotime(to_sql_date($date))),
                'name' => $seria,
                'current_number >=' => $number,

            ]) > 0) {
            echo 'false';
        } else {
            echo 'true';
        }
    }

    public function add_note($rel_id)
    {
        if ($this->input->post() && user_can_view_proforma($rel_id)) {
            $this->misc_model->add_note($this->input->post(), 'proforma', $rel_id);
            echo $rel_id;
        }
    }

    public function get_notes($id)
    {
        if (user_can_view_proforma($id)) {
            $data['notes'] = $this->misc_model->get_notes($id, 'proforma');
            $this->load->view('admin/includes/sales_notes_template', $data);
        }
    }

    public function pause_overdue_reminders($id)
    {
        if (has_permission('proformas', '', 'edit')) {
            $this->db->where('id', $id);
            $this->db->update(db_prefix() . 'proformas', ['cancel_overdue_reminders' => 1]);
        }
        redirect(admin_url('proformas/list_proformas/' . $id));
    }

    public function resume_overdue_reminders($id)
    {
        if (has_permission('proformas', '', 'edit')) {
            $this->db->where('id', $id);
            $this->db->update(db_prefix() . 'proformas', ['cancel_overdue_reminders' => 0]);
        }
        redirect(admin_url('proformas/list_proformas/' . $id));
    }

    public function mark_as_cancelled($id)
    {
        if (!has_permission('proformas', '', 'edit') && !has_permission('proformas', '', 'create')) {
            access_denied('proformas');
        }

        $success = $this->proformas_model->mark_as_cancelled($id);

        if ($success) {
            set_alert('success', _l('proforma_marked_as_cancelled_successfully'));
        }

        redirect(admin_url('proformas/list_proformas/' . $id));
    }

    public function unmark_as_cancelled($id)
    {
        if (!has_permission('proformas', '', 'edit') && !has_permission('proformas', '', 'create')) {
            access_denied('proformas');
        }
        $success = $this->proformas_model->unmark_as_cancelled($id);
        if ($success) {
            set_alert('success', _l('proforma_unmarked_as_cancelled'));
        }
        redirect(admin_url('proformas/list_proformas/' . $id));
    }

    public function copy($id)
    {
        if (!$id) {
            redirect(admin_url('proformas'));
        }
        if (!has_permission('proformas', '', 'create')) {
            access_denied('proformas');
        }
        $new_id = $this->proformas_model->copy($id);
        if ($new_id) {
            set_alert('success', _l('proforma_copy_success'));
            redirect(admin_url('proformas/proforma/' . $new_id));
        } else {
            set_alert('success', _l('proforma_copy_fail'));
        }
        redirect(admin_url('proformas/proforma/' . $id));
    }

    public function get_merge_data($id)
    {
        $proforma = $this->proformas_model->get($id);
        $cf = get_custom_fields('items');

        $i = 0;

        foreach ($proforma->items as $item) {
            $proforma->items[$i]['taxname'] = get_proforma_item_taxes($item['id']);
            $proforma->items[$i]['long_description'] = clear_textarea_breaks($item['long_description']);
            $this->db->where('item_id', $item['id']);
            $rel = $this->db->get(db_prefix() . 'related_items')->result_array();
            $item_related_val = '';
            $rel_type = '';
            foreach ($rel as $item_related) {
                $rel_type = $item_related['rel_type'];
                $item_related_val .= $item_related['rel_id'] . ',';
            }
            if ($item_related_val != '') {
                $item_related_val = substr($item_related_val, 0, -1);
            }
            $proforma->items[$i]['item_related_formatted_for_input'] = $item_related_val;
            $proforma->items[$i]['rel_type'] = $rel_type;

            $proforma->items[$i]['custom_fields'] = [];

            foreach ($cf as $custom_field) {
                $custom_field['value'] = get_custom_field_value($item['id'], $custom_field['id'], 'items');
                $proforma->items[$i]['custom_fields'][] = $custom_field;
            }
            $i++;
        }
        echo json_encode($proforma);
    }

    public function get_bill_expense_data($id)
    {
        $this->load->model('expenses_model');
        $expense = $this->expenses_model->get($id);

        $expense->qty = 1;
        $expense->long_description = clear_textarea_breaks($expense->description);
        $expense->description = $expense->name;
        $expense->rate = $expense->amount;
        if ($expense->tax != 0) {
            $expense->taxname = [];
            array_push($expense->taxname, $expense->tax_name . '|' . $expense->taxrate);
        }
        if ($expense->tax2 != 0) {
            array_push($expense->taxname, $expense->tax_name2 . '|' . $expense->taxrate2);
        }
        echo json_encode($expense);
    }

    /* Add new proforma or update existing */
    public function proforma($id = '')
    {

        $series = $this->proformas_model->get_series();
        if (empty($series)) {
            set_alert('warning', _l('no_billling_series_in_account', _l('billing')));
            redirect(admin_url('billing/config/series'));
        }

        if ($this->input->post()) {
            $proforma_data = $this->input->post();
            if ($id == '') {
                if (!has_permission('proformas', '', 'create')) {
                    access_denied('proformas');
                }
                $id = $this->proformas_model->add($proforma_data);
                if ($id) {
                    set_alert('success', _l('added_successfully', _l('proforma')));
                    $redUrl = admin_url('proformas/list_proformas/' . $id);

                    if (isset($proforma_data['save_and_record_payment'])) {
                        $this->session->set_userdata('record_payment', true);
                    } elseif (isset($proforma_data['save_and_send_later'])) {
                        $this->session->set_userdata('send_later', true);
                    }

                    redirect($redUrl);
                }
            } else {
                if (!has_permission('proformas', '', 'edit')) {
                    access_denied('proformas');
                }
                $success = $this->proformas_model->update($proforma_data, $id);
                if ($success) {
                    set_alert('success', _l('updated_successfully', _l('proforma')));
                }
                redirect(admin_url('proformas/list_proformas/' . $id));
            }
        }
        if ($id == '') {
            $title = _l('create_new_proforma');
            $data['billable_tasks'] = [];
        } else {
            $proforma = $this->proformas_model->get($id);

            if (!$proforma || !user_can_view_proforma($id)) {
                blank_page(_l('proforma_not_found'));
            }

            $data['proformas_to_merge'] = $this->proformas_model->check_for_merge_proforma($proforma->clientid, $proforma->id);
            $data['expenses_to_bill'] = $this->proformas_model->get_expenses_to_bill($proforma->clientid);

            $data['proforma'] = $proforma;
            $data['edit'] = true;
            $data['billable_tasks'] = $this->tasks_model->get_billable_tasks($proforma->clientid, !empty($proforma->project_id) ? $proforma->project_id : '');

            $title = _l('edit', _l('proforma_lowercase')) . ' - ' . format_proforma_number($proforma->id);
        }

        if ($this->input->get('customer_id')) {
            $data['customer_id'] = $this->input->get('customer_id');
        }

        $this->load->model('payment_modes_model');
        $data['payment_modes'] = $this->payment_modes_model->get('', [
            'expenses_only !=' => 1,
        ]);

        $this->load->model('taxes_model');
        $data['taxes'] = $this->taxes_model->get();
        $this->load->model('invoice_items_model');

        $data['ajaxItems'] = false;
        if (total_rows(db_prefix() . 'items') <= ajax_on_total_items()) {
            $data['items'] = $this->invoice_items_model->get_grouped();

            if (!empty($data['items'])) {
                foreach ($data['items'] as $key => $group) {
                    foreach ($group as $itemkey => $item) {
                        if (isset($data['items'][$key][$itemkey]['group_type'])) {
                            if ($data['items'][$key][$itemkey]['group_type'] == '1') {
                                $data['items'][$key][$itemkey]['name'] = $item['group_name'] . ' (Products)';
                                $data['items'][$key][$itemkey]['group_name'] = $item['group_name'] . ' (Products)';

                            } else if ($data['items'][$key][$itemkey]['group_type'] == '2') {
                                $data['items'][$key][$itemkey]['name'] = $item['group_name'] . ' (Services)';
                                $data['items'][$key][$itemkey]['group_name'] = $item['group_name'] . ' (Services)';

                            }
                        }
                    }
                }
            }

        } else {
            $data['items'] = [];
            $data['ajaxItems'] = true;
        }
        //echo '<pre>'; var_dump($data['items']); exit;
        $data['items_groups'] = $this->invoice_items_model->get_groups();
        //echo '<pre>'; var_dump($data['items_groups']); exit;
        if (!empty($data['items_groups'])) {
            foreach ($data['items_groups'] as $key => $group) {
                if ($group['group_type'] == '1') {
                    $data['items_groups'][$key]['name'] = $group['name'] . ' (Products)';
                } else if ($group['group_type'] == '2') {
                    $data['items_groups'][$key]['name'] = $group['name'] . ' (Services)';
                }
            }
        }

        $this->load->model('currencies_model');
        $data['currencies'] = $this->currencies_model->get();

        $data['base_currency'] = $this->currencies_model->get_base_currency();

        $data['staff'] = $this->staff_model->get('', ['active' => 1]);
        $data['title'] = $title;
        $data['bodyclass'] = 'proforma';

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

        $data['settings'] = $settings;

        $data['invoice_settings'] = get_option('invoice_settings');
        $data['invoice_settings'] = json_decode($data['invoice_settings'], true);

        $this->load->view('admin/proformas/proforma', $data);
    }

    /* Get all proforma data used when user click on invoiec number in a datatable left side*/
    public function get_proforma_data_ajax($id)
    {
        if (!has_permission('proformas', '', 'view')
            && !has_permission('proformas', '', 'view_own')
            && get_option('allow_staff_view_proformas_assigned') == '0') {
            echo _l('access_denied');
            die;
        }

        if (!$id) {
            die(_l('proforma_not_found'));
        }

        $proforma = $this->proformas_model->get($id);

        if (!$proforma || !user_can_view_proforma($id)) {
            echo _l('proforma_not_found');
            die;
        }

        $proforma->date = _d($proforma->date);
        $proforma->duedate = _d($proforma->duedate);

        $template_name = 'proforma_send_to_customer'; // proforma_send_to_customer

        if ($proforma->sent == 1) {
            $template_name = 'proforma_send_to_customer_already_sent'; // proforma_send_to_customer_already_sent
        }

        $data = prepare_mail_preview_data($template_name, $proforma->clientid);

        // Check for recorded payments
        $this->load->model('payments_model');
        $data['proformas_to_merge'] = $this->proformas_model->check_for_merge_proforma($proforma->clientid, $id);
        $data['members'] = $this->staff_model->get('', ['active' => 1]);
        $data['payments'] = $this->payments_model->get_proforma_payments($id);
        $data['activity'] = $this->proformas_model->get_proforma_activity($id);
        $data['totalNotes'] = total_rows(db_prefix() . 'notes', ['rel_id' => $id, 'rel_type' => 'proforma']);
        $data['proforma_recurring_proformas'] = $this->proformas_model->get_proforma_recurring_proformas($id);

        $data['proforma'] = $proforma;

        $data['record_payment'] = false;
        $data['send_later'] = false;

        if ($this->session->has_userdata('record_payment')) {
            $data['record_payment'] = true;
            $this->session->unset_userdata('record_payment');
        } elseif ($this->session->has_userdata('send_later')) {
            $data['send_later'] = true;
            $this->session->unset_userdata('send_later');
        }
        $data['proforma']->options = json_decode(get_option('invoice_settings'), TRUE);

        $this->load->view('admin/proformas/proforma_preview_template', $data);
    }

    public function apply_credits($proforma_id)
    {
        $total_credits_applied = 0;
        foreach ($this->input->post('amount') as $credit_id => $amount) {
            $success = $this->credit_notes_model->apply_credits($credit_id, [
                'proforma_id' => $proforma_id,
                'amount' => $amount,
            ]);
            if ($success) {
                $total_credits_applied++;
            }
        }

        if ($total_credits_applied > 0) {
            update_proforma_status($proforma_id, true);
            set_alert('success', _l('proforma_credits_applied'));
        }
        redirect(admin_url('proformas/list_proformas/' . $proforma_id));
    }

    public function get_proformas_total()
    {
        if ($this->input->post()) {
            load_proformas_total_template();
        }
    }

    /* Record new inoice payment view */
    public function record_proforma_payment_ajax($id)
    {
        $this->load->model('payment_modes_model');
        $this->load->model('payments_model');
        $data['payment_modes'] = $this->payment_modes_model->get('', [
            'expenses_only !=' => 1,
        ]);
        $data['proforma'] = $this->proformas_model->get($id);
        $data['payments'] = $this->payments_model->get_proforma_payments($id);
        $this->load->view('admin/proformas/record_payment_template', $data);
    }

    /* This is where proforma payment record $_POST data is send */
    public function record_payment()
    {
        if (!has_permission('payments', '', 'create')) {
            access_denied('Record Payment');
        }
        if ($this->input->post()) {
            $this->load->model('payments_model');
            $id = $this->payments_model->process_payment($this->input->post(), '', 'proforma');
            if ($id) {
                set_alert('success', _l('proforma_payment_recorded'));
                redirect(admin_url('payments/payment/' . $id));
            } else {
                set_alert('danger', _l('proforma_payment_record_failed'));
            }
            redirect(admin_url('proformas/list_proformas/' . $this->input->post('proformaid')));
        }
    }

    /* Send proforma to email */
    public function send_to_email($id)
    {
        $canView = user_can_view_proforma($id);
        if (!$canView) {
            access_denied('Invoices');
        } else {
            if (!has_permission('proformas', '', 'view') && !has_permission('proformas', '', 'view_own') && $canView == false) {
                access_denied('Invoices');
            }
        }

        try {
            $statementData = [];
            if ($this->input->post('attach_statement')) {
                $statementData['attach'] = true;
                $statementData['from'] = to_sql_date($this->input->post('statement_from'));
                $statementData['to'] = to_sql_date($this->input->post('statement_to'));
            }

            $success = $this->proformas_model->send_proforma_to_client(
                $id,
                '',
                $this->input->post('attach_pdf'),
                $this->input->post('cc'),
                false,
                $statementData
            );
        } catch (Exception $e) {
            $message = $e->getMessage();
            echo $message;
            if (strpos($message, 'Unable to get the size of the image') !== false) {
                show_pdf_unable_to_get_image_size_error();
            }
            die;
        }

        // In case client use another language
        load_admin_language();
        if ($success) {
            set_alert('success', _l('proforma_sent_to_client_success'));
        } else {
            set_alert('danger', _l('proforma_sent_to_client_fail'));
        }
        redirect(admin_url('proformas/list_proformas/' . $id));
    }

    /* Delete proforma payment*/
    public function delete_payment($id, $proformaid)
    {
        if (!has_permission('payments', '', 'delete')) {
            access_denied('payments');
        }
        $this->load->model('payments_model');
        if (!$id) {
            redirect(admin_url('payments'));
        }
        $response = $this->payments_model->delete($id);
        if ($response == true) {
            set_alert('success', _l('deleted', _l('payment')));
        } else {
            set_alert('warning', _l('problem_deleting', _l('payment_lowercase')));
        }
        redirect(admin_url('proformas/list_proformas/' . $proformaid));
    }

    /* Delete proforma */
    public function delete($id)
    {
        if (!has_permission('proformas', '', 'delete')) {
            access_denied('proformas');
        }
        if (!$id) {
            redirect(admin_url('proformas/list_proformas'));
        }
        $success = $this->proformas_model->delete($id);

        if ($success) {
            set_alert('success', _l('deleted', _l('proforma')));
        } else {
            set_alert('warning', _l('problem_deleting', _l('proforma_lowercase')));
        }
        if (strpos($_SERVER['HTTP_REFERER'], 'list_proformas') !== false) {
            redirect(admin_url('proformas/list_proformas'));
        } else {
            redirect($_SERVER['HTTP_REFERER']);
        }
    }

    public function delete_attachment($id)
    {
        $file = $this->misc_model->get_file($id);
        if ($file->staffid == get_staff_user_id() || is_admin()) {
            echo $this->proformas_model->delete_attachment($id);
        } else {
            header('HTTP/1.0 400 Bad error');
            echo _l('access_denied');
            die;
        }
    }

    /* Will send overdue notice to client */
    public function send_overdue_notice($id)
    {
        $canView = user_can_view_proforma($id);
        if (!$canView) {
            access_denied('Invoices');
        } else {
            if (!has_permission('proformas', '', 'view') && !has_permission('proformas', '', 'view_own') && $canView == false) {
                access_denied('Invoices');
            }
        }

        $send = $this->proformas_model->send_proforma_overdue_notice($id);
        if ($send) {
            set_alert('success', _l('proforma_overdue_reminder_sent'));
        } else {
            set_alert('warning', _l('proforma_reminder_send_problem'));
        }
        redirect(admin_url('proformas/list_proformas/' . $id));
    }

    /* Generates proforma PDF and senting to email of $send_to_email = true is passed */
    public function pdf($id)
    {
        if (!$id) {
            redirect(admin_url('proformas/list_proformas'));
        }

        $canView = user_can_view_proforma($id);
        if (!$canView) {
            access_denied('Invoices');
        } else {
            if (!has_permission('proformas', '', 'view') && !has_permission('proformas', '', 'view_own') && $canView == false) {
                access_denied('Invoices');
            }
        }

        $proforma = $this->proformas_model->get($id);
        $proforma = hooks()->apply_filters('before_admin_view_proforma_pdf', $proforma);
        $proforma_number = format_proforma_number($proforma->id);

        $type = 'D';

        if ($this->input->get('output_type')) {
            $type = $this->input->get('output_type');
        }

        if ($this->input->get('print')) {
            $type = 'I';
        }

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

        ];

        $data = [
            'proforma_number' => $proforma_number,
            'return_type' => 'pdf',
            'output' => $type,
            'company' => $company,
            'invoice' => $proforma, //json_decode(json_encode($invoice),true),
        ];
        $settings['vat_payer'] = (int)get_option('settings_company_vat_payer');
        $settings['vat_on_collection'] = (int)get_option('settings_company_vat_on_collection');
        if ($settings['vat_on_collection'] == 1) {
            $display_vat_collection = '<p>' . _l('invoice_notice_vat_on_collection') . '</p>';
            $settings['display_vat_collection'] = $display_vat_collection;
        }
        $settings['show_tax_per_item'] = (int)get_option('show_tax_per_item');

        $data['settings'] = $settings;

        $this->load->model('billing/billing_bank_model');
        $banks = $this->billing_bank_model->get_active();

        $data['banks'] = $banks;

        //$this->_template_invoice($data);

        $this->load->library('billing/crm_proforma', $proforma);
        $proforma = $this->crm_proforma->prepare_document();


        $proforma->company = $company;
        $proforma->settings = $settings;


        try {
            $pdf = proforma_pdf($proforma);
        } catch (Exception $e) {
            $message = $e->getMessage();
            echo $message;
            if (strpos($message, 'Unable to get the size of the image') !== false) {
                show_pdf_unable_to_get_image_size_error();
            }
            die;
        }

        $type = 'D';

        if ($this->input->get('output_type')) {
            $type = $this->input->get('output_type');
        }

        if ($this->input->get('print')) {
            $type = 'I';
        }

        $pdf->Output(mb_strtoupper(slug_it($proforma_number)) . '.pdf', $type);

    }

    public function _template_invoice($data)
    {
        $this->load->library('mpdf_lib');

        $defaultConfig = (new Mpdf\Config\ConfigVariables())->getDefaults();
        $fontDirs = $defaultConfig['fontDir'];

        $defaultFontConfig = (new Mpdf\Config\FontVariables())->getDefaults();
        $fontData = $defaultFontConfig['fontdata'];

        $mpdf = new MPDF\MPDF([
            'mode' => 'utf-8',
            'format' => 'A4-P',
            'default_font_size' => NULL,
            'default_font' => NULL,
            'mgl' => 0,
            'fontDir' => array_merge($fontDirs, [
                $_SERVER["DOCUMENT_ROOT"] . '/assets/invoice-design-v2/fonts/poppins',
            ]),
            'fontdata' => $fontData + [
                    'Poppins' => [
                        'R' => 'Poppins-Regular.ttf',
                        'I' => 'Poppins-Italic.ttf',
                        'B' => 'Poppins-Bold.ttf',
                    ],
                ],
        ]);

        $mpdf->SetDisplayMode('fullpage');

        //		$mpdf = new MPDF\MPDF([
        //			'mode' => 'utf-8',
        //			'format' => 'A4-P',
        //			'default_font_size' => NULL,
        //			'default_font' => NULL,
        //			'mgl' => 0,
        //		]);
        $filename = mb_strtoupper(slug_it($data['invoice_number'])) . '.pdf';
        $this->load->library('billing/crm_proforma', $data['invoice']);

        //  pre($data);
        $data['invoice'] = $this->crm_proforma->prepare_document();
        if ($data['invoice']->template == '' or $data['invoice']->template == null) {
            $html = $this->load->view('billing/templates/v2/main', $data, true);//TODO MIA
        } else {
            $html = $this->load->view('billing/templates/' . $data['invoice']->template . '/main', $data, true);
        }


        //echo '<pre>';
        //print_r($data);
        //echo '</pre>';
        //die;
        //      echo $html; die();
        $mpdf->setAutoTopMargin = 'stretch';
        $mpdf->setAutoBottomMargin = 'stretch';
        $mpdf->WriteHTML($html);

        $mpdf->Output($filename, $data['output']);
    }


    public function mark_as_sent($id)
    {
        if (!$id) {
            redirect(admin_url('proformas/list_proformas'));
        }
        if (!user_can_view_proforma($id)) {
            access_denied('Invoice Mark As Sent');
        }
        $success = $this->proformas_model->set_proforma_sent($id, true);
        if ($success) {
            set_alert('success', _l('proforma_marked_as_sent'));
        } else {
            set_alert('warning', _l('proforma_marked_as_sent_failed'));
        }
        redirect(admin_url('proformas/list_proformas/' . $id));
    }

    public function get_due_date()
    {
        if ($this->input->post()) {
            $date = $this->input->post('date');
            $duedate = '';
            if (get_option('proforma_due_after') != 0) {
                $date = to_sql_date($date);
                $d = date('Y-m-d', strtotime('+' . get_option('proforma_due_after') . ' DAY', strtotime($date)));
                $duedate = _d($d);
                echo $duedate;
            }
        }
    }

    public function invoice($id)
    {
        if (!$id) {
            redirect(admin_url('proformas/list_proformas'));
        }

        if (!user_can_view_invoice($id) && !has_permission('invoice', '', 'create')) {
            access_denied('Invoice Mark As Sent');
        }

        $invoice_id = $this->proformas_model->convert_invoice($id);
        if ($invoice_id) {
            set_alert('success', _l('proforma_copy_success'));
            redirect(admin_url('invoices/invoice/' . $invoice_id));
        } else {
            set_alert('success', _l('proforma_convert_fail'));
        }
        redirect(admin_url('proformas/proforma/' . $id));

    }

}
