<?php

/**
 * Description of Invoice
 *
 * @author Mohammad Jaherul Islam
 */
class Invoice extends TT_user_login {

    private $regExp = '/^[0-9a-zA-Z\-]+$/';
    private $numberRegExp = '/^[0-9]+$/';

    public function __construct() {
        parent::__construct();
        $this->load->model(['invoice_model', 'invoice_payment_model',
            'payment_process_model', 'admin_payment_model', 'bank_branch_model', 'bank_model']);
    }

    /**
     * @Description         : view right side information
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 17-11-2016 06:06 PM   
     * */
    function get_right_side_data($data, $payment_sub_menu) {
        $data['active_menu'] = 'dashboard';
        $data['active_sub_menu'] = 'payment';
        $data['payment_sub_menu'] = $payment_sub_menu;
        $data['left_side'] = 1;
        $data['left_side_menu_view'] = 1;
        return $data;
    }

    /*
      -----------@@@Start@ Save Course Payment----------------------------------
     */

    /**
     * @Description         : Save payment information for course
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 17-11-2016 12:14 PM  
     * @Parameter           : $course_id[Integer]=>get Course information 
     * */
    private $course_info;
    private $price_info;
    private $person_info;
    private $random_numbr;

    function save_course_payment($course_id) {
        // get payment person informaton
        $this->person_info = $this->person_model->set_person_id($this->session->person_id)
                        ->set_field_name('person_id,person_first_name,person_last_name,person_email')->set_info_by_id()->get_info();

        // get course information
        $this->course_info = $this->utility_model
                ->get_table_information('course_id,person_id,resource_person_id,course_name,course_start_date,last_date_of_registration,course_resource_person_view_invoice', 'tbl_course', ['course_id' => $course_id]);

        // get paid course price information
        $this->price_info = $this->utility_model
                ->get_table_information('price_currency,price', 'tbl_price', ['price_type' => 1, 'price_type_id' => $course_id]);

        // Save payment information
        $this->save_course_payment_information();

        // Save invoice information
        $this->save_course_invoice_information();
        // save notification information for create invoice
        $this->set_notification_data_for_create_invoice()->save_notification();

        // Save random information
        $this->tt_random_number->set_random_data(1, $this->invoice_id)->save_random_value();

        // Filter random number
        $this->random_numbr = $this->tt_random_number->filter_number('12')->get_filter_number();

        // send email for created new invoice 
        $this->set_mail_data_for_create_invoice()->send_mail();

        // redirect view invoice
        redirect('user/view-invoice/' . $this->random_numbr);
    }

    /**
     * @Description         : save course payment information
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 19-01-2016 03:54 PM   
     * */
    private $payment_id;

    function save_course_payment_information() {
        $this->payment_id = $this->payment_model
                        ->set_person_id($this->person_info->person_id)
                        ->set_type(1)
                        ->set_type_id($this->course_info->course_id)
                        ->set_currency($this->price_info->price_currency)
                        ->set_unit_price($this->price_info->price)
                        ->set_discounted_price(0)
                        ->set_total_price($this->price_info->price)
                        ->set_status(3)
                        ->save()
                        ->get_insert_id()->get_id();
        return $this;
    }

    /**
     * @Description         : save course invoice information
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 19-01-2016 03:54 PM   
     * */
    private $invoice_id;

    function save_course_invoice_information() {
        $course_description = $this->course_info->course_name . ',' . $this->course_info->course_start_date;
        $this->invoice_id = $this->invoice_model
                        ->set_payment_id($this->payment_id)
                        ->datetime()
                        ->set_description($course_description)
                        ->save()
                        ->get_insert_id()->get_id();
        return $this;
    }

    /*
      -----------@@@End@ Save Course Payment----------------------------------
     */
    /*
      -----------@@@Start@ View Single Invoice----------------------------------
     */

    /**
     * @Description         : view invoice information  
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 17-11-2016 03:37 PM   
     * */
    function view_single_invoice($temp_invoice_id) {
        // set random ID and process for random information
        $random_info = $this->random_number_model->set_temp_random_id($temp_invoice_id)->process()->get_info();

        // if does not matched random ID into database
        if (empty($random_info)) {
            redirect();
        }

        // assign data for view Invoice
        $data = $this->get_data_for_single_invoice($temp_invoice_id);

        // check paid amount data for view invoice
        $payment_data = $this->check_paid_amount_data_for_single_invoice($data);

        // get currency type if paid any payment
        $payment_data['currency_info'] = $this->invoice_payment_model->set_currency_info()->get_result();

        // mearge invoice information and payment data
        $merge_data = array_merge($data, $payment_data);
//        echo '<pre>';
//        print_r($merge_data);
//        exit();
        
        // get data for right side content
        $data_with_right_side = $this->get_right_side_data($merge_data, 'invoice');
        $data_with_right_side['main_content'] = $this->load->view('user/payment/invoice', $data_with_right_side, TRUE);
        $this->load->view('user/master', $data_with_right_side);
    }
    
    public function pay_now($temp_invoice_id){
        $random_info = $this->random_number_model->set_temp_random_id($temp_invoice_id)->process()->get_info();

        // if does not matched random ID into database
        if (empty($random_info)) {
            redirect();
        }

        // assign data for view Invoice
        $data = $this->get_data_for_single_invoice($temp_invoice_id);

        // check paid amount data for view invoice
        $payment_data = $this->check_paid_amount_data_for_single_invoice($data);

        // get currency type if paid any payment
        $payment_data['currency_info'] = $this->invoice_payment_model->set_currency_info()->get_result();

        // mearge invoice information and payment data
        $merge_data = array_merge($data, $payment_data);
        
        define("STORE_ID", "testbox");

        define("STORE_PASSWORD", "qwerty");

        define("SSLCZ_REDIRECT_URL", "https://sandbox.sslcommerz.com/gwprocess/v3/api.php");

        define("SSLCZ_VALIDATION_API", "https://sandbox.sslcommerz.com/validator/api/validationserverAPI.php");
        
    $post_data = array();

    $post_data['store_id'] = STORE_ID;

    $post_data['store_passwd'] = STORE_PASSWORD;

    $post_data['currency'] = 'BDT';

    $post_data['total_amount'] = str_replace(',', '', 3000);

    $_SESSION['SSLCZ_TRX_ID'] = $post_data['tran_id'] = "SSLCZ_TEST_" . uniqid();

    $post_data['success_url'] = "http://localhost/hysawa/?page_id=847";

    $post_data['fail_url'] = "http://localhost/hysawa/?page_id=847";

    $post_data['cancel_url'] = "http://localhost/hysawa/?page_id=847";

    # CUSTOMER INFORMATION

    $_SESSION['CUS_HISTORY']['CUS_NAME'] = $post_data['cus_name'] = 'Tania';
	$_SESSION['CUS_HISTORY']['CUS_NAME2'] = $post_data['cus_name2'] = '';

    $_SESSION['CUS_HISTORY']['CUS_EMAIL'] = $post_data['cus_email'] ='tania@talhatraining.com';

    $_SESSION['CUS_HISTORY']['CUS_ADD'] = $post_data['cus_add1'] = 'Dhaka';
	$_SESSION['CUS_HISTORY']['CUS_COUNTRY'] = $post_data['cus_country'] = 'Bangladesh';
   
    

    $handle = curl_init();

    curl_setopt($handle, CURLOPT_URL, SSLCZ_REDIRECT_URL);

    curl_setopt($handle, CURLOPT_POST, 1);

    curl_setopt($handle, CURLOPT_POSTFIELDS, $post_data);

    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);

    /* ---------- **Below two lines only for Localhost ----------- */
    curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, 0);


    $content = curl_exec($handle);

    $code = curl_getinfo($handle, CURLINFO_HTTP_CODE);


    if ($code == 200 && !( curl_errno($handle))) {

        curl_close($handle);

        $sslcommerzResponse = $content;

        # PARSE THE JSON RESPONSE 

        $sslcz = json_decode($sslcommerzResponse, true);

        if (isset($sslcz['status']) && $sslcz['status'] == 'SUCCESS') {

            if (isset($sslcz['GatewayPageURL']) && $sslcz['GatewayPageURL'] != '') {

                echo '<meta http-equiv="refresh" content="0; url=' . $sslcz['GatewayPageURL'] . '" />';

                #header("Location: " . $sslcz['GatewayPageURL']);

                exit;
            } else {

                echo "No redirect URL found!";
            }
        } else {

            echo "Invalid Credential!";
        }
    } else {

        curl_close($handle);

        echo "FAILED TO CONNECT WITH SSLCOMMERZ API";

        exit;
    }
    
    }

    /**
     * @Description         : get data for view invoice and check access validdation
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 12-12-2016 05:16 PM   
     * */
    function get_data_for_single_invoice($temp_invoice_id) {
        $data = [];
        $data['invoice_id'] = $temp_invoice_id;
        $data['invoice_number'] = "tt-$temp_invoice_id";

        // get invoice information by invoice ID
        $data['invoice_info'] = $this->utility_model
                ->get_table_information('*', 'tbl_invoice', ['invoice_id' => $this->random_number_model->get_info()->random_type_id]);

        // get payment information by payment information ID
        $data['payment_info'] = $this->payment_model->set_payment_id($data['invoice_info']->payment_id)->set_info()->get_info();

        // check acces validation for view invoice
        $this->access_validation_for_single_invoice($data);

        // get all bank information
        $data['all_bank'] = $this->admin_payment_model->get_all_bank();

        // get payment person information
        $data['person_info'] = $this->utility_model
                ->get_table_information('*', 'tbl_person', ['person_id' => $data['payment_info']->person_id]);
        // get payment invoice information
        $data['payment_invoice_info'] = $this->utility_model
                ->get_table_information('*', 'tbl_invoice_payment', ['invoice_id' => $data['invoice_info']->invoice_id]);

        // get refund payment data
        $data['refund_payment_info'] = $this->utility_model
                ->get_table_information('payment_refund_amount', 'tbl_payment_refund', ['payment_refund_id' => $data['invoice_info']->payment_id]);
        return $data;
    }

    /**
     * @Description         : check acces validation for view invoice 
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 12-12-2016 05:16 PM   
     * */
    function access_validation_for_single_invoice($data) {
        switch ($data['payment_info']->payment_type) {
            case 1: // for course
                // get course creator ID and resource person ID for check authentication
                $person_id = $this->course_model
                        ->set_course_id($data['payment_info']->payment_type_id)
                        ->get_person_id_for_course_view_invoice();
                break;

            case 2: // for Video Course
                $person_id = [0 => $this->session->person_id];
                break;
        }

        // course/video course creator/resource person access this course
        if (!in_array($this->session->person_id, $person_id)) {
            // if other user acces to this invoice then redirect home page
            if ($data['payment_info']->person_id != $this->session->person_id) {
                redirect();
            }
        }
    }

    /**
     * @Description         : check paid amount data for view invoice 
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 12-12-2016 05:56 PM   
     * */
    function check_paid_amount_data_for_single_invoice($data) {
        // get paid amount using payment ID
        $paid_amount = $this->payment_model->generate_paid_amount()->get_total_paid_amount();
        // if paid amount not equal zer0
        if (!empty($paid_amount)) {
            // get payment currency type
            $data['currency_type'] = $this->invoice_payment_model->get_currency_type();
            // generate country code
            $country_code = ($data['currency_type'] == 1) ? 'BD' : 'BB';
            // generate all payment amount
            return $this->payment_model->set_country_code($country_code)->set_currency($data['currency_type'])
                            ->generate_invoice_payment_amount()->get_payment_amount();
        } else {
            // get currency
            $currency = ($data['person_info']->person_country == 'BD') ? 1 : 2;
            // generate all payment amount
            return $this->payment_model->set_country_code($data['person_info']->person_country)->set_currency($currency)
                            ->generate_invoice_payment_amount()->get_payment_amount();
        }
    }

    /**
     * @Description         : get payment information for invoice update
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 19-11-2016 02:03 PM   
     * */
    function get_payment_info() {
        if (empty($this->input->is_ajax_request())) {
            redirect();
        }
        $data = [];
        $temp_invoice_id = $this->input->post('invoice_id', TRUE);
        // set random ID and process for random information
        $random_info = $this->random_number_model->set_temp_random_id($temp_invoice_id)->process()->get_info();

        //get invoice information by invoice ID
        $invoice_info = $this->utility_model
                ->get_table_information('payment_id', 'tbl_invoice', ['invoice_id' => $random_info->random_type_id]);

        // get all recepit number
        $data['receipt_number'] = $this->payment_process_model->get_all_receipt_number();

        // get payment information by payment information ID
        $data['payment_info'] = $this->payment_model->set_payment_id($invoice_info->payment_id)->set_info()->get_info();

        // get payment person information
        $data['person_info'] = $this->utility_model
                ->get_table_information('person_country', 'tbl_person', ['person_id' => $data['payment_info']->person_id]);

        // generate paid amount using payment ID
        $this->payment_model->generate_paid_amount()->get_total_paid_amount();

        //    if user are BDT and payment currency are BDT
        if ($data['person_info']->person_country == 'BD' && $data['payment_info']->payment_currency == 1) {
            $data['BTD'] = $this->payment_model->set_currency(1)->set_payment_amount_data([])->set_payment_amount()->get_payment_amount();
            $data['USD'] = $this->payment_model->set_currency(2)->set_payment_amount_data([])->convert_bdt_to_usd()->get_payment_amount();
        }

        // if user are BDT and payment currency are USD
        if ($data['person_info']->person_country == 'BD' && $data['payment_info']->payment_currency == 2) {
            $data['BTD'] = $this->payment_model->set_currency(1)->set_payment_amount_data([])->convert_usd_to_bdt()->get_payment_amount();
            $data['USD'] = $this->payment_model->set_currency(2)->set_payment_amount_data([])->set_payment_amount()->get_payment_amount();
        }

        if ($data['person_info']->person_country != 'BD' && $data['payment_info']->payment_currency == 1) {
            $data['USD'] = $this->payment_model->set_currency(2)->set_payment_amount_data([])->convert_bdt_to_usd()->get_payment_amount();
        }

        if ($data['person_info']->person_country != 'BD' && $data['payment_info']->payment_currency == 2) {
            $data['USD'] = $this->payment_model->set_currency(2)->set_payment_amount_data([])->set_payment_amount()->get_payment_amount();
        }
        echo json_encode($data);
    }

    /*
      -----------@@@End@ View Single Invoice----------------------------------
     */


    /*
      -----------@@@Start@ saved cash payment----------------------------------
     */

    /**
     * @Description         : save cash amount
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 19-11-2016 02:37 PM   
     * */
    private $invoice_info;

    function save_cash_amount() {
        if (empty($this->input->is_ajax_request())) {
            redirect();
        }
        $temp_invoice_id = $this->input->post('invoice_id', TRUE);
        // set random ID and process for random information
        $random_info = $this->random_number_model->set_temp_random_id($temp_invoice_id)->process()->get_info();

        if ($random_info) {
            // Saved cash amount
            $this->invoice_info = $this->utility_model->get_table_information('invoice_id,payment_id,invoice_description', 'tbl_invoice', ['invoice_id' => $random_info->random_type_id]);
            $data = $this->saved_cash();
        } else {
            $data['error'] = 'invalid_invoice';
        }
        echo json_encode($data);
    }

    /**
     * @Description         : saved cash amount
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 26-11-2016 10:31 AM
     * @Parameter           : $invoice_ID[Primary Key], $temp_invoice_id[random invooice ID]   
     * */
    private $payment_method_id;
    private $payment_method_type;

    function saved_cash() {
        // Save Cheque payment Band ID and Account Number
        $this->payment_process_model->receipt_number = trim($this->input->post('receipt_number', TRUE));

        // check cash validation
        $error = $this->check_cash_amount_validation($this->invoice_info->invoice_id);

        if ($error) {
            return $this->redirect_error();
        } else {
            //save and get cash payment insert ID
            $this->payment_method_id = $this->payment_process_model
                            ->set_table_name('tbl_payment_cash')
                            ->save()
                            ->set_insert_id()->get_id();

            // Save invoice payment, set_type=>1 [for Cash Payment]
            $this->payment_method_type = 1;
            $this->save_invoice_payment_information();

            // Update invoice for new payment
            return $this->update_invoice_for_new_payment();
        }
    }

    /**
     * @Description         : check cash amount validation
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 21-11-2016 11:23 AM
     * @Parameter           : $invoice_ID   
     * */
    function check_cash_amount_validation($invoice_id) {
        $receipt_number = $this->payment_process_model->get('receipt_number');
        $all_receipt_number = explode(',', $this->payment_process_model->get_all_receipt_number());

        $error = [];

        if (!preg_match($this->regExp, $receipt_number)) {
            $error['error_receipt'] = 1;
        } else if (in_array(strtolower($receipt_number), $all_receipt_number)) {
            $error['error_receipt'] = 1;
        } else {
            $error['error_receipt'] = '';
        }

        $paid_amount = $this->input->post('paid_amount', TRUE);
        $error['error_amount'] = $this->payment_process_model->check_payment_amount($invoice_id, $paid_amount);
        return array_filter($error);
    }

    /*
      -----------@@@End@ saved cash payment----------------------------------
     */


    /*
      -----------@@@Start@ saved cheque payment----------------------------------
     */

    /**
     * @Description         : save cheque payment amount
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 21-11-2016 11:23 AM   
     * */
    function save_cheque_amount() {
        if (empty($this->input->is_ajax_request())) {
            redirect();
        }
        $temp_invoice_id = $this->input->post('invoice_id', TRUE);
        // set random ID and process for random information
        $random_info = $this->random_number_model->set_temp_random_id($temp_invoice_id)->process()->get_info();

        if ($random_info) {
            // saved cheque amount
            $this->invoice_info = $this->utility_model->get_table_information('invoice_id,payment_id,invoice_description', 'tbl_invoice', ['invoice_id' => $random_info->random_type_id]);
            $data = $this->saved_cheque_amount();
        } else {
            $data['error'] = 'invalid_invoice';
        }
        echo json_encode($data);
    }

    /**
     * @Description         : save cheque payment amount
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 26-11-2016 02:50 PM   
     * */
    function saved_cheque_amount() {
        // Save Cheque payment Band ID and Account Number
        $this->payment_process_model->bank_branch_id = $this->input->post('bank_branch_id', TRUE);
        $this->payment_process_model->account_number = $this->input->post('account_number', TRUE);

        // Ckeck cheque Amount validation
        $error = $this->check_cheque_amount_validation($this->invoice_info->invoice_id);

        if ($error) {
            return $this->redirect_error();
        } else {
            // get cash payment insert ID
            $this->payment_method_id = $this->payment_process_model
                            ->set_table_name('tbl_payment_cheque')
                            ->save()
                            ->set_insert_id()->get_id();
            //  Save invoice payment, set_type => 2 [for cheque Payment]
            $this->payment_method_type = 2;
            $this->save_invoice_payment_information();

            //  Update invoice for new payment
            return $this->update_invoice_for_new_payment();
        }
    }

    /**
     * @Description         : save cheque payment amount
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 26-11-2016 02:53 PM   
     * */
    function check_cheque_amount_validation($invoice_id) {
        $bank_branch_id = $this->payment_process_model->get('bank_branch_id');
        $account_number = $this->payment_process_model->get('account_number');

        $error['error_bank'] = (empty($bank_branch_id)) ? 1 : '';

        if (empty($account_number)) {
            $error['error_cheque'] = 1;
        } else if (!preg_match($this->regExp, $account_number)) {
            $error['error_cheque'] = 1;
        } else {
            $error['error_cheque'] = '';
        }

        $paid_amount = $this->input->post('paid_amount', TRUE);
        $error['error_amount'] = $this->payment_process_model->check_payment_amount($invoice_id, $paid_amount);

        return array_filter($error);
    }

    /*
      -----------@@@End@ saved cheque payment----------------------------------
     */

    /*
      -----------@@@Start@ saved bKash payment----------------------------------
     */

    /**
     * @Description         : save bkash amount
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 26-11-2016 04:56 PM   
     * */
    function save_bkash_amount() {
        if (empty($this->input->is_ajax_request())) {
            redirect();
        }
        $temp_invoice_id = $this->input->post('invoice_id', TRUE);
        // set random ID and process for random information
        $random_info = $this->random_number_model->set_temp_random_id($temp_invoice_id)->process()->get_info();

        if ($random_info) {
            // saved cheque amount by invoice ID
            $this->invoice_info = $this->utility_model->get_table_information('invoice_id,payment_id,invoice_description', 'tbl_invoice', ['invoice_id' => $random_info->random_type_id]);
            $data = $this->saved_bkash_amount();
        } else {
            $data['error'] = 'invalid_invoice';
        }
        echo json_encode($data);
    }

    /**
     * @Description         : save bkash amount and check validation
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 26-11-2016 04:57 PM   
     * */
    function saved_bkash_amount() {
        // Save Cheque payment Band ID and Account Number
        $this->payment_process_model->bkash_mobile_number = $this->input->post('mobile_number', TRUE);
        $this->payment_process_model->bkash_transaction_id = $this->input->post('transaction_id', TRUE);

        // Ckeck cheque Amount validation
        $error = $this->check_bkash_amount_validation($this->invoice_info->invoice_id);

        if ($error) {
            return $this->redirect_error();
        } else {
            // get bKash payment insert ID
            $this->payment_method_id = $this->payment_process_model
                            ->set_table_name('tbl_payment_bkash')
                            ->save()
                            ->set_insert_id()->get_id();

//            Save invoice payment, set_type => 3 [for bkash Payment]
            $this->payment_method_type = 3;
            $this->save_invoice_payment_information();

//            Update invoice for new payment
            return $this->update_invoice_for_new_payment();
        }
    }

    /**
     * @Description         : check bkash amount validation
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 26-11-2016 05:01 PM   
     * */
    function check_bkash_amount_validation($invoice_id) {
        $mobile_number = $this->payment_process_model->get('bkash_mobile_number');
        $transaction_id = $this->payment_process_model->get('bkash_transaction_id');


        if (empty($mobile_number)) {
            $error['error_mobile_number'] = 1;
        } else if (!preg_match($this->numberRegExp, $mobile_number)) {
            $error['error_mobile_number'] = 1;
        } else {
            $error['error_mobile_number'] = '';
        }

        if (empty($transaction_id)) {
            $error['error_transaction_id'] = 1;
        } else if (!preg_match($this->numberRegExp, $transaction_id)) {
            $error['error_transaction_id'] = 1;
        } else {
            $error['error_transaction_id'] = '';
        }

        $paid_amount = $this->input->post('paid_amount', TRUE);
        $error['error_amount'] = $this->payment_process_model->check_payment_amount($invoice_id, $paid_amount);
        return array_filter($error);
    }

    /*
      -----------@@@End@ saved bKash payment----------------------------------
     */

    /*
      -----------@@@Start@ Update payment status----------------------------------
     */

    /**
     * @Description         : save invoice payment information
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 19-01-2017 06:15 PM   
     * */
    function save_invoice_payment_information() {
        $this->invoice_payment_model
                ->set_invoice_id($this->invoice_info->invoice_id)
                ->set_type($this->payment_method_type)
                ->set_type_id($this->payment_method_id)
                ->set_currency_type($this->input->post('currency_type', TRUE))
                ->set_paid_amount(trim($this->input->post('paid_amount', TRUE)))
                ->datetime()
                ->save();
    }

    /**
     * @Description         : create new invoice for new payment
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 22-11-2016 12:16 PM   
     * */
    function update_invoice_for_new_payment() {
        $data = $session_data = [];

        // get payment information
        $payment_info = $this->utility_model->get_table_information('person_id,payment_type,payment_type_id', 'tbl_payment', ['payment_id' => $this->invoice_info->payment_id]);

        // get student information
        $this->person_info = $this->utility_model->get_table_information('person_id,person_first_name,person_last_name,person_email', 'tbl_person', ['person_id' => $payment_info->person_id]);

        // get course information
        $this->course_info = $this->utility_model->get_table_information('course_name,person_id,resource_person_id,course_resource_person_view_invoice', 'tbl_course', ['course_id' => $payment_info->payment_type_id]);

        $this->payment_model->set_payment_id($this->invoice_info->payment_id)->payment_status = 6;
        $this->payment_model->update();

        // save notification for update payment status
        $this->set_notification_data_for_invoice_payment()->save_notification();

        // sand main for update payment status
        $this->set_mail_data_for_invoice_payment()->send_mail();

        // get payment status
        $paid_amount_status = $this->payment_model->get_payment_amount_status();

        if ($paid_amount_status == 1) {
            $data['redirect_url'] = base_url() . 'user/view-invoice/' . $this->random_number_model->get_temp_random_id();
        } else {
            $this->create_new_invoice();
            $data['redirect_url'] = base_url() . 'user/view-invoice/' . $this->random_number;
        }


        // Set payment success message in session
        $session_data['sess_message'] = '<span style="color: green">Your payment has been added successfully</span>';
        set_session($session_data);
        return $data;
    }

    /**
     * @Description         : create new invoice for new payment
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 19-01-2017 06:40 PM   
     * */
    private $random_number;

    function create_new_invoice() {
        // Create new invoice
        $this->invoice_id = $this->invoice_model
                        ->set_payment_id($this->invoice_info->payment_id)
                        ->datetime()
                        ->set_description($this->invoice_info->invoice_description)
                        ->save()
                        ->get_insert_id()->get_id();

        // Save random information & Filter random number
        $this->tt_random_number->set_random_data(1, $this->invoice_id)->save_random_value();
        $this->random_number = $this->tt_random_number->filter_number('37')->get_filter_number();

        // save notification for create invoice
        $this->set_notification_data_for_create_invoice()->save_notification();
        // send email for create new invoice
        //$this->set_mail_data_for_create_invoice()->send_mail();
        return $this;
    }

    /*
      -----------@@@End@ Update payment status----------------------------------
     */

    /*
      -----------@@@Start@ Notification View status----------------------------------
     */

    /**
     * @Description         : set notification data for create invoice
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 16-01-2016 03:52 PM   
     * */
    private $notify_to;
    private $notify_by;
    private $notification_type;
    private $notification_type_id;
    private $notification_description;

    function set_notification_data_for_create_invoice() {
        $notification_description = [];
        $notification_description[1] = '<strong>' . $this->person_info->person_first_name . ' ' . $this->person_info->person_last_name . '</strong> created a paid invoice for a course <strong>' . mb_substr($this->course_info->course_name, 0, 15) . '...' . '</strong>';
        $notification_description[$this->person_info->person_id] = '<strong>You</strong> created a paid invoice for a course <strong>' . mb_substr($this->course_info->course_name, 0, 15) . '...' . '</strong>';
        if ($this->course_info->person_id != 1) {
            $notification_description[$this->course_info->person_id] = '<strong>' . $this->person_info->person_first_name . ' ' . $this->person_info->person_last_name . '</strong> created a paid invoice for a course <strong>' . mb_substr($this->course_info->course_name, 0, 15) . '...' . '</strong>';
        }

        if ($this->course_info->course_resource_person_view_invoice == 1) {
            $resource_person_info = $this->resource_person_model
                            ->set_resource_person_id($this->course_info->resource_person_id)
                            ->set_info_by_resource_person_id()->get_result();
            $notification_description[$resource_person_info->person_id] = '<strong>' . $this->person_info->person_first_name . ' ' . $this->person_info->person_last_name . '</strong> created a paid invoice for a course <strong>' . mb_substr($this->course_info->course_name, 0, 15) . '...' . '</strong>';
        }

        $this->notification_description = serialize($notification_description);
        $this->notify_by = $this->person_info->person_id;
        $this->notify_to = implode(',', array_keys($notification_description));
        $this->notification_type = 8;
        $this->notification_type_id = $this->invoice_id;
        return $this;
    }

    /**
     * @Description         : set notification data for update payment status
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 19-01-2016 05:23 PM   
     * */
    function set_notification_data_for_invoice_payment() {
        $notification_description = [];
        $notification_description[1] = '<strong>' . $this->person_info->person_first_name . ' ' . $this->person_info->person_last_name . '</strong> updated payment status for a course <strong>' . mb_substr($this->course_info->course_name, 0, 15) . '...' . '</strong>';
        $notification_description[$this->person_info->person_id] = '<strong>You</strong> updated your payment status for a course <strong>' . mb_substr($this->course_info->course_name, 0, 15) . '...' . '</strong>';

        if ($this->course_info->person_id != 1) {
            $notification_description[$this->person_info->person_id] = '<strong>' . $this->person_info->person_first_name . ' ' . $this->person_info->person_last_name . '</strong> updated payment status for your course <strong>' . mb_substr($this->course_info->course_name, 0, 15) . '...' . '</strong>';
        }

        if ($this->course_info->course_resource_person_view_invoice == 1) {
            $resource_person_info = $this->resource_person_model->set_resource_person_id($this->course_info->resource_person_id)
                            ->set_info_by_resource_person_id()->get_result();
            $notification_description[$resource_person_info->person_id] = '<strong>' . $this->person_info->person_first_name . ' ' . $this->person_info->person_last_name . '</strong> updated payment status for your course <strong>' . mb_substr($this->course_info->course_name, 0, 15) . '...' . '</strong>';
        }

        $this->notification_description = serialize($notification_description);
        $this->notify_by = $this->person_info->person_id;
        $this->notify_to = implode(',', array_keys($notification_description));
        $this->notification_type = 8;
        $this->notification_type_id = $this->invoice_info->invoice_id;
        return $this;
    }

    /**
     * @Description         : save notification
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 15-01-2016 06:40 PM   
     * */
    function save_notification() {
        // save notification information
        $this->notification_model
                ->set_notify_by($this->notify_by)
                ->set_notify_to($this->notify_to)
                ->set_notification_description($this->notification_description)
                ->set_notification_type($this->notification_type)
                ->save();

        // save notification type 
        $this->notification_model->set_insert_id()
                ->set_notification_type_info_id($this->notification_type_id)
                ->save_type_info();
        return $this;
    }

    /*
      -----------@@@End@ Notification View status----------------------------------
     */


    /*
      -----------@@@Start@ Email View status----------------------------------
     */

    /**
     * @Description         : set mail data for create invoice
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 19-01-2016 05:27 PM   
     * */
    private $mail_subject;
    private $mail_site_link;
    private $mail_to;
    private $mail_person_name;
    private $email_message;
    private $mail_view_page;

    function set_mail_data_for_create_invoice() {
        $this->mail_subject = 'New Invoice';
        $this->mail_site_link = base_url() . 'user/view-invoice/' . $this->random_numbr;
        $this->mail_to = $this->person_info->person_email;
        $this->mail_person_name = $this->person_info->person_first_name . ' ' . $this->person_info->person_last_name;
        $this->email_message = get_message('assign_course_invoice_message');
        $this->mail_view_page = 'invoice_created_view';
        return $this;
    }

    /**
     * @Description         : set mail data for update invoice
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 19-01-2016 05:25 PM   
     * */
    function set_mail_data_for_invoice_payment() {
        $this->mail_subject = 'Updated Payment Satus';
        $this->mail_site_link = base_url() . 'user/view-invoice/' . $this->random_number_model->get_temp_random_id();
        $this->mail_to = $this->person_info->person_email;
        $this->mail_person_name = $this->person_info->person_first_name . ' ' . $this->person_info->person_last_name;
        $this->email_message = get_message('updated_payment_invoice');
        $this->mail_view_page = 'invoice_created_view';
        return $this;
    }

    /**
     * @Description         : send mail to payment person
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 19-01-2016 03:51 PM   
     * */
    function send_mail() {
        $mail_data = [];
        $mail_data['name'] = 'TalhaTraining Contact';
        $mail_data['from'] = 'no-reply@talhatraining.com';
        $mail_data['subject'] = $this->mail_subject;
        $mail_data['title_message'] = 'Talha Training';
        $mail_data['site_link'] = $this->mail_site_link;
        $mail_data['to'] = $this->mail_to;
        $mail_data['person_name'] = $this->mail_person_name;
        $mail_data['message'] = $this->email_message;

        $this->mailer_model->set_mail_data($mail_data)
                ->set_mail_view_page($this->mail_view_page)
                ->send_mail();
        return $this;
    }

    /*
      -----------@@@Start@ Email View status----------------------------------
     */

    /**
     * @Description         : redirect error page
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 26-11-2016 11:24 AM   
     * */
    function redirect_error() {
        $data = [];
        $data['redirect_url'] = base_url() . 'user/view-invoice/' . $this->random_number_model->get_temp_random_id();
        $session_data['sess_message'] = '<span style="color: green">Thank you for your payment.</span>';
        set_session($session_data);
        return $data;
    }

    /*
      -----------@@@End@ update invoice status----------------------------------
     */

    /**
     * @Description         : view bank branch name by bank ID
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 29-12-2016 03:07 PM   
     * */
    function view_bank_branch_name() {
        if (empty($this->input->is_ajax_request())) {
            redirect();
        }
        $bank_id = $this->input->post('bank_id', TRUE);
        $bank_branchs = $this->bank_branch_model->set_bank_id($bank_id)
                        ->set_bank_branch_status(1)->set_branch_name_by_bank_id()->get_result();
        echo json_encode($bank_branchs);
    }

}
