<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Loan extends CI_Controller
{
    var $main_menu_name = "loan";
    var $sub_menu_name = "list_loan";
    public function __construct()
    {

        parent::__construct();
        $this->load->model('Loan_Model');
        $this->load->model('Warehouse_Model');
        $this->load->model('Bank_Model');
        $this->load->model('Common_Model');
        $this->load->model('Customer_Model');
        $this->load->model('Menu_Model');
        $this->load->model('User_Model');
        $this->load->model('System_Settings_Model');
        $this->load->model('Unit_Model');
        $this->load->model('Menu_Items_List_Model');
        $this->load->model('Route_Model');
        $this->load->model('System_Settings_Model');
        $this->load->model('Holiday_Model');
        date_default_timezone_set('asia/colombo');
        $this->load->model('Loan_Payment_Received_Model');
        $this->load->model('Report_Loan_Model');
    }
    //Sales list page load
    public function index()
    {
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = $this->sub_menu_name;
        $this->load->view('loan/index', $data);
    }

    public function fix_different_days()
    {
        $this->load->model('Loan_Model');
        $this->Loan_Model->update_different_days();

        echo "different_days column updated successfully!";
    }


    public function get_loan_details_by_id()
    {
        $loan_id = $this->input->get('loan_id');
        $this->db->select("l.*, c.full_name as cus_name, c.cus_nic, g.full_name as gar_name, r.route_name, pt.payment_term_name");
        $this->db->from("loan l");
        $this->db->join("customer c", "c.cus_id = l.cus_id", "left");
        $this->db->join("customer g", "g.cus_id = l.g_cus_id", "left");
        $this->db->join("routes r", "r.route_id = l.route_id", "left");
        $this->db->join("mstr_payment_terms pt", "pt.id = l.loan_payment_term", "left");
        $this->db->where("l.loan_id", $loan_id);
        $this->db->where("l.loan_type_status", 'Normal');
        $query = $this->db->get();
        $row = $query->row_array();

        if ($row) {
            // =========================
            // Total payments made
            // =========================
            $this->db->select_sum('pymnt_amount');
            $this->db->from('loan_payment');
            $this->db->where('loan_id', $loan_id);
            $payment_query = $this->db->get();
            $payment_row = $payment_query->row_array();

            $total_paid = !empty($payment_row['pymnt_amount']) ? $payment_row['pymnt_amount'] : 0;

            $row['total_paid']   = $total_paid;
            $row['outstanding']  = $row['loan_tot_amount'] - $total_paid;

            // =========================
            // Calculate new total amount
            // =========================
            $loan_term_amount = !empty($row['loan_term_amount']) ? $row['loan_term_amount'] : 0;
            $loan_interest    = !empty($row['loan_interest']) ? $row['loan_interest'] : 0;

            $base_amount = $row['outstanding'] + $loan_term_amount;
            $row['new_total_amount'] = $base_amount + ($base_amount * $loan_interest / 100);

            // =========================
            // Paid terms count
            // =========================
            $this->db->select('COUNT(*) as paid_terms');
            $this->db->from('loan_terms');
            $this->db->where('loan_id', $loan_id);
            $this->db->where('paymnt_id IS NOT NULL', null, false);
            $paid_terms_query = $this->db->get();
            $paid_terms_row   = $paid_terms_query->row_array();
            $row['paid_terms'] = !empty($paid_terms_row['paid_terms']) ? $paid_terms_row['paid_terms'] : 0;

            // =========================
            // Arrears terms count
            // =========================
            $today = date('Y-m-d');
            $this->db->select('COUNT(*) as arrears_terms');
            $this->db->from('loan_terms');
            $this->db->where('loan_id', $loan_id);
            $this->db->where('term_date <=', $today);
            $this->db->where('paymnt_id', 0);
            $arrears_query = $this->db->get();
            $arrears_row   = $arrears_query->row_array();
            $row['arrears_terms'] = !empty($arrears_row['arrears_terms']) ? $arrears_row['arrears_terms'] : 0;

            // =========================
            // Sum delay_charge from loan_terms
            // =========================
            $this->db->select_sum('delay_charge');
            $this->db->from('loan_terms');
            $this->db->where('loan_id', $loan_id);
            $delay_query = $this->db->get();
            $delay_row   = $delay_query->row_array();
            $row['delay_charge'] = !empty($delay_row['delay_charge']) ? $delay_row['delay_charge'] : 0.00;

            $row['reschedule_amount'] = $row['outstanding'] + $row['delay_charge'];
        }

        echo json_encode($row);
    }

    public function change_collected_status()
    {
        //echo 'test';
        $paymnt_id = $this->input->post('paymnt_id');
        $status    = $this->input->post('status');
        $type      = $this->input->post('type');
        if ($type == 'collected') {
            $col = 'pymnt_collected';
        }
        if ($type == 'deposited') {
            $col = 'pymnt_deposited';
        }
        if ($type == 'returned') {
            $col = 'pymnt_returned';
        }
        $data = array(
            $col => $status
        );
        if ($this->Loan_Model->change_collected_status($data, $paymnt_id)) {
            $st = array(
                'status' => 1,
                'validation' => 'Done!'
            );
            echo json_encode($st);
        }
    }
    public function add_payments()
    {
        $pymnt_amount                = $this->input->post('pymnt_amount');
        $loan_id                     = $this->input->post('loan_id');
        $pymnt_paying_by             = $this->input->post('pymnt_paying_by');
        $pymnt_date_time             = $this->input->post('pymnt_date_time');
        $pymnt_date_time_send        = date('Y-m-d H:i:s', strtotime($pymnt_date_time));
        $pymnt_cheque_no             = $this->input->post('pymnt_cheque_no');
        $pymnt_crdt_card_no          = $this->input->post('pymnt_crdt_card_no');
        $pymnt_crdt_card_holder_name = $this->input->post('pymnt_crdt_card_holder_name');
        $pymnt_crdt_card_month       = $this->input->post('pymnt_crdt_card_month');
        $pymnt_crdt_card_year        = $this->input->post('pymnt_crdt_card_year');
        $pymnt_crdt_card_type        = $this->input->post('pymnt_crdt_card_type');
        $pymnt_given_amount          = $this->input->post('pymnt_given_amount');
        $pymnt_balance_amount        = $this->input->post('pymnt_balance_amount');
        $pymnt_note                  = $this->input->post('pymnt_note');
        $user_id                     = $this->session->userdata('ss_user_id');
        $pymnt_added_date_time       = date("Y-m-d H:i:s");
        $pymnt_id                    = '';
        $pymnt_ref_no                = $this->Common_Model->gen_ref_number('paymnt_id', 'loan_payment', 'REF/');;
        $this->load->library('form_validation'); //form validation lib
        $this->form_validation->set_rules('pymnt_amount', 'Amount', 'required');
        if ($pymnt_paying_by == 'Credit Card') {
            $this->form_validation->set_rules('pymnt_crdt_card_type', 'Card Type', 'required');
            $this->form_validation->set_rules('pymnt_crdt_card_no', 'Credit Card No', 'required');
            $this->form_validation->set_rules('pymnt_crdt_card_holder_name', 'Holder Name', 'required');
            $this->form_validation->set_rules('pymnt_crdt_card_month', 'Month', 'required');
            $this->form_validation->set_rules('pymnt_crdt_card_year', 'Year', 'required');
        }
        if ($pymnt_paying_by == 'Cheque') {
            $this->form_validation->set_rules('pymnt_cheque_no', 'Cheque No', 'required');
        }
        $this->form_validation->set_rules('loan_id', 'System Error', 'required');
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            $data = array(
                'pymnt_amount' => $pymnt_amount,
                'pymnt_ref_no' => $pymnt_ref_no,
                'pymnt_paying_by' => $pymnt_paying_by,
                'pymnt_date_time' => $pymnt_date_time_send,
                'pymnt_note' => $pymnt_note,
                'user_id' => $user_id,
                'loan_id' => $loan_id,
                'pymnt_added_date_time' => $pymnt_added_date_time,
                'pymnt_cheque_no' => $pymnt_cheque_no,
                'pymnt_crdt_card_no' => $pymnt_crdt_card_no,
                'pymnt_crdt_card_holder_name' => $pymnt_crdt_card_holder_name,
                'pymnt_crdt_card_type' => $pymnt_crdt_card_type,
                'pymnt_crdt_card_month' => $pymnt_crdt_card_month,
                'pymnt_crdt_card_year' => $pymnt_crdt_card_year,
                //'sale_payment_type' => $sale_type,
                'pymnt_given_amount' => $pymnt_given_amount,
                'pymnt_balance_amount' => $pymnt_balance_amount
            );
            if ($this->Loan_Model->save_loan_payments($data)) {
                $st = array(
                    'status' => 1,
                    'validation' => 'Done!'
                );
                echo json_encode($st);
            } else {
                $st = array(
                    'status' => 0,
                    'validation' => 'error occurred please contact your system administrator'
                );
                echo json_encode($st);
            }
        }
    }
    //loan calendar
    public function loan_calendar()
    {
        $data['main_menu_name'] = $this->main_menu_name;
        //$data['sub_menu_name'] = 'loan_calendar';
        $warehouse_id           = $this->uri->segment('3');
        $data['loan_details']   = $this->Loan_Model->getLoan($warehouse_id);
        if ($warehouse_id == 1) {
            $data['sub_menu_name'] = 'loan_calendar_1';
        }

        if ($warehouse_id == 2) {
            $data['sub_menu_name'] = 'loan_calendar_2';
        }
        $ss_warehouse_id = $this->session->userdata('ss_warehouse_id');
        //echo $this->db->last_query();
        if ($warehouse_id) {
            $data['loan_details']      = $this->Loan_Model->getLoan($warehouse_id);
            $data['warehouse_details'] = $this->Warehouse_Model->get_warehouse_info($warehouse_id);
            $data['system_settings']   = $this->System_Settings_Model->get_system_settings_info(1);
            //check correct wharehouse
            if ($this->session->userdata('ss_group_id') == 2) {
                $this->load->view('loan_calendar', $data);
            } else if ($this->session->userdata('ss_group_id') == 3) {
                if ($ss_warehouse_id == $warehouse_id) {
                    $this->load->view('loan_calendar', $data);
                } else {
                    // no accdess
                    redirect(base_url());
                }
            }
        }
    }
    //loan calendar
    public function get_loan_details_by_id_for_loan_calendar()
    {
        $loan_id  = $this->input->post('loan_id');
        $d        = $this->Loan_Model->get_loan_details_by_id($loan_id);
        $loan_ref = $d->loan_ref;
        if ($d) {
            $detailsurl      = base_url('loan/details/') . "/" . $loan_id;
            $loan_ref        = $loan_ref;
            $menu_name       = $d->menu_name;
            $bkng_tot_amount = $d->bkng_tot_amount;
            $paid_amount     = $this->Loan_Model->get_total_paid_by_loan_id($loan_id);
            $balance         = $bkng_tot_amount - $paid_amount;
            $bkng_details    = "<div class='pull-right'><a href='" . $detailsurl . "' target='_blank'>More Details</a> <i aria-hidden='true' class='fa fa-mail-forward'></i></div>
            <table width='100%' border='0'>
            <tr><td>Loan ID</td><td>" . $loan_ref . "</td></tr>
            <tr><td>Menu Name:</td><td>$menu_name</td></tr><tr><td>Customer Name</td><td>Sanath Udayasiri</td></tr>
            <tr><td>Total Amount: </td><td>$bkng_tot_amount</td></tr>
            <tr><td>Total Paid</td><td>$paid_amount</td></tr>
            <tr><td>Balance</td><td>$balance</td></tr>
            </table><div class='input-group'><span class='input-group-btn'></span></div>";
            $e               = array(
                'status' => 1,
                'loan_id' => $loan_id,
                'loan_ref' => $loan_ref,
                'bkng_details' => $bkng_details
            );
            echo json_encode($e);
        } else {
            $e = array(
                'status' => 0
            );
            echo json_encode($e);
        }
    }
    public function menu_item_suggestions($value = '')
    {
        $term          = $this->input->get('term');
        $warehouse_id  = $this->input->get('w');
        $data['items'] = $this->Loan_Model->get_menu_items_suggestions($term);
        //print_r($data['items']);
        $json          = array();
        foreach ($data['items'] as $row) {
            $item_code = $row['item_code'];
            $item_name = $row['item_name'];
            $json_itm  = array(
                'id' => $row['item_id'],
                'item_id' => $row['item_id'],
                'item_code' => $row['item_code'],
                'item_name' => $row['item_name'],
                'item_price' => $row['item_price_' . $warehouse_id],
                'value' => $row['item_name'] . " (" . $row['item_code'] . ")",
                'label' => $row['item_name'] . " (" . $row['item_code'] . ")"
            );
            array_push($json, $json_itm);
        }
        echo json_encode($json);
    }
    public function menu_extra_item_suggestions($value = '')
    {
        $term          = $this->input->get('term');
        $warehouse_id  = $this->input->get('w');
        $data['items'] = $this->Loan_Model->get_menu_extra_items_suggestions($term);
        //print_r($data['items']);
        $json          = array();
        foreach ($data['items'] as $row) {
            //get unit code by id
            $unit_dtls  = $this->Unit_Model->get_unit_info($row['item_unit']);
            $unit_code  = $unit_dtls['unit_code'];
            $item_code  = $row['item_code'];
            $item_name  = $row['item_name'];
            $item_price = $row['item_price_' . $warehouse_id];
            $json_itm   = array(
                'id' => $row['item_id'],
                'item_id' => $row['item_id'],
                'item_id' => $row['item_id'],
                'item_code' => $row['item_code'],
                'item_name' => $row['item_name'],
                'item_price' => $row['item_price_' . $warehouse_id],
                'unit_code' => $unit_code,
                'value' => $row['item_code'] . " " . $row['item_code'] . "",
                'label' => $row['item_name'] . " (" . $row['item_name'] . ")"
            );
            array_push($json, $json_itm);
        }
        echo json_encode($json);
    }

    public function print_loan_invoice()
    {
        $this->load->model('Loan_Payment_Received_Model');
        $this->load->model('Loan_Panalty_Process_Model');
        $this->load->model('Loan_Due_Process_Model');
        $data['main_menu_name']     = $this->main_menu_name;
        $data['sub_menu_name']      = '';
        //get sale id
        $loan_id                    = $this->uri->segment('3');
        //$data['sale_item_list']= $this->Sales_Model->get_sale_item_list_by_sale_id($sale_id);
        //$data['loan_item_list']=array();
        $data['loan_details']       = $this->Loan_Model->get_loan_info_id($loan_id);
        $data['customer_details'] = $this->Customer_Model->get_business_info($data['loan_details']->cus_id);
        //echo '<pre>',print_r($data['loan_details']); die();
        $data['loan_panalty']       = $this->Loan_Panalty_Process_Model->get_loan_penalty_by_loan_id($loan_id);
        $data['loan_due']           = $this->Loan_Due_Process_Model->get_loan_due_by_loan_id($loan_id);
        $data['total_paid_amount']  = $this->Loan_Model->get_total_paid_by_loan_id($loan_id);
        $data['warehouse_details']  = $this->Warehouse_Model->get_warehouse_info($data['loan_details']->warehouse_id);
        //$data['loan_selected_menu_list'] = $this->Loan_Model->get_loan_selected_all_menu_items($data['loan_details']->loan_id);        
        //$data['loan_selected_extra_item_list'] = $this->Loan_Model->get_loan_selected_all_menu_items($data['loan_details']->loan_id,'','extra_item');    
        $data['loan_payment_list']  = $this->Loan_Model->get_loan_payments_by_loan_id($loan_id);
        $data['loan_id']            = $loan_id;
        $paid                       = $this->Loan_Payment_Received_Model->get_loan_paid_total_by_loan_id($loan_id);
        $total_paid_amount          = $this->Loan_Model->get_total_paid_by_loan_id($loan_id);
        $total_panalty              = $this->Loan_Payment_Received_Model->get_total_panalty_by_loan_id($loan_id);
        $total_due                  = $this->Loan_Payment_Received_Model->get_total_due_by_loan_id($loan_id);
        $total_paid_panalty         = $this->Loan_Payment_Received_Model->get_total_paid_panalty_by_loan_id($loan_id);
        $total_paid_due             = $this->Loan_Payment_Received_Model->get_total_paid_due_by_loan_id($loan_id);
        $total_paid_loan            = $this->Loan_Payment_Received_Model->get_total_paid_loan_by_loan_id($loan_id);
        $data['total_panalty']      = $total_panalty['panalty_amount'];
        $data['total_due']          = $total_due['due_amount'];
        $data['total_paid_panalty'] = $total_paid_panalty['panalty_received'];
        $data['total_paid_due']     = $total_paid_due['due_received'];
        $data['total_paid_loan']    = $total_paid_loan['loan_received'];
        $this->load->view('models/print_loan_invoice', $data);
    }
    //Sales details view 
    public function loan_details()
    {
        $this->load->model('Loan_Payment_Received_Model');
        $this->load->model('Loan_Panalty_Process_Model');
        $this->load->model('Loan_Due_Process_Model');
        $data['main_menu_name']     = "";
        $data['sub_menu_name']      = '';
        //get sale id
        $loan_id                    = $this->uri->segment('3');
        $data['loan_id']            = $loan_id;
        $data['loan_details']       = $this->Loan_Model->get_loan_details_by_id($loan_id);
        $data['loan_panalty']       = $this->Loan_Panalty_Process_Model->get_loan_penalty_by_loan_id($loan_id);
        $data['loan_due']           = $this->Loan_Due_Process_Model->get_loan_due_by_loan_id($loan_id);
        $data['total_paid_amount']  = $this->Loan_Model->get_total_paid_by_loan_id($loan_id);

        $data['customer_details']   = $this->Customer_Model->get_customer_info($data['loan_details']->cus_id);
        $data['spouse_info']   = $this->Customer_Model->get_spouse_info($data['loan_details']->cus_id);
        $data['guarantor_info']   = $this->Customer_Model->get_customer_guarantor_info($data['loan_details']->cus_id);
        //echo '<pre>',print_r($data['customer_details']); die();
        $data['warehouse_details']  = $this->Warehouse_Model->get_warehouse_info($data['loan_details']->warehouse_id);
        $data['loan_payment_list']  = $this->Loan_Model->get_loan_payments_by_loan_id($loan_id);
        $data['paid_summary']            = $this->Loan_Model->loan_payment_summary_by_loan_id($loan_id);
        $total_panalty             = $this->Loan_Payment_Received_Model->get_total_panalty_by_loan_id($loan_id);
        $total_due         = $this->Loan_Payment_Received_Model->get_total_due_by_loan_id($loan_id);
        $data['total_due'] = $total_due['due_amount'];
        $data['total_panalty'] = $total_panalty['panalty_amount'];

        $loan_start_date = $data['loan_details']->loan_date;
        $loan_close_date = $data['loan_details']->loan_close_date;


        $data['holiday_list'] = $this->Holiday_Model->get_holiday_between_loan_start_date_and_end_date($loan_start_date, $loan_close_date);
        $data['holiday_count'] = $this->Holiday_Model->get_holiday_count_between_loan_start_date_and_end_date($loan_start_date, $loan_close_date);
        if ($data['holiday_count']) {
            $total_holidays = $data['holiday_count'];
        } else {
            $total_holidays = 0;
        }
        $total_no_of_term = $data['loan_details']->loan_no_of_terms;
        $loan_total_days = $total_no_of_term + $total_holidays - 1;
        $data['extented_closing_date'] = date('Y-m-d', strtotime($loan_start_date . ' + ' . $loan_total_days . ' days'));
        $date1 = date_create($loan_close_date);
        $date2 = date_create($data['extented_closing_date']);

        $diff  = date_diff($date1, $date2);
        $exd_days  = $diff->format("%a");

        $data['addition_holi_date'] = $exd_days;
        $data['include_holi_date'] = $total_holidays - $exd_days;
        //---------------------------------------------------------------
        $payment_term = $data['loan_details']->loan_payment_term;
        $oustanding_value = 0;
        $should_be_received_value = 0;
        $total_paid_amount = 0;
        $a = 0;
        $total_paid_amount = $this->Loan_Model->get_total_paid_by_loan_id($loan_id);
        $total_panalty = $this->Loan_Payment_Received_Model->get_total_panalty_by_loan_id($loan_id);
        $total_due = $this->Loan_Payment_Received_Model->get_total_due_by_loan_id($loan_id);
        $total_paid_panalty = $this->Loan_Payment_Received_Model->get_total_paid_panalty_by_loan_id($loan_id);
        $total_paid_due = $this->Loan_Payment_Received_Model->get_total_paid_due_by_loan_id($loan_id);
        $total_paid_loan = $this->Loan_Payment_Received_Model->get_total_paid_loan_by_loan_id($loan_id);
        $last_paid = $this->Loan_Payment_Received_Model->get_last_paid_loan_by_loan_id($loan_id);
        $today = date('Y-m-d');
        //calcilation start ------------------------------------------------------------------
        $data2 = array(
            'loan_id' => $loan_id,
            'payment_term' => $payment_term,
            'total_paid_amount' => $total_paid_amount,
            'total_panalty' => $total_panalty,
            'total_due' => $total_due,
            'total_paid_panalty' => $total_paid_panalty,
            'total_paid_due' => $total_paid_due,
            'total_paid_loan' => $total_paid_loan,
            'users' => $data['loan_details']
        );
        // $oustanding_value = common_outstanding_calculation($data2);
        $oustanding_value = 0;

        if ($data['loan_details']->is_closed == 1) {
            //----------------------------------

            if ($total_panalty['panalty_amount'] > 0) {
                $panalty_charge = $total_panalty['panalty_amount'];
            } else {
                $panalty_charge = 0;
            }
            if ($total_due['due_amount'] > 0) {
                $due_charge = $total_due['due_amount'];
            } else {
                $due_charge = 0;
            }
            if ($total_paid_panalty['panalty_received'] > 0) {
                $paid_panalty_charge = $total_paid_panalty['panalty_received'];
            } else {
                $paid_panalty_charge = 0;
            }
            if ($total_paid_due['due_received'] > 0) {
                $paid_due_charge = $total_paid_due['due_received'];
            } else {
                $paid_due_charge = 0;
            }
            if ($total_paid_loan['loan_received'] > 0) {
                $paid_loan_only = $total_paid_loan['loan_received'];
            } else {
                $paid_loan_only = 0;
            }
            if (isset($last_paid['pymnt_amount'])) {
                $last_paid = $last_paid['pymnt_amount'];
            } else {
                $last_paid = 0;
            }
            $panalty_charge_total = 0;
            $panalty_charge_total = $panalty_charge;
            $due_balance = $due_charge - $paid_due_charge;
            $panlty_balance = $panalty_charge_total - $paid_panalty_charge;

            $tot_l_amount = $data['loan_details']->loan_payable_total_amount;

            $tot_p_amount = $tot_l_amount - $paid_loan_only;
            //------------------------------------	
            $oustanding_value = $tot_p_amount + $due_balance + $panlty_balance;
        }


        $data['arreas_amount'] = $oustanding_value;

        $data['loan_documents'] = $this->Loan_Model->get_documents_by_loan($loan_id);
        $data['loan_terms'] = $this->Loan_Model->get_loan_terms_by_loan_id($loan_id);
        $data['documents']      = $this->Customer_Model->get_documents($data['loan_details']->cus_id);
        //---------------------------------------------------------------
        $this->load->view('loan/loan_details', $data);
    }


    public function get_cheque_details_row()
    {
        $last_bank_id           = $this->input->post('last_bank_id');
        $last_pymnt_cheque_date = $this->input->post('last_pymnt_cheque_date');
        $loan_payment_term      = $this->input->post('loan_payment_term');
        $rowCount_e             = $this->input->post('rowCount_e');
        $row_details            = '';
        $bank_list              = $this->Bank_Model->get_all_bank();
        $selbox                 = '';
        $tmp_th_e               = $rowCount_e;
        $pymnt_cheque_date      = '';
        if ($last_pymnt_cheque_date) {
            $plus_data         = "+$loan_payment_term day";
            $pymnt_cheque_date = date('d-m-Y', strtotime($last_pymnt_cheque_date . $plus_data));
        }
        //validate
        $this->load->library('form_validation');
        //$this->form_validation->set_rules('bank_id_'.$tmp_th_e, 'Bank', 'required');
        //if ($this->form_validation->run() != FALSE)
        {
            $selbox .= "<select id=\"bank_id_$tmp_th_e\" class=\"form-control\" name=\"row_e[$tmp_th_e][bank_id][]\" onChange=\"$('#last_bank_id').val(this.value)\">
                  <option value=\"\">-- Select Bank --</option>";
            foreach ($bank_list as $row2) {
                $sel = '';
                if ($last_bank_id == $row2['bank_id']) {
                    $sel       = ' selected="selected"';
                    $bank_id   = $row2['bank_id'];
                    $bank_code = $row2['bank_code'];
                    $bank_name = $row2['bank_name'];
                } else {
                    $sel       = '';
                    $bank_id   = $row2['bank_id'];
                    $bank_code = $row2['bank_code'];
                    $bank_name = $row2['bank_name'];
                }
                $selbox .= "<option$sel value=\"$bank_id\">$bank_code / $bank_name</option>";
            }
            $selbox .= '</select>';
            $paing_by_sel_box = "<select id=\"pymnt_paying_by_$tmp_th_e\" class=\"form-control\" name=\"row_e[$tmp_th_e][pymnt_paying_by][]\" onChange=\"changePayingbyLoan(this.value,$tmp_th_e)\">";
            $paing_by_sel_box .= "<option value=\"Cheque\">Cheque</option>";
            $paing_by_sel_box .= "<option value=\"Cash\">Cash</option>";
            $paing_by_sel_box .= '</select>';
            $row_details = "
            <tr id=\"row_e_$tmp_th_e\"><td class=\"text-right\">$tmp_th_e</td><td>$paing_by_sel_box</td><td>$selbox</td>
            <td><input type=\"text\" style=\"text-align:left\" name=\"row_e[$tmp_th_e][pymnt_branch][]\" id=\"pymnt_branch_$tmp_th_e\" value=\"\" class=\"form-control\"></td>
            <td><input type=\"text\" style=\"text-align:left\" name=\"row_e[$tmp_th_e][pymnt_cheque_no][]\" id=\"pymnt_cheque_no_$tmp_th_e\" value=\"\" class=\"form-control\"></td>
            <td><input type=\"text\" style=\"text-align:left; text-align:center; \" name=\"row_e[$tmp_th_e][pymnt_cheque_date][]\" id=\"pymnt_cheque_date_$tmp_th_e\" value=\"$pymnt_cheque_date\" data-date-format=\"dd-mm-yyyy\" data-date-viewmode=\"years\" class=\"form-control date-picker\"></td>
            <td align=\"right\"><input type=\"text\"  text-align:right\" name=\"row_e[$tmp_th_e][pymnt_amount][]\" id=\"pymnt_amount_$tmp_th_e\" value=\"\" class=\"pymnt_amount\"
            style=\"width:100%;   text-align:right; height:100%;\">           
            </td>
            <td><a onclick=\"deleteExtraItem($tmp_th_e)\"><i class=\"fa fa-times tip podel\" id=\"1446800197032\" title=\"Remove\" style=\"cursor:pointer;\"></i></a></td>
            </tr>
            ";
            /*
            <input type=\"text\" value=\"0\" name=\"row_e[$tmp_th_e][pymnt_collected][]\">
            <input type=\"text\" value=\"0\" name=\"row_e[$tmp_th_e][pymnt_deposited][]\">
            <input type=\"text\" value=\"0\" name=\"row_e[$tmp_th_e][pymnt_returned][]\">
            */
            $e           = array(
                'status' => 1,
                'row_details' => $row_details
            );
            echo json_encode($e);
        }
        //  else
        {
            //  $st = array('status' =>0,'validation' => validation_errors());
            // echo json_encode($st);
        }
    }

    public function loan_payments()
    {
        $data['loan_id'] = $this->uri->segment('3');
        $this->load->view('models/loan_payment', $data);
    }
    public function get_all_interest_by_payment_term_id()
    {
        $term_id       = $this->input->get('R');
        $customer_list = $this->Loan_Model->get_loan_payments_interest_by_p_term_id($term_id);
        echo json_encode($customer_list);
    }



    public function reschedule()
    {
        $data['main_menu_name']        = $this->main_menu_name;
        $data['sub_menu_name']         = 'add_loan';
        $loan_id                       = $this->uri->segment('3');
        //$data['customer_list']         = $this->Customer_Model->get_all_customer();
        $data['payment_term_list']     = $this->Loan_Model->get_loan_payments_term();
        $data['routes_list']           = $this->Route_Model->get_all_active_routes();
        $data['loan_details'] = $this->Report_Loan_Model->get_all_loans();
        $data['type']                  = 'add';
        $this->load->view('loan/reschedule', $data);
    }
    //Add Loan
    public function loan_add()
    {
        $data['main_menu_name']        = $this->main_menu_name;
        $data['sub_menu_name']         = 'add_loan';
        $loan_id                       = $this->uri->segment('3');
        //$data['customer_list']         = $this->Customer_Model->get_all_customer();
        $data['payment_term_list']     = $this->Loan_Model->get_loan_payments_term();
        $data['routes_list']           = $this->Route_Model->get_all_active_routes();
        $data['marketing_officer_list']           = $this->User_Model->getFilterUsers(5);
        $this->load->model('Bank_model');
        $data['banks'] = $this->Bank_model->get_banks();
        $data['type']                  = 'add';
        $this->load->view('loan/loan_add', $data);
    }
    
    /* AJAX: get branches */
    public function get_branches_by_bank()
    {
        $bank_id = $this->input->post('bank_id');

        if (!$bank_id) {
            echo json_encode([]);
            return;
        }
        $this->load->model('Bank_model');
        $branches = $this->Bank_model->get_branches_by_bank($bank_id);

        echo json_encode($branches);
    }

    public function loan_modify()
    {
        $data['main_menu_name']        = $this->main_menu_name;
        $data['sub_menu_name']         = 'add_loan';
        $loan_id                       = $this->uri->segment('3');
        //$data['warehouse_list']        = $this->Warehouse_Model->get_all_warehouse();
        //$data['bank_list']             = $this->Bank_Model->get_all_bank();
        $data['customer_list']         = $this->Customer_Model->get_all_customers();
        //$data['menu_list']             = $this->Menu_Model->get_all_menu();
        //$data['loan_payment_list']     = $this->Loan_Model->get_loan_payments_by_loan_id($loan_id);
        $data['payment_term_list']     = $this->Loan_Model->get_loan_payments_term();
        //$data['payment_interest_list'] = $this->Loan_Model->get_loan_payments_interest();
        //$data['payment_duration_list'] = $this->Loan_Model->get_loan_payments_duration();
        $data['routes_list']           = $this->Route_Model->get_all_active_routes();
        //$data['loan_id']               = $loan_id;
        $data['type']                  = 'update';
        $data['loan_id']               = $this->uri->segment('3');
        if ($data['loan_id']) {
            $data['hdr_data'] = $this->Loan_Model->get_loan_details_by_id($data['loan_id']);

            $loan_editable    = false;
            if (!$loan_editable) {
                //get customer details
                $data['sel_customer_details'] = $this->Customer_Model->get_customer_info($data['hdr_data']->cus_id);
                // ✅ Get already uploaded documents

            } else {
                //no acsess
                redirect(base_url('dashboard'));
            }
        }
        $this->load->view('loan_modify', $data);
    }

    public function loan_guaranteed()
    {
        $data['main_menu_name']        = $this->main_menu_name;
        $data['sub_menu_name']         = 'add_loan';
        $loan_id                       = $this->uri->segment('3');
        $data['customer_list']         = $this->Customer_Model->get_all_customers();
        $data['payment_term_list']     = $this->Loan_Model->get_loan_payments_term();
        $data['routes_list']           = $this->Route_Model->get_all_active_routes();
        $data['type']                  = 'update';
        $data['loan_id']               = $this->uri->segment('3');
        if ($data['loan_id']) {
            $data['hdr_data'] = $this->Loan_Model->get_loan_details_by_id($data['loan_id']);
            $data['loan_documents'] = $this->Loan_Model->get_documents_by_loan($loan_id);
            //echo '<pre>',print_r($data['loan_documents']); die();
            $loan_editable    = false;
            if (!$loan_editable) {
                //get customer details
                $data['sel_customer_details'] = $this->Customer_Model->get_customer_info($data['hdr_data']->cus_id);
            } else {
                //no acsess
                redirect(base_url('dashboard'));
            }
        }


        $this->load->view('loan/loan_guaranteed', $data);
    }


    public function loan_menu_item_save()
    {
        $disMsg      = '';
        $error       = '';
        //print_r($this->input->post());
        //insert sale item data
        $row         = $this->input->post('row_sr');
        $rowCount_sr = $this->input->post('rowCount_sr');
        $menu_id     = $this->input->post('menu_id');
        $loan_id     = $this->input->post('loan_id');
        $data_item   = array();
        //delete old items
        //$this->Loan_Model->delete_loan_assign_item($loan_id);
        //echo $this->db->last_query();
        for ($i = 1; $i <= $rowCount_sr; $i++) {
            //    echo "/ $rowCount , Test:".$row[$i]['product_id'][0];
            if (isset($row[$i]['item_id'][0])) {
                $data_item = array(
                    'item_id' => $row[$i]['item_id'][0],
                    'loan_id' => $loan_id,
                    'bkng_itm_price' => $row[$i]['price'][0],
                    'bkng_itm_type' => $row[$i]['itm_type'][0],
                    'bkng_itm_added_date' => date("Y-m-d H:i:s"),
                    'user_id' => $this->session->userdata('ss_user_id')
                );
                //add items
                $this->Loan_Model->save_menu_assign_item($data_item);
                //echo $this->db->last_query();
            }
            //save loan payment dtls
            $this->add_loan_dtls();
        }
        echo json_encode(array(
            'error' => $error,
            'disMsg' => $disMsg
        ));
    }
    public function loan_extra_item_save()
    {
        $disMsg     = '';
        $error      = '';
        //print_r($this->input->post('row_e'));
        //insert sale item data
        $row        = $this->input->post('row_e');
        $rowCount_e = $this->input->post('rowCount_e');
        //$menu_id=$this->input->post('menu_id');
        $loan_id    = $this->input->post('loan_id');
        $data_item  = array();
        $this->load->library('form_validation'); //form validation lib    
        /* start validation */
        $error     = false;
        $error_msg = '';
        for ($i = 1; $i <= $rowCount_e; $i++) {
            //echo "/ $rowCount_e , Test:".$row[$i]['bank_id'][0];
            if (isset($row[$i]['pymnt_paying_by'][0])) {
                //echo "<br/>Branch:".$row[$i]['pymnt_branch'][0];
                if ($row[$i]['pymnt_paying_by'][0] == 'Cheque') {
                    if ($row[$i]['bank_id'][0] == '') {
                        $error_msg .= "<p>The Bank Row $i field is required</p>";
                        $error = true;
                    }
                    if ($row[$i]['pymnt_branch'][0] == '') {
                        $error_msg .= "<p>The Bank Branch Row $i field is required</p>";
                        $error = true;
                    }
                    if ($row[$i]['pymnt_cheque_no'][0] == '') {
                        $error_msg .= "<p>The Cheque No Row $i field is required</p>";
                        $error = true;
                    }
                }
                if ($row[$i]['pymnt_cheque_date'][0] == '') {
                    $error_msg .= "<p>The Date Row $i field is required</p>";
                    $error = true;
                }
                if ($row[$i]['pymnt_amount'][0] == '') {
                    $error_msg .= "<p>The Amount Row $i field is required</p>";
                    $error = true;
                }
            }
        }
        /* end validation */
        if ($error) {
            echo json_encode(array(
                'error' => 1,
                'disMsg' => $error_msg
            ));
        } else {
            //delete old items
            $this->Loan_Model->delete_loan_assign_item($loan_id, 'extra_item');
            //echo $this->db->last_query();
            for ($i = 1; $i <= $rowCount_e; $i++) {
                //echo "/ $rowCount_e , Test:".$row[$i]['bank_id'][0];
                if (isset($row[$i]['pymnt_branch'][0])) {
                    //echo "<br/>pymnt_branch:".$row[$i]['pymnt_branch'][0];
                }
                if (isset($row[$i]['pymnt_paying_by'][0])) {
                    $pymnt_collected = 0;
                    if (isset($row[$i]['pymnt_collected'][0]))
                        $pymnt_collected = $row[$i]['pymnt_collected'][0];
                    $pymnt_deposited = 0;
                    if (isset($row[$i]['pymnt_deposited'][0]))
                        $pymnt_deposited = $row[$i]['pymnt_deposited'][0];
                    $pymnt_returned = 0;
                    if (isset($row[$i]['pymnt_returned'][0]))
                        $pymnt_returned = $row[$i]['pymnt_returned'][0];
                    $bank_id = 0;
                    if (isset($row[$i]['bank_id'][0]))
                        $bank_id = $row[$i]['bank_id'][0];
                    $pymnt_cheque_no = 0;
                    if (isset($row[$i]['pymnt_cheque_no'][0]))
                        $pymnt_cheque_no = $row[$i]['pymnt_cheque_no'][0];
                    $pymnt_branch = 0;
                    if (isset($row[$i]['pymnt_branch'][0]))
                        $pymnt_branch = $row[$i]['pymnt_branch'][0];
                    $details_confirm        = $this->Loan_Model->get_loan_details_by_loan_id($loan_id);
                    $currant_amount_balance = $row[$i]['pymnt_amount'][0];
                    //start:calculate currant recived capital and interest received %
                    $tot_loan_amount        = $details_confirm['loan_payable_total_amount'];
                    $tot_capital            = $details_confirm['loan_tot_amount'];
                    $tot_interest           = $details_confirm['total_interest'];
                    $capital_presentage     = ($tot_capital / $tot_loan_amount) * 100;
                    $interest_presentage    = ($tot_interest / $tot_loan_amount) * 100;
                    //end:calculate currant recived capital and interest received %            
                    $tot_loan_payment       = 0;
                    if ($currant_amount_balance > 0) {
                        $total_loan_payment    = $currant_amount_balance;
                        //start : cal capital and interest payment amount
                        $tot_loan_payment      = $total_loan_payment;
                        $loan_capital_payment  = round(($total_loan_payment / 100) * $capital_presentage, 2);
                        $loan_interest_payment = round(($total_loan_payment / 100) * $interest_presentage, 2);
                        //end : cal capital and interest payment amount            
                    }
                    $data_item = array(
                        //'item_id'=>$row[$i]['item_id'][0],
                        'loan_id' => $loan_id,
                        'bank_id' => $bank_id,
                        'pymnt_branch' => $pymnt_branch,
                        'pymnt_paying_by' => $row[$i]['pymnt_paying_by'][0],
                        'pymnt_cheque_no' => $pymnt_cheque_no,
                        'pymnt_cheque_date' => date('Y-m-d', strtotime($row[$i]['pymnt_cheque_date'][0])),
                        'pymnt_amount' => $row[$i]['pymnt_amount'][0],
                        'pymnt_ref_no' => $this->Common_Model->gen_ref_number('paymnt_id', 'loan_payment', 'RCPT/'),
                        'pymnt_added_date_time' => date("Y-m-d H:i:s"),
                        'user_id' => $this->session->userdata('ss_user_id'),
                        'pymnt_collected' => 1,
                        'pymnt_deposited' => $pymnt_deposited,
                        'pymnt_returned' => $pymnt_returned,
                        'cus_id' => $details_confirm['cus_id'],
                        'warehouse_id' => $details_confirm['warehouse_id'],
                        'route_id' => $details_confirm['route_id'],
                        'loan_received' => $tot_loan_payment,
                        'capital_received' => $loan_capital_payment,
                        'loan_interest_recived' => $loan_interest_payment,
                        'is_initial_cheque' => 1,
                        'payment_term' => $details_confirm['loan_payment_term']
                        //'pymnt_deposited'=>intval($row[$i]['pymnt_deposited'][0]),
                        //'pymnt_collected'=>intval($row[$i]['pymnt_collected'][0])
                    );
                    //add items
                    $result    = $this->Loan_Model->save_menu_assign_item($data_item);
                    //echo $this->db->last_query();
                }
            }
            if ($result = 1) {
                $error = 0;
                echo json_encode(array(
                    'error' => $error,
                    'disMsg' => ''
                ));
            } else {
                $error = 1;
                echo json_encode(array(
                    'error' => $error,
                    'disMsg' => 'Save Fail'
                ));
            }
        }
    }
    public function add_loan_dtls()
    {
        $error                                     = false;
        $loan_id                                   = $this->input->post('loan_id');
        $bkng_discount                             = $this->input->post('bkng_discount');
        $bkng_discount_value                       = $this->input->post('bkng_discount_value');
        $bkng_per_head_discount                    = $this->input->post('bkng_per_head_discount');
        $bkng_per_head_discount_value              = $this->input->post('bkng_per_head_discount_value');
        $bkng_tot_amount                           = $this->input->post('bkng_tot_amount');
        $bkng_menu_amount                          = $this->input->post('bkng_menu_amount');
        $bkng_extra_menu_item_amount               = $this->input->post('bkng_extra_menu_item_amount');
        $bkng_extra_item_amount                    = $this->input->post('bkng_extra_item_amount');
        $bkng_note                                 = $this->input->post('bkng_note');
        $bkng_flora_bill_no                        = $this->input->post('bkng_flora_bill_no');
        $bkng_type                                 = $this->input->post('bkng_type');
        $data_item                                 = array();
        $data_item['bkng_discount_value']          = $bkng_discount_value;
        $data_item['bkng_discount']                = $bkng_discount; //added discount
        $data_item['bkng_per_head_discount']       = $bkng_per_head_discount; // added per head discount
        $data_item['bkng_per_head_discount_value'] = $bkng_per_head_discount_value;
        $data_item['bkng_tot_amount']              = $bkng_tot_amount;
        $data_item['bkng_note']                    = $bkng_note;
        $data_item['bkng_type']                    = $bkng_type;
        $data_item['bkng_flora_bill_no']           = $bkng_flora_bill_no;
        $this->Loan_Model->save_loan_header($data_item, $loan_id);
    }
    public function loan_complete()
    {
        $this->add_loan_dtls();
        $loan_id = $this->input->post('loan_id');
        $error   = false;
        if (!$error) {
            echo json_encode(array(
                'loan_id' => $loan_id,
                'error' => 0,
                'msg' => ''
            ));
        } else {
            echo json_encode(array(
                'loan_id' => $loan_id,
                'error' => 1,
                'msg' => "Please select these ($errtxt) before adding"
            ));
        }
    }
    public function update_loan_header()
    {
        //echo 'test';
        //echo 'b id:'; print_r($this->input->post());
        $loan_id            = $this->input->post('loan_id');
        $cus_id             = $this->input->post('cus_id');
        $bkng_status        = $this->input->post('bkng_status');
        $bkng_time          = $this->input->post('bkng_time');
        $menu_id            = $this->input->post('menu_id');
        $bkng_head_count    = $this->input->post('bkng_head_count');
        $bkng_date          = date('Y-m-d', strtotime($this->input->post('bkng_date')));
        $bkng_date_validate = date('Y-m-d', strtotime($this->input->post('bkng_date')));
        $warehouse_id       = $this->input->post('warehouse_id');
        $bkng_type          = $this->input->post('bkng_type');
        $error              = false;
        $errtxt             = '';
        if (!$bkng_date) {
            //echo '111111111111111';
            $error = true;
            $errtxt .= 'Loan Date';
        } else if ($this->Loan_Model->checkAvalabilityDate($loan_id, $bkng_date_validate, $warehouse_id)) {
            if ($this->Loan_Model->checkAvalabilityTime($loan_id, $bkng_date_validate, $bkng_time, $warehouse_id)) {
                $error = true;
                $errtxt .= 'Selected Date, Time not avalable';
            }
        }
        if (!$cus_id) {
            //echo '2222222222222';
            $error = true;
            if ($errtxt)
                $errtxt .= ', ';
            $errtxt .= 'Customer';
        }
        if (!$bkng_time) {
            $error = true;
            if ($errtxt)
                $errtxt .= ', ';
            $errtxt .= 'Loan Time';
        }
        if (!$menu_id) {
            $error = true;
            if ($errtxt)
                $errtxt .= ', ';
            $errtxt .= 'Menu';
        }
        if (!$bkng_head_count) {
            $error = true;
            if ($errtxt)
                $errtxt .= ', ';
            $errtxt .= 'Head Count';
        }
        if (!$bkng_status) {
            $error = true;
            if ($errtxt)
                $errtxt .= ', ';
            $errtxt .= 'Loan Status';
        }
        $error = false;
        if (!$error) {
            $data_item['loan_id']         = $loan_id;
            $data_item['cus_id']          = $cus_id;
            $data_item['bkng_status']     = $bkng_status;
            $data_item['bkng_time']       = $bkng_time;
            $data_item['bkng_date']       = $bkng_date;
            //$data_item['bkng_type']=$bkng_type;
            $data_item['menu_id']         = $menu_id;
            $data_item['bkng_head_count'] = $bkng_head_count;
            //get menu amount
            $menudetls                    = $this->Menu_Model->get_menu_info($menu_id);
            $menu_name_new                = '';
            $data_item['bkng_tot_amount'] = 0;
            /* Check menu change, if change add new menu items and delete old items */
            //get old menu id
            $oldloandetails               = '';
            $oldloandetails               = $this->Loan_Model->get_loan_details_by_id($loan_id);
            $oldloanmenuid                = $oldloandetails->menu_id;
            $loan_ref                     = $oldloandetails->loan_ref;
            //echo '<br/>old menu id:'.$oldloanmenuid;
            if ($menu_id != $oldloanmenuid) {
                $data_item['bkng_menu_amount'] = $menudetls['menu_price_' . $warehouse_id];
                $data_item['bkng_tot_amount']  = $menudetls['menu_price_' . $warehouse_id] * $bkng_head_count;
                //delete old items
                $this->Loan_Model->delete_loan_assign_item($loan_id);
                //send data to log table
                $menuolddetls  = $this->Menu_Model->get_menu_info($oldloanmenuid);
                $menu_name_old = $menuolddetls['menu_name'];
                $this->Common_Model->add_user_activitie("Loan ID: $loan_ref , Menu Changed, From: $menu_name_old To: $menu_name_new");
            }
            //check per head count change
            $oldbkng_head_count = $oldloandetails->bkng_head_count;
            if ($bkng_head_count != $oldbkng_head_count) {
                $data_item['bkng_per_head_discount']       = '0';
                $data_item['bkng_per_head_discount_value'] = '0';
                //send data to log table
                $this->Common_Model->add_user_activitie("Loan ID: $loan_ref , Head Count Changed, From: $oldbkng_head_count To: $bkng_head_count");
            }
            //check date changed
            $oldbkng_date = $oldloandetails->bkng_date;
            if ($bkng_date != $oldbkng_date) {
                //send data to log table
                $this->Common_Model->add_user_activitie("Loan ID: $loan_ref , Loan Date Changed, From: $oldbkng_date To: $bkng_date");
            }
            //check time changed
            $oldbkng_time = $oldloandetails->bkng_time;
            if ($bkng_time != $oldbkng_time) {
                $this->Common_Model->add_user_activitie("Loan ID: $loan_ref , Loan Time Changed, From: $oldbkng_time To: $bkng_time");
            }
            //check status changed
            $oldbkng_status = $oldloandetails->bkng_status;
            if ($bkng_status != $oldbkng_status) {
                //send data to log table
                $this->Common_Model->add_user_activitie("Loan ID: $loan_ref , Loan Status Changed, From: $oldbkng_status To: $bkng_status");
            }
            //check status changed
            $oldcus_id = $oldloandetails->cus_id;
            if ($cus_id != $oldcus_id) {
                //send data to log table
                $this->Common_Model->add_user_activitie("Loan ID: $loan_ref , Loan Customer Changed, From: $oldcus_id To: $cus_id");
            }
            // check manu id change, if changed delete all loan menu ids
            /* END Check menu change, if change add new menu items and delete old items */
            $this->Loan_Model->save_loan_header($data_item, $loan_id);
            if ($menu_id != $oldloanmenuid) {
                //add menu items to loan menu item table
                $selected_menu_list = $this->Menu_Model->get_selected_all_menu_items($menu_id);
                if (isset($selected_menu_list)) {
                    foreach ($selected_menu_list as $row) {
                        //insert menu items
                        $arr            = array();
                        $arr['item_id'] = $row->item_id;
                        if ($warehouse_id == 1) {
                            $arr['bkng_itm_price'] = $row->item_price_1;
                        }
                        if ($warehouse_id == 2) {
                            $arr['bkng_itm_price'] = $row->item_price_2;
                        }
                        $arr['bkng_itm_type']       = '';
                        $arr['loan_id']             = $loan_id;
                        $arr['bkng_itm_added_date'] = date("Y-m-d H:i:s");
                        $arr['user_id']             = $this->session->userdata('ss_user_id');
                        $this->Loan_Model->save_menu_assign_item($arr);
                    }
                }
            }
            //update loan summary details
            $this->add_loan_dtls();
            //END add menu items to loan menu item table
            //echo $this->db->last_query();
            //$vcl_srvs_inv_id=$this->db->insert_id();
            echo json_encode(array(
                'loan_id' => $loan_id,
                'error' => 0,
                'msg' => ''
            ));
        } else {
            echo json_encode(array(
                'loan_id' => $loan_id,
                'error' => 1,
                'msg' => "Please select these ($errtxt) before adding"
            ));
        }
    }

    public function generate_loan_ref($cus_id)
    {
        // Get customer info
        $customer = $this->Customer_Model->get_customer_info($cus_id);
        $customer_code = isset($customer['cus_code']) ? $customer['cus_code'] : 'CUST';

        // Count how many loans the customer already has
        $this->db->where('cus_id', $cus_id);
        $loan_count = $this->db->count_all_results('loan');

        // Next loan number
        $next_loan_number = $loan_count + 1;

        // Build reference: CustomerCode/LoanNumber
        $loan_ref = $customer_code . "/" . $next_loan_number;

        return $loan_ref;
    }

    public function generate_reschedule_ref($old_loan_ref)
    {
        // Example: BIL0014/1 => BIL0014/1/R/1
        // Example: BIL0014/1/R/1 => BIL0014/1/R/2
        // Example: BIL0014/1/R/2 => BIL0014/1/R/3
        
        if (strpos($old_loan_ref, '/R/') !== false) {
            // Already has reschedule part - increment the last number
            $parts = explode('/R/', $old_loan_ref);
            $base_ref = $parts[0]; // e.g., "BIL0014/1"
            $reschedule_number = (int)$parts[1]; // e.g., "1" or "2"
            $reschedule_number++; // Increment: 1 => 2, 2 => 3, etc.
            
            $new_ref = $base_ref . '/R/' . $reschedule_number;
        } else {
            // No reschedule part yet - add /R/1
            $new_ref = $old_loan_ref . '/R/1';
        }
        
        return $new_ref;
    }

    public function loan_header_save()
    {

        $system_settings = $this->System_Settings_Model->get_system_settings_info(1);

        $holiday_active = $system_settings['holiday_status'];
        $adjest_loan_close_date = $system_settings['adjest_loan_close_date_via_holiday'];

        $this->load->library('form_validation'); //form validation lib
        $this->form_validation->set_rules('cus_id', 'Customer', 'required');
        $this->form_validation->set_rules('warehouse_id', 'Warehouse', 'required');
        $this->form_validation->set_rules('loan_tot_amount', 'Total Amount', 'required|greater_than[0]');
        $this->form_validation->set_rules('loan_date', 'Loan Date', 'required');
        $this->form_validation->set_rules('loan_interest', 'Interest', 'required|greater_than[-1]|less_than[101]');
        $this->form_validation->set_rules('loan_payment_term', 'Payment Term', 'required');
        $this->form_validation->set_rules('loan_no_of_terms', 'No. of Months', 'required|greater_than[0]');
        $this->form_validation->set_rules('loan_term_amount', 'Term Amount', 'required'); //|greater_than[0]
        $this->form_validation->set_rules('route_id', 'Route', 'required');
        $this->form_validation->set_rules('route_id', 'Route', 'required');
        $this->form_validation->set_rules('panalty_presentage', 'Panalty', 'required|greater_than[0]|less_than[101]');
        $this->form_validation->set_rules('due_presentage', 'Panalty', 'required|greater_than[0]|less_than[101]');
        //insert header data
        $data_item                 = array();
        $warehouse_id              = $this->input->post('warehouse_id');
        $ref_id_nxt                = $this->Common_Model->gen_ref_number('loan_id', 'loan', '');
        $cus_id                    = $this->input->post('cus_id');
        $route_id                  = $this->input->post('route_id');
        $loan_type                  = $this->input->post('loan_type');
        $loan_tot_amount           = $this->input->post('loan_tot_amount');
        $loan_date                 = $this->input->post('loan_date');
        $loan_interest             = $this->input->post('loan_interest');
        $loan_payment_term         = $this->input->post('loan_payment_term');
        $loan_no_of_terms          = $this->input->post('loan_no_of_terms');
        $loan_no_of_days          = $this->input->post('loan_no_of_days');
        $loan_term_amount_value = $this->input->post('loan_term_amount');
        $loan_term_amount_value = str_replace(',', '', $loan_term_amount_value); // remove commas
        $loan_term_amount          = ($loan_payment_term == 4) ? 0 : str_replace(',', '', $loan_term_amount_value);
        $loan_status               = $this->input->post('loan_status');
        $loan_id                   = $this->input->post('loan_id');
        $loan_payable_total_amount = $this->input->post('loan_payable_total_amount');
        $panalty_enable            = $this->input->post('panalty_enable');
        $reduce_from_cheque        = $this->input->post('reduce_from_cheque');
        $doc_charge                = $this->input->post('doc_charge');
        $g_cus_id                  = $this->input->post('g_cus_id');
        $loan_interest_type        = $this->input->post('loan_interest_type');
        $total_interest            = $this->input->post('total_interest');
        $term_intrerest            = $this->input->post('term_intrerest');
        $loan_payment_term_qty     = $this->input->post('loan_payment_term_qty');
        $note                      = $this->input->post('note');
        $due_presentage            = $this->input->post('due_presentage');
        $panalty_presentage        = $this->input->post('panalty_presentage');
        $new_closing_date        = $this->input->post('loan_end_date');
        $marketing_officer_id        = $this->input->post('marketing_officer_id');
        $marketing_officer_discount        = $this->input->post('marketing_officer_discount');

        //get warehouse code
        $warehouse_dtls            = $this->Warehouse_Model->get_warehouse_info($warehouse_id);

        $loan_ref = $this->generate_loan_ref($cus_id);
        $error                     = false;
        $errtxt                    = '';

        if ($loan_payment_term == 1) {
            $total_days   = $loan_no_of_terms;
            //$total_days=$total_days-1;
            $Date         = $loan_date;
            //---------------------------------------------------------	
            if ($loan_type == 'Passive') {
                $closing_date = date('Y-m-d', strtotime($new_closing_date));
            } else {
                if ($holiday_active == 1 && $adjest_loan_close_date == 1) {
                    $open_date = date('Y-m-d', strtotime($loan_date));
                    $loop_date = $open_date;
                    $holiday_count = 0;
                    $days_count = $total_days;
                    for ($i = 1; $i <= $days_count; $i++) {
                        $check_holiday = $this->Holiday_Model->get_holidays_between_loan_open_close_date($loop_date);
                        if ($check_holiday > 0) {
                            $holiday_count += 1;
                            $days_count += 1;
                        }
                        $loop_date = date('Y-m-d', strtotime($loop_date . ' + 1 days'));
                    }
                    $total_days += $holiday_count;
                    $total_days = $total_days - 1;
                }
                //-----------------------------------------------------------
                $closing_date = date('Y-m-d', strtotime($Date . ' + ' . $total_days . ' days'));
            }
        }
        if ($loan_payment_term == 2) {
            $total_days   = $loan_no_of_terms * 7;
            $Date         = $loan_date;
            //---------------------------------------------------------		
            if ($loan_type == 'Passive') {
                $closing_date = date('Y-m-d', strtotime($new_closing_date));
            } else {
                if ($holiday_active == 1 && $adjest_loan_close_date == 1) {
                    $open_date = date('Y-m-d', strtotime($loan_date));
                    $loop_date = $open_date;
                    $holiday_count = 0;
                    $days_count = $total_days;
                    for ($i = 1; $i <= $days_count; $i++) {
                        $check_holiday = $this->Holiday_Model->get_holidays_between_loan_open_close_date($loop_date);
                        if ($check_holiday > 0) {
                            $holiday_count += 1;
                            $days_count += 1;
                        }
                        $loop_date = date('Y-m-d', strtotime($loop_date . ' + 1 days'));
                    }
                    echo $total_days . "--";
                    $total_days += $holiday_count;
                    $total_days = $total_days - 1;
                    echo $total_days . "--";
                }
                //-----------------------------------------------------------
                $closing_date = date('Y-m-d', strtotime($Date . ' + ' . $total_days . ' days'));
            }
        }
        if ($loan_payment_term == 3) {
            $total_days   = $loan_no_of_terms;
            $Date         = $loan_date;

            if ($loan_type == 'Passive') {
                $closing_date = date('Y-m-d', strtotime($new_closing_date));
            } else {
                $closing_date = date('Y-m-d', strtotime("+" . $loan_no_of_terms . " months", strtotime($Date)));
            }
        }
        if ($loan_payment_term == 4) {
            $total_days   = $loan_no_of_terms * $loan_payment_term_qty;
            $Date         = $loan_date;
            if ($loan_type == 'Passive') {
                $closing_date = date('Y-m-d', strtotime($new_closing_date));
            } else {
                $closing_date = date('Y-m-d', strtotime($Date . ' + ' . $total_days . ' days'));
            }
        }
        if ($this->form_validation->run() == FALSE) {
            echo json_encode(array(
                'loan_id' => '',
                'error' => 1,
                'msg' => validation_errors()
            ));
        } else {

            if ($loan_type == 'Passive') {
                $closing_date = date('Y-m-d', strtotime($new_closing_date));
            }
            $data_item['loan_ref']                  = $loan_ref;
            $data_item['warehouse_id'] = $warehouse_id;
            $data_item['cus_id']                    = $cus_id;
            $data_item['loan_tot_amount']           = $loan_tot_amount;
            $data_item['loan_date']                 = date('Y-m-d', strtotime($loan_date));
            $data_item['loan_interest']             = $loan_interest;
            $data_item['loan_payment_term']         = $loan_payment_term;
            $data_item['loan_no_of_terms']          = $loan_no_of_terms;
            $data_item['loan_term_amount']          = $loan_term_amount;
            $data_item['loan_no_of_days']          = $loan_no_of_days;
            $data_item['loan_payable_total_amount'] = $loan_payable_total_amount;
            $data_item['loan_creted_date']          = date("Y-m-d H:i:s");
            $data_item['panalty_enable']            = $panalty_enable;
            $data_item['reduce_fron_ceque']         = $reduce_from_cheque;
            $data_item['document_charges']          = $doc_charge;
            $data_item['g_cus_id']                  = $g_cus_id;
            $data_item['loan_interest_type']        = $loan_interest_type;
            $data_item['total_interest']            = $total_interest;
            $data_item['term_intrerest']            = $term_intrerest;
            $data_item['loan_payment_term_qty']     = $loan_payment_term_qty;
            $data_item['route_id']                  = $route_id;
            $data_item['note']                      = $note;
            $data_item['loan_close_date']           = $closing_date;
            $data_item['user_id']                   = $this->session->userdata('ss_user_id');
            $data_item['panalty_presentage']        = $panalty_presentage;
            $data_item['due_presentage']            = $due_presentage;
            $data_item['marketing_officer_id']            = $marketing_officer_id;
            $data_item['marketing_officer_discount']            = $marketing_officer_discount;
            //-------------------------------------------------------

            /*  if ($this->session->userdata('ss_group_id') == 1) {
                $data_item['approval_by']                 = $this->session->userdata('ss_user_id');
                $data_item['approval_date_time']        = date("Y-m-d H:i:s");
                $data_item['approval_comment']          = "Owner auto approval";
                $data_item['approval_status']           = 1;
                $data_item['loan_issue_status']            = 1;
            } */

            //-------------------------------------------------------	
            if ($loan_id) {
                $this->Loan_Model->save_loan_header($data_item, $loan_id);
            } else {
                $this->Loan_Model->save_loan_header($data_item);
                $loan_id = $this->db->insert_id();
            }

            // Delete old terms if updating
            $this->Loan_Model->delete_loan_terms($loan_id);
            if ($loan_payment_term == 4) { // CHEQUE
                $cheques = $this->input->post('cheques');

                if (!empty($cheques) && is_array($cheques)) {
                    $term_no = 1;
                    foreach ($cheques as $cheque) {
                        if (empty($cheque['cheque_date']) || empty($cheque['realize_date']) || empty($cheque['cheque_amount'])) {
                            continue; // skip invalid rows
                        }

                        $cheque_date = DateTime::createFromFormat('d/m/Y', $cheque['cheque_date']);
                        $realize_date = DateTime::createFromFormat('d/m/Y', $cheque['realize_date']);

                        // Calculate different_days

                        $different_days = null;
                        if (!empty($closing_date) && !empty($realize_date)) {
                            $diff = (strtotime($closing_date) - strtotime($realize_date)) / (60 * 60 * 24);
                            $different_days = (int)$diff;
                        }

                        $term_data = array(
                            'loan_id'        => $loan_id,
                            'term_no'        => $term_no++,
                            'term_date'      => $realize_date ? $realize_date->format('Y-m-d') : null,
                            'term_amount'    => !empty($cheque['cheque_amount']) ? $cheque['cheque_amount'] : 0,
                            'paid_amount'    => 0.00,
                            'penalty_amount' => 0.00,
                            'status'         => 'Pending',
                            'payment_date'   => null,
                            'different_days'   => $different_days,
                            'cheque_date'    => $cheque_date ? $cheque_date->format('Y-m-d') : null,
                            'realize_date'   => $realize_date ? $realize_date->format('Y-m-d') : null,
                            'bank_id'   => $cheque['bank_id'] ? $cheque['bank_id'] : null,
                            'branch_id'   => $cheque['branch_id'] ? $cheque['branch_id'] : null,
                            'days'           => !empty($cheque['days']) ? $cheque['days'] : 0,
                            'charges'        => !empty($cheque['charges']) ? $cheque['charges'] : 0.00,
                        );

                        $this->Loan_Model->save_loan_term($term_data);
                    }
                }
            } else { // DAILY, WEEKLY, MONTHLY
                $term_count  = $loan_no_of_terms;
                $term_amount = $loan_term_amount;
                $current_date = $loan_date;

                for ($i = 1; $i <= $term_count; $i++) {
                    if ($loan_payment_term == 1) { // DAILY
                        $current_date = date('Y-m-d', strtotime($current_date . " + 1 day"));
                    } elseif ($loan_payment_term == 2) { // WEEKLY
                        $current_date = date('Y-m-d', strtotime($current_date . " + 7 days"));
                    } elseif ($loan_payment_term == 3) { // MONTHLY
                        $current_date = date('Y-m-d', strtotime($current_date . " + 1 month"));
                    }

                    // Skip weekends & holidays
                    $valid_date = $this->get_next_valid_date($current_date);

                    // Calculate different_days
                    $different_days = null;
                    if (!empty($closing_date) && !empty($valid_date)) {
                        $diff = (strtotime($closing_date) - strtotime($valid_date)) / (60 * 60 * 24);
                        $different_days = (int)$diff;
                    }

                    $term_data = array(
                        'loan_id'       => $loan_id,
                        'term_no'       => $i,
                        'term_date'     => $valid_date,
                        'term_amount'   => $term_amount,
                        'paid_amount'   => 0.00,
                        'penalty_amount' => 0.00,
                        'status'        => 'Pending',
                        'payment_date'  => null,
                        'different_days' => $different_days,
                    );
                    $this->Loan_Model->save_loan_term($term_data);

                    $current_date = $valid_date; // next term calculation
                }
            }





            //echo $this->db->last_query();    
            if ($loan_payment_term == 4) {
                if ($loan_type == 'Passive') {
                    $is_cheque = 0;
                } else {
                    $is_cheque = 1;
                }
            } else {
                $is_cheque = 0;
            }
            echo json_encode(array(
                'loan_id' => $loan_id,
                'error' => 0,
                'msg' => '',
                'is_cheque_req' => $is_cheque
            ));
        }
    }


    public function loan_reschedule_save()
    {
        $loan_id            = $this->input->post('loan_id');
        $new_no_of_terms    = $this->input->post('loan_no_of_terms');
        $new_term_amount    = str_replace(',', '', $this->input->post('loan_term_amount'));
        $new_total_interest = 0;
        $new_end_date       = $this->input->post('loan_end_date');
        $new_end_date = date('Y-m-d', strtotime($new_end_date));
        $reschedule_reason  = $this->input->post('note');
        $loan_payment_term  = $this->input->post('loan_payment_term'); // daily, weekly, monthly, etc.
        $loan_tot_amount    = $this->input->post('loan_tot_amount'); // daily, weekly, monthly, etc.

        $this->db->trans_begin();

        // 1️⃣ Get old loan details
        $old_loan = $this->Loan_Model->get_loan_details_by_id($loan_id);

        // 2️⃣ Save reschedule history
        $reschedule_data = array(
            'loan_id'            => $loan_id,
            'old_no_of_terms'    => $old_loan->loan_no_of_terms,
            'old_term_amount'    => $old_loan->loan_term_amount,
            'old_total_interest' => $old_loan->total_interest,
            'old_end_date'       => $old_loan->loan_close_date,
            'old_loan_tot_amount'       => $old_loan->loan_tot_amount,
            'old_loan_payable_total_amount'       => $old_loan->loan_payable_total_amount,
            'new_no_of_terms'    => $new_no_of_terms,
            'new_term_amount'    => $new_term_amount,
            'new_total_interest' => $new_total_interest,
            'new_loan_tot_amount' => $loan_tot_amount,
            'new_end_date'       => $new_end_date,
            'reschedule_reason'  => $reschedule_reason,
            'user_id'            => $this->session->userdata('ss_user_id'),
        );
        
        $this->Loan_Model->save_reschedule($reschedule_data);

        // 3️⃣ Close unpaid old terms
        $this->db->where('loan_id', $loan_id);
        $this->db->where('status', 'Pending');
        $this->db->update('loan_terms', array('status' => 'Closed'));

        // 5️⃣ Create NEW loan with reference number
        $new_loan_ref = $this->generate_reschedule_ref($old_loan->loan_ref);

        // 4️⃣ Update old loan header - only update status and date
        $loan_update_old = array(
            'loan_type_status'  => 'Rescheduled',
            'loan_creted_date'  => date("Y-m-d H:i:s"),
            'is_closed'  => 1,
            'close_by'  => $this->session->userdata('ss_user_id'),
            'close_reason'  => 'Rescheduled on ' .date('Y-m-d H:is:'). ' New loan ref '.$new_loan_ref,

        );
        $this->Loan_Model->save_loan_header($loan_update_old, $loan_id);

        
        
        $new_loan_data = array(
            'loan_ref'                  => $new_loan_ref,
            'warehouse_id'              => $old_loan->warehouse_id,
            'cus_id'                    => $old_loan->cus_id,
            'route_id'                  => $old_loan->route_id,
            'loan_type'                 => $old_loan->loan_type,
            'loan_tot_amount'           => $loan_tot_amount,
            'loan_date'                 => date('Y-m-d'),
            'loan_interest'             => $old_loan->loan_interest,
            'loan_payment_term'         => $loan_payment_term,
            'loan_no_of_terms'          => $new_no_of_terms,
            'loan_term_amount'          => $new_term_amount,
            'loan_payable_total_amount' => $loan_tot_amount,
            'loan_creted_date'          => date("Y-m-d H:i:s"),
            'g_cus_id'                  => $old_loan->g_cus_id,
            'panalty_enable'            => $old_loan->panalty_enable,
            'reduce_fron_ceque'         => $old_loan->reduce_fron_ceque,
            'document_charges'          => $old_loan->document_charges,
            'loan_interest_type'        => $old_loan->loan_interest_type,
            'total_interest'            => $new_total_interest,
            'term_intrerest'            => 0,
            'loan_payment_term_qty'     => $old_loan->loan_payment_term_qty,
            'loan_close_date'           => $new_end_date,
            'user_id'                   => $this->session->userdata('ss_user_id'),
            'panalty_presentage'        => $old_loan->panalty_presentage,
            'due_presentage'            => $old_loan->due_presentage,
            'marketing_officer_id'      => $old_loan->marketing_officer_id,
            'marketing_officer_discount'=> $old_loan->marketing_officer_discount,
            'loan_type_status'          => 'Active',
            'note'                      => $reschedule_reason,
        );
        
        $this->Loan_Model->save_loan_header($new_loan_data, false); // Insert as new loan
        $new_loan_id = $this->db->insert_id(); // Get the inserted loan ID

        // 6️⃣ Create new terms for the NEW loan
        $current_date = date('Y-m-d'); // Today as the starting point

        for ($i = 1; $i <= $new_no_of_terms; $i++) {
            if ($i > 1) {
                // From 2nd term onward, add days/weeks/months
                if ($loan_payment_term == 1) { // DAILY
                    $current_date = date('Y-m-d', strtotime($current_date . " + 1 day"));
                } elseif ($loan_payment_term == 2) { // WEEKLY
                    $current_date = date('Y-m-d', strtotime($current_date . " + 7 days"));
                } elseif ($loan_payment_term == 3) { // MONTHLY
                    $current_date = date('Y-m-d', strtotime($current_date . " + 1 month"));
                }
            }

            // Skip weekends & holidays if needed
            $valid_date = $this->get_next_valid_date($current_date);

            $term_data = array(
                'loan_id'        => $new_loan_id,
                'term_no'        => $i,
                'term_date'      => $valid_date,
                'term_amount'    => $new_term_amount,
                'paid_amount'    => 0.00,
                'penalty_amount' => 0.00,
                'status'         => 'Pending',
                'payment_date'   => null,
            );

            $this->Loan_Model->save_loan_term($term_data);

            $current_date = $valid_date; // update for next loop
        }


        // 7️⃣ Commit / Rollback
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            echo json_encode(array('error' => 1, 'msg' => 'Reschedule failed!'));
        } else {
            $this->db->trans_commit();
            echo json_encode(array('error' => 0, 'msg' => 'Loan successfully rescheduled!', 'loan_id' => $new_loan_id, 'old_loan_id' => $loan_id, 'new_loan_ref' => $new_loan_ref));
        }
    }


    private function get_next_valid_date($date)
    {
        // check if the given date is a holiday
        $is_holiday = $this->Holiday_Model->is_holiday($date);

        if ($is_holiday) {
            // move to the next day until not holiday
            do {
                $date = date('Y-m-d', strtotime($date . ' +1 day'));
            } while ($this->Holiday_Model->is_holiday($date));
        }

        return $date; // returns same date if not holiday
    }

    //-------------------------------------------------------------------
    public function loan_header_update()
    {
        $system_settings = $this->System_Settings_Model->get_system_settings_info(1);

        $holiday_active = $system_settings['holiday_status'];
        $adjest_loan_close_date = $system_settings['adjest_loan_close_date_via_holiday'];

        $this->load->library('form_validation'); //form validation lib
        $this->form_validation->set_rules('cus_id', 'Customer', 'required');
        $this->form_validation->set_rules('warehouse_id', 'Warehouse', 'required');
        $this->form_validation->set_rules('loan_tot_amount', 'Total Amount', 'required|greater_than[0]');
        $this->form_validation->set_rules('loan_date', 'Loan Date', 'required');
        $this->form_validation->set_rules('loan_interest', 'Interest', 'required|greater_than[-1]|less_than[101]');
        $this->form_validation->set_rules('loan_payment_term', 'Payment Term', 'required');
        $this->form_validation->set_rules('loan_no_of_terms', 'No. of Months', 'required|greater_than[0]');
        $this->form_validation->set_rules('loan_term_amount', 'Term Amount', 'required|greater_than[0]');
        $this->form_validation->set_rules('route_id', 'Route', 'required');
        $this->form_validation->set_rules('route_id', 'Route', 'required');
        $this->form_validation->set_rules('panalty_presentage', 'Panalty', 'required|greater_than[-1]|less_than[101]');
        $this->form_validation->set_rules('due_presentage', 'Panalty', 'required|greater_than[-1]|less_than[101]');
        //insert header data
        $data_item                 = array();

        $warehouse_id              = $this->input->post('warehouse_id');
        $ref_id_nxt                = $this->Common_Model->gen_ref_number('loan_id', 'loan', '');
        $cus_id                    = $this->input->post('cus_id');
        $loan_type                    = $this->input->post('loan_type');
        $route_id                  = $this->input->post('route_id');
        $loan_tot_amount           = $this->input->post('loan_tot_amount');
        $loan_date                 = $this->input->post('loan_date');
        $loan_interest             = $this->input->post('loan_interest');
        $loan_payment_term         = $this->input->post('loan_payment_term');
        $loan_no_of_terms          = $this->input->post('loan_no_of_terms');
        $loan_term_amount          = $this->input->post('loan_term_amount');
        $loan_status               = $this->input->post('loan_status');
        $loan_id                   = $this->input->post('loan_id');
        $loan_payable_total_amount = $this->input->post('loan_payable_total_amount');
        $panalty_enable            = $this->input->post('panalty_enable');
        $reduce_from_cheque        = $this->input->post('reduce_from_cheque');
        $doc_charge                = $this->input->post('doc_charge');
        $g_cus_id                  = $this->input->post('g_cus_id');
        $loan_interest_type        = $this->input->post('loan_interest_type');
        $total_interest            = $this->input->post('total_interest');
        $term_intrerest            = $this->input->post('term_intrerest');
        $loan_payment_term_qty     = $this->input->post('loan_payment_term_qty');
        $note                      = $this->input->post('note');
        $due_presentage            = $this->input->post('due_presentage');
        $panalty_presentage        = $this->input->post('panalty_presentage');
        //get warehouse code
        $warehouse_dtls            = $this->Warehouse_Model->get_warehouse_info($warehouse_id);
        $loan_ref                  = "LP" . $ref_id_nxt;
        $error                     = false;
        $errtxt                    = '';
        if ($loan_payment_term == 1) {

            $total_days   = $loan_no_of_terms;
            $Date         = $loan_date;
            //---------------------------------------------------------			
            if ($holiday_active == 1 && $adjest_loan_close_date == 1) {
                $open_date = date('Y-m-d', strtotime($loan_date));
                $loop_date = $open_date;
                $holiday_count = 0;
                $days_count = $total_days;
                for ($i = 1; $i <= $days_count; $i++) {
                    $check_holiday = $this->Holiday_Model->get_holidays_between_loan_open_close_date($loop_date);
                    if ($check_holiday > 0) {
                        $holiday_count += 1;
                        $days_count += 1;
                    }
                    $loop_date = date('Y-m-d', strtotime($loop_date . ' + 1 days'));
                }
                $total_days += $holiday_count;
                $total_days = $total_days - 1;
            }
            //-----------------------------------------------------------
            $closing_date = date('Y-m-d', strtotime($Date . ' + ' . $total_days . ' days'));
        }
        if ($loan_payment_term == 2) {
            $total_days   = $loan_no_of_terms * 7;
            $Date         = $loan_date;
            //---------------------------------------------------------			
            if ($holiday_active == 1 && $adjest_loan_close_date == 1) {
                $open_date = date('Y-m-d', strtotime($loan_date));
                $loop_date = $open_date;
                $holiday_count = 0;
                $days_count = $total_days;
                for ($i = 1; $i <= $days_count; $i++) {
                    $check_holiday = $this->Holiday_Model->get_holidays_between_loan_open_close_date($loop_date);
                    if ($check_holiday > 0) {
                        $holiday_count += 1;
                        $days_count += 1;
                    }
                    $loop_date = date('Y-m-d', strtotime($loop_date . ' + 1 days'));
                }
                echo $total_days . "--";
                $total_days += $holiday_count;
                $total_days = $total_days - 1;
                echo $total_days . "--";
            }
            //-----------------------------------------------------------
            $closing_date = date('Y-m-d', strtotime($Date . ' + ' . $total_days . ' days'));
        }
        if ($loan_payment_term == 3) {
            $total_days   = $loan_no_of_terms;
            $Date         = $loan_date;
            $closing_date = date('Y-m-d', strtotime("+" . $loan_no_of_terms . " months", strtotime($Date)));
        }
        if ($loan_payment_term == 4) {
            $total_days   = $loan_no_of_terms * $loan_payment_term_qty;
            $Date         = $loan_date;
            $closing_date = date('Y-m-d', strtotime($Date . ' + ' . $total_days . ' days'));
        }

        if ($this->form_validation->run() == FALSE) {
            echo json_encode(array(
                'loan_id' => '',
                'error' => 1,
                'msg' => validation_errors()
            ));
        } else {
            //$data_item['loan_ref']                  = $loan_ref;
            $data_item['warehouse_id'] = $warehouse_id;
            $data_item['cus_id']                    = $cus_id;
            $data_item['loan_tot_amount']           = $loan_tot_amount;
            $data_item['loan_date']                 = date('Y-m-d', strtotime($loan_date));
            $data_item['loan_interest']             = $loan_interest;
            $data_item['loan_payment_term']         = $loan_payment_term;
            $data_item['loan_no_of_terms']          = $loan_no_of_terms;
            $data_item['loan_term_amount']          = $loan_term_amount;
            $data_item['loan_payable_total_amount'] = $loan_payable_total_amount;
            $data_item['loan_creted_date']          = date("Y-m-d H:i:s");
            $data_item['panalty_enable']            = $panalty_enable;
            $data_item['reduce_fron_ceque']         = $reduce_from_cheque;
            $data_item['document_charges']          = $doc_charge;
            $data_item['g_cus_id']                  = $g_cus_id;
            $data_item['loan_interest_type']        = $loan_interest_type;
            $data_item['total_interest']            = $total_interest;
            $data_item['term_intrerest']            = $term_intrerest;
            $data_item['loan_payment_term_qty']     = $loan_payment_term_qty;
            $data_item['route_id']                  = $route_id;
            $data_item['note']                      = $note;
            $data_item['loan_close_date']           = $closing_date;
            $data_item['user_id']           = $this->session->userdata('ss_user_id');
            $data_item['panalty_presentage']        = $panalty_presentage;
            $data_item['due_presentage']            = $due_presentage;
            //-------------------------------------------------------
            if ($this->session->userdata('ss_group_id') == 1) {
                $data_item['approval_by']                 = $this->session->userdata('ss_user_id');
                $data_item['approval_date_time']        = date("Y-m-d H:i:s");
                $data_item['approval_comment']          = "Owner auto approval";
                $data_item['approval_status']           = 1;
                $data_item['loan_issue_status']            = 1;
            }
            //-------------------------------------------------------	
            if ($loan_id) {
                $this->Loan_Model->save_loan_header($data_item, $loan_id);
            } else {
                $this->Loan_Model->save_loan_header($data_item);
                $loan_id = $this->db->insert_id();
            }
            //echo $this->db->last_query();    
            if ($loan_payment_term == 4) {
                $is_cheque = 1;
            } else {
                $is_cheque = 0;
            }
            echo json_encode(array(
                'loan_id' => $loan_id,
                'error' => 0,
                'msg' => '',
                'is_cheque_req' => $is_cheque
            ));
        }
    }
    //---------------------------------------------------------------------
    public function get_list_loan($value = '')
    {
        $wareh_id = '';
        if ($this->session->userdata('ss_group_id') == 2) {
        } else {
            $wareh_id = $this->session->userdata('ss_warehouse_id');
        }
        $values  = $this->Loan_Model->getLoan(0);
        $columns = array();
        $data    = array();
        if (!empty($values)) {
            foreach ($values as $users) {
                $row     = array();
                $loan_id = $users->loan_id;
                if ($users->loan_payment_term == 4) {
                    $pTname = $users->payment_term_name . " " . $users->loan_payment_term_qty . " days";
                    if ($users->reduce_fron_ceque == 1) {
                        $pTname = $users->payment_term_name . " ( Custom duration ) ";
                    }
                } else {
                    $pTname = $users->payment_term_name;
                }
                //print_r($loan_id);
                $row[]         = $users->loan_id;
                $row[]         = '<a target="_blank" href="' . base_url() . 'loan/details/' . $users->loan_id . '">' . $users->loan_ref . '</a>';
                $row[]         = $users->cus_name;
                $row[]         = $users->loan_date;
                $row[]         = $pTname;
                $clas          = '';
                $row[]         = $users->loan_no_of_terms;
                $row[]         = $users->loan_term_amount;
                $row[]         = $users->loan_interest . ' %';
                $loan_editable = false;
                $loan_editable = false;
                $app_status    = '';
                if ($users->approval_status == 1) {
                    $app_status = '<span class="label label-success">Approved</span>';
                }
                if ($users->approval_status == 0) {
                    $app_status = '<span class="label label-info">Pending</span>';
                }
                if ($users->approval_status == (-1)) {
                    $app_status = '<span class="label danger">Reject</span>';
                }
                $row[] = $app_status;
                $row[] = number_format($users->loan_tot_amount, 2, '.', ',');
                $row[] = number_format($users->loan_payable_total_amount, 2, '.', ',');
                if ($users->loan_payment_term == 4) {
                    $is_cheque = '                           
                             <li><a href="' . base_url() . 'loan/add_cheque_for_loan/' . $users->loan_id . '"><i class="fa fa-edit"></i> ADD Cheque</a></li>';
                } else {
                    $is_cheque = "";
                }
                $row_action = '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">';
                if (!$loan_editable) {
                    $row_action .= '                           
                             <li><a href="' . base_url() . 'loan/manage/' . $users->loan_id . '"><i class="fa fa-edit"></i> Update Loan Details</a></li>';
                }
                $row_action .= ' <li><a href="' . base_url() . 'loan/details/' . $users->loan_id . '"><i class="fa fa-file-text-o"></i> Loan Details</a></li>' . $is_cheque . '
                            <li><a onClick="fbs_click(' . $users->loan_id . ')" data-toggle="modal" href="#" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-print"></i> Print Loan Invoice</a></li>                        
                            </ul></div>';
                $row[]  = $row_action;
                //$row[]=$actionTxtUpdate.$actionTxtDisble.$actionTxtEnable.$actionTxtPw.$actionTxtDelete;    
                $data[] = $row;
            }
            $output = array(
                'data' => $data
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
    //----------------------------------------------------------------------------------- 
    public function get_list_loan_by_customer($value = '')
    {
        $cus_id   = $this->input->get('cus_id');
        $wareh_id = '';
        if ($this->session->userdata('ss_group_id') == 2) {
        } else {
            $wareh_id = $this->session->userdata('ss_warehouse_id');
        }
        $values  = $this->Loan_Model->getLoan_by_customer($cus_id);
        $columns = array();
        $data    = array();
        //print_r($values);
        if (!empty($values)) {
            foreach ($values as $users) {
                $row               = array();
                $loan_id           = $users->loan_id;
                $row[]             = $users->loan_id;
                $row[]             = '<a target="_blank" href="' . base_url() . 'loan/details/' . $users->loan_id . '">' . $users->loan_ref . '</a>';
                $row[]             = $users->cus_name;
                $row[]             = $users->loan_date;
                $row[]             = $users->payment_term_name;
                $clas              = '';
                $row[]             = $users->loan_no_of_terms;
                $row[]             = $users->loan_term_amount;
                $row[]             = $users->loan_interest . ' %';
                $loan_editable     = false;
                $loan_editable     = false;
                $total_paid_amount = 0;
                $total_paid_amount = $this->Loan_Payment_Received_Model->get_total_paid_loan_by_loan_id($loan_id);

                $loan_only_paid = 0;
                if (isset($total_paid_amount['loan_received'])) {
                    $loan_only_paid = $total_paid_amount['loan_received'];
                }


                $pay_st            = '';
                if (empty($total_paid_amount)) {
                    if ($loan_only_paid < $users->loan_payable_total_amount) { {
                            $pay_st = '<span class="label label-yellow">Pending</span>';
                        }
                    }
                } else {
                    if ($loan_only_paid >= $users->loan_payable_total_amount) {
                        $pay_st = '<span class="label label-success">Paid</span>';
                    } else {
                        if ($loan_only_paid < $users->loan_payable_total_amount) { {
                                $pay_st = '<span class="label label-info">Partial</span>';
                            }
                        }
                    }
                }
                $row[]      = $pay_st;
                $row[]      = number_format($users->loan_tot_amount, 2, '.', ',');
                $row[]      = number_format($loan_only_paid, 2, '.', ',');
                $row[]      = number_format($users->loan_payable_total_amount - $loan_only_paid, 2, '.', ',');
                $row_action = '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">';
                if (!$loan_editable) {
                    $row_action .= '';
                }
                $row_action .= ' <li><a target="_blank" href="' . base_url() . 'loan/details/' . $users->loan_id . '"><i class="fa fa-file-text-o"></i> Loan Details</a></li>
                            <li><a onClick="fbs_click(' . $users->loan_id . ')" data-toggle="modal" href="#" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-print"></i> Print Loan Invoice</a></li>                        
                            </ul></div>';
                $row[]  = $row_action;
                //$row[]=$actionTxtUpdate.$actionTxtDisble.$actionTxtEnable.$actionTxtPw.$actionTxtDelete;    
                $data[] = $row;
            }
            $output = array(
                'data' => $data
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }

    public function get_previous_list_loans_by_customer_id()
    {
        $cus_id   = $this->input->get('cus_id');
        $loan_id   = $this->input->get('loan_id');
        $values  = $this->Loan_Model->get_previous_loan_by_customer_id($cus_id, $loan_id);
        $columns = array();
        $data    = array();
        //print_r($values);
        if (!empty($values)) {
            foreach ($values as $users) {
                $row               = array();
                $loan_id           = $users->loan_id;
                $row[]             = $users->loan_id;
                $row[]             = '<a target="_blank" href="' . base_url() . 'loan/details/' . $users->loan_id . '">' . $users->loan_ref . '</a>';
                $row[]             = $users->loan_date;
                $row[]             = $users->payment_term_name;
                $row[]             = $users->loan_no_of_terms;
                $row[]             = $users->loan_term_amount;
                $loan_editable     = false;
                $loan_editable     = false;
                $total_paid_amount = 0;
                $total_paid_amount = $this->Loan_Payment_Received_Model->get_total_paid_loan_by_loan_id($loan_id);

                $loan_only_paid = 0;
                if (isset($total_paid_amount['loan_received'])) {
                    $loan_only_paid = $total_paid_amount['loan_received'];
                }


                $pay_st            = '';
                if (empty($total_paid_amount)) {
                    if ($loan_only_paid < $users->loan_payable_total_amount) { {
                            $pay_st = '<span class="label label-yellow">Pending</span>';
                        }
                    }
                } else {
                    if ($loan_only_paid >= $users->loan_payable_total_amount) {
                        $pay_st = '<span class="label label-success">Paid</span>';
                    } else {
                        if ($loan_only_paid < $users->loan_payable_total_amount) { {
                                $pay_st = '<span class="label label-info">Partial</span>';
                            }
                        }
                    }
                }
                $row[]      = $pay_st;
                $row[]      = number_format($users->loan_tot_amount, 2, '.', ',');
                $row[]      = number_format($loan_only_paid, 2, '.', ',');
                $row[]      = number_format($users->loan_payable_total_amount - $loan_only_paid, 2, '.', ',');

                $data[] = $row;
            }
            $output = array(
                'data' => $data
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }

    public function add_cheque_for_loan()
    {
        $data['main_menu_name']    = $this->main_menu_name;
        $data['sub_menu_name']     = "";
        $loan_id                   = $this->uri->segment('3');
        $data['loan_id']           = $loan_id;
        $data['loan_payment_list'] = $this->Loan_Model->get_loan_payments_by_loan_id($loan_id);
        $data['bank_list']         = $this->Bank_Model->get_all_bank();
        $data['hdr_data']          = $this->Loan_Model->get_loan_details_by_id($loan_id);
        $this->load->model('Bank_model');
        $data['banks'] = $this->Bank_model->get_banks();
        //print_r($data['loan_payment_list']);
        $this->load->view('loan_add_cheque', $data);
    }

    //--------------------------------------------------------------

    public function ongoing_loan()
    {
        $data['main_menu_name'] = "ongoing_loan";
        $data['sub_menu_name'] = "ongoing_loan";
        $data['payment_term_list'] = $this->Loan_Model->get_loan_payments_term();
        $data['routes_list'] = $this->Route_Model->get_all_active_routes();
        $this->load->view('ongoing_loan', $data);
    }

    public function get_list_loan_approved_active($value = '')
    {
        $start            = $this->input->get('start');
        $length           = $this->input->get('length');
        $search           = $this->input->get('search');

        if ($this->session->userdata('ss_group_id') == 1 || $this->session->userdata('ss_group_id') == 2) {
            $wareh_id = '';
        } else {
            $wareh_id = $this->session->userdata('ss_warehouse_id');
        }
        $route = $this->input->get('route');
        $payment_t = $this->input->get('payment_t');
        $values = $this->Loan_Model->getLoan_approved_active($wareh_id, $route, $payment_t, $start, $length, $search['value']);
        $count = $this->Loan_Model->getLoan_approved_active($wareh_id, $route, $payment_t, "", "", $search['value']);

        $totalData = $count;
        $totalFiltered = $totalData;
        $columns = array();
        $data = array();
        if (!empty($values)) {
            foreach ($values as $users) {
                $row = array();
                if ($users->loan_payment_term == 4) {
                    $pTname = $users->payment_term_name . " " . $users->loan_payment_term_qty . " days";
                    if ($users->reduce_fron_ceque == 1) {
                        $pTname = $users->payment_term_name . " ( Custom duration ) ";
                    }
                } else {
                    $pTname = $users->payment_term_name;
                }
                $loan_id = $users->loan_id;
                $row[] = $users->loan_id;
                $row[] = '<a target="_blank" href="' . base_url() . 'loan/details/' . $users->loan_id . '">' . $users->loan_ref . '</a>';
                $row[] = $users->cus_name;
                $row[] = $users->loan_date;
                $row[] = $pTname;
                $clas = '';
                $row[] = $users->loan_no_of_terms;
                $row[] = $users->loan_term_amount;
                $row[] = $users->loan_interest . ' %';
                $loan_editable = false;
                $loan_editable = false;

                $app_status = '';
                if ($users->approval_status == 1) {
                    $app_status = '<span class="label label-success">Approved</span>';
                }
                if ($users->approval_status == 0) {
                    $app_status = '<span class="label label-info">Pending</span>';
                }
                if ($users->approval_status == (-1)) {
                    $app_status = '<span class="label danger">Reject</span>';
                }
                $row[] = $app_status;
                $row[] = number_format($users->loan_tot_amount, 2, '.', ',');

                $row[] = number_format($users->loan_payable_total_amount, 2, '.', ',');
                $manual_close = '';
                if ($this->session->userdata('ss_group_id') == 1) {
                    $manual_close = ' <li><a onClick="loan_close_manually(' . $users->loan_id . ')" data-toggle="modal" href="#" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-ban"></i> Close Manually</a></li>';
                }
                $row_action = '<div class="btn-group text-left">                       
					 <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                       <ul role="menu" class="dropdown-menu pull-right">
                           <li><a href="' . base_url() . 'loan/details/' . $users->loan_id . '"><i class="fa fa-text-o"></i> Loan Details</a></li>
                           ' . $manual_close . '
                       </ul></div>';

                $row[] = $row_action;
                //$row[]=$actionTxtUpdate.$actionTxtDisble.$actionTxtEnable.$actionTxtPw.$actionTxtDelete;	
                $data[] = $row;
            }
            $json_data = array(
                //"draw"            => intval( $requestData['draw'] ),  
                "recordsTotal"    => intval($totalData),
                "recordsFiltered" => intval($totalFiltered),
                "data"            => $data
            );

            echo json_encode($json_data);
        } else {
            $json_data = array(
                //"draw"            => intval( $requestData['draw'] ),  
                "recordsTotal"    => intval(0),
                "recordsFiltered" => intval(0),
                "data"            => ""
            );

            echo json_encode($json_data);
        }
    }


    //----------------------------------------------------------

    //--------------------------------------------------------------

    public function closed_loan()
    {
        $data['main_menu_name'] = "closed_loan";
        $data['sub_menu_name'] = "closed_loan";
        $this->load->view('closed_loan', $data);
    }

    public function get_list_loan_closed($value = '')
    {
        $start            = $this->input->get('start');
        $length           = $this->input->get('length');
        $search           = $this->input->get('search');

        if ($this->session->userdata('ss_group_id') == 1 || $this->session->userdata('ss_group_id') == 2) {
            $wareh_id = '';
        } else {
            $wareh_id = $this->session->userdata('ss_warehouse_id');
        }
        $values = $this->Loan_Model->getLoan_closed($wareh_id, $start, $length, $search['value']);
        $count = $this->Loan_Model->getLoan_closed($wareh_id, "", "", $search['value']);

        $totalData = $count;
        $totalFiltered = $totalData;
        $columns = array();
        $data = array();
        if (!empty($values)) {
            foreach ($values as $users) {
                $row = array();
                if ($users->loan_payment_term == 4) {
                    $pTname = $users->payment_term_name . " " . $users->loan_payment_term_qty . " days";
                    if ($users->reduce_fron_ceque == 1) {
                        $pTname = $users->payment_term_name . " ( Custom duration ) ";
                    }
                } else {
                    $pTname = $users->payment_term_name;
                }
                $loan_id = $users->loan_id;
                $total_paid_amount = $this->Loan_Model->get_total_paid_by_loan_id($loan_id);
                //--------------------------------------

                $date_different = '';
                $loan_start_date = $users->loan_date;
                $loan_close_date = $users->loan_close_date;

                $holiday_count = $this->Holiday_Model->get_holiday_count_between_loan_start_date_and_end_date($loan_start_date, $loan_close_date);
                if ($holiday_count) {
                    $total_holidays = $holiday_count;
                } else {
                    $total_holidays = 0;
                }
                $total_no_of_term = $users->loan_no_of_terms;
                $loan_total_days = $total_no_of_term + $total_holidays - 1;
                $extented_closing_date = date('Y-m-d', strtotime($loan_start_date . ' + ' . $loan_total_days . ' days'));

                $loan_closed_date = $users->system_close_date;

                if ($loan_closed_date > $extented_closing_date) {
                    $loan_closed_date = "<span class='label label-danger'>" . $loan_closed_date . "</span>";

                    $date1 = date_create($users->system_close_date);
                    $date2 = date_create($extented_closing_date);
                    $diff = date_diff($date1, $date2);
                    $date_different = $diff->format("%a");
                }


                //--------------------------------------------
                //$row[] = $users->loan_id;
                $row[] = '<a target="_blank" href="' . base_url() . 'loan/details/' . $users->loan_id . '">' . $users->loan_ref . '</a>';
                $row[] = $users->cus_name;
                $row[] = $loan_closed_date;
                $row[] = $users->loan_date;
                $row[] = $date_different;
                $row[] = $pTname;
                $clas = '';
                $row[] = $users->loan_no_of_terms;
                $row[] = $users->loan_term_amount;
                $row[] = $users->loan_interest . ' %';
                $loan_editable = false;
                $loan_editable = false;

                $app_status = '';
                if ($users->approval_status == 1) {
                    $app_status = '<span class="label label-success">Approved</span>';
                }
                if ($users->approval_status == 0) {
                    $app_status = '<span class="label label-info">Pending</span>';
                }
                if ($users->approval_status == (-1)) {
                    $app_status = '<span class="label label-danger">Reject</span>';
                }
                $row[] = number_format($users->loan_tot_amount, 2, '.', ',');

                $row[] = number_format($users->loan_payable_total_amount, 2, '.', ',');
                $row_action = '<div class="btn-group text-left">                       
					 <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                       <ul role="menu" class="dropdown-menu pull-right">
                           <li><a href="' . base_url() . 'loan/details/' . $users->loan_id . '"><i class="fa fa-text-o"></i> Loan Details</a></li>					
                       </ul></div>';

                $row[] = number_format($total_paid_amount, 2, '.', ',');
                $row[] = number_format($total_paid_amount - $users->loan_tot_amount, 2, '.', ',');
                $data[] = $row;
            }
            $json_data = array(
                //"draw"            => intval( $requestData['draw'] ),  
                "recordsTotal"    => intval($totalData),
                "recordsFiltered" => intval($totalFiltered),
                "data"            => $data
            );

            echo json_encode($json_data);
        } else {
            $json_data = array(
                //"draw"            => intval( $requestData['draw'] ),  
                "recordsTotal"    => intval(0),
                "recordsFiltered" => intval(0),
                "data"            => ""
            );

            echo json_encode($json_data);
        }
    }
    //----------------------------------------------------------


    function ongoing_loan_currant_status()
    {
        $data['main_menu_name'] = "ongoing_loan";
        $data['sub_menu_name'] = "ongoing_loan_currant_status";
        $this->load->view('ongoing_loan_currant_status', $data);
    }

    public function get_list_loan_ongoing_loan_currant_status($value = '')
    {
        $start            = $this->input->get('start');
        $length           = $this->input->get('length');
        $search           = $this->input->get('search');

        if ($this->session->userdata('ss_group_id') == 1 || $this->session->userdata('ss_group_id') == 2) {
            $wareh_id = '';
        } else {
            $wareh_id = $this->session->userdata('ss_warehouse_id');
        }
        $route = $this->input->get('route');
        $payment_t = $this->input->get('payment_t');
        $values = $this->Loan_Model->getLoan_approved_active($wareh_id, $route, $payment_t, $start, $length, $search['value']);
        $count = $this->Loan_Model->getLoan_approved_active($wareh_id, $route, $payment_t, "", "", $search['value']);

        $totalData = $count;
        $totalFiltered = $totalData;
        $columns = array();
        $data = array();
        if (!empty($values)) {
            foreach ($values as $users) {
                $row = array();
                if ($users->loan_payment_term == 4) {
                    $pTname = $users->payment_term_name . " " . $users->loan_payment_term_qty . " days";
                    if ($users->reduce_fron_ceque == 1) {
                        $pTname = $users->payment_term_name . " ( Custom duration ) ";
                    }
                } else {
                    $pTname = $users->payment_term_name;
                }
                $loan_id = $users->loan_id;
                $row[] = '<a target="_blank" href="' . base_url() . 'loan/details/' . $users->loan_id . '">' . $users->loan_ref . '</a>';
                $row[] = $users->cus_name;
                $row[] = $pTname;
                $row[] = $users->loan_no_of_terms;
                $row[] = $users->loan_interest . ' %';
                $row[] = number_format($users->loan_term_amount, 2, '.', ',');
                $row[] = number_format($users->loan_tot_amount, 2, '.', ',');
                $row[] = number_format($users->loan_payable_total_amount, 2, '.', ',');
                $row_action = '<div class="btn-group text-left">                       
					 <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                       <ul role="menu" class="dropdown-menu pull-right">
                           <li><a href="' . base_url() . 'loan/details/' . $users->loan_id . '"><i class="fa fa-text-o"></i> Loan Details</a></li>					
                       </ul></div>';

                $row[] = $row_action;
                $data[] = $row;
            }
            $json_data = array(
                //"draw"            => intval( $requestData['draw'] ),  
                "recordsTotal"    => intval($totalData),
                "recordsFiltered" => intval($totalFiltered),
                "data"            => $data
            );

            echo json_encode($json_data);
        } else {
            $json_data = array(
                //"draw"            => intval( $requestData['draw'] ),  
                "recordsTotal"    => intval(0),
                "recordsFiltered" => intval(0),
                "data"            => ""
            );

            echo json_encode($json_data);
        }
    }



    public function save_attached_documents()
    {
        //error_reporting( E_ALL );
        $sale_id = $this->input->post('att_sale_id');
        $data_item = array();
        for ($m = 1; $m < 6; $m++) {
            $col_tmp_name = 'sale_att_0' . $m;
            //upload sale_att_01
            $media_url = '';
            if (isset($_FILES[$col_tmp_name]['name']) && !empty($_FILES[$col_tmp_name]['name'])) {
                $image_upload = $this->upload_file($col_tmp_name, '');

                if ($image_upload) {
                    $image_upload = $image_upload;
                }
                if (!empty($image_upload)) {
                    $data_item[$col_tmp_name] = $image_upload;
                }
            }
            //end upload image 01	
        }

        if ($this->Sales_Model->update_sale($data_item, $sale_id)) {
            redirect(base_url('sales/view/' . $sale_id), 'refresh');
        }
    }

    public function upload_file($image_fld_name, $path = 'assets')

    {
        $target_dir = "assets/";
        $file_name = date("ymdhis") . '_' . rand(5, 9999) . '_' . basename($_FILES[$image_fld_name]["name"]);
        $target_file = $target_dir . $file_name;
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        // Check if image file is a actual image or fake image
        if (isset($_POST["submit"])) {
            $check = getimagesize($_FILES[$image_fld_name]["tmp_name"]);
            if ($check !== false) {
                // echo "File is an image - " . $check["mime"] . ".";
                $uploadOk = 1;
            } else {
                // echo "File is not an image.";
                $uploadOk = 0;
            }
        }
        // Check if file already exists
        if (file_exists($target_file)) {
            // echo "Sorry, file already exists.";
            $uploadOk = 0;
        }
        // Check file size
        if ($_FILES[$image_fld_name]["size"] > 500000) {
            // echo "Sorry, your file is too large.";
            $uploadOk = 0;
        }
        // Allow certain file formats
        if (
            $imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
            && $imageFileType != "gif"
        ) {
            // echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            $uploadOk = 0;
        }
        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            //  echo "Sorry, your file was not uploaded.";
            // if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES[$image_fld_name]["tmp_name"], $target_file)) {
                //  echo "The file ". basename( $_FILES[$image_fld_name]["name"]). " has been uploaded.";
            } else {
                // echo "Sorry, there was an error uploading your file.";
            }
        }
        return $file_name;
    }

    public function upload_document($loan_id)
    {
        $person_type = $this->input->post('person_type');
        $doc_type = $this->input->post('doc_type');

        $config['upload_path']   = 'thems/uploads/loans/' . $loan_id . '/';
        if (!is_dir($config['upload_path'])) {
            mkdir($config['upload_path'], 0777, true);
        }
        $config['allowed_types'] = 'jpg|jpeg|png|pdf';
        $config['max_size']      = 20480; // 20 MB
        $config['file_name']     = $person_type . '_' . $doc_type . '_' . time();

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('document')) {
            echo json_encode([
                'status' => 'error',
                'message' => strip_tags($this->upload->display_errors())
            ]);
            return;
        }

        $file_data = $this->upload->data();
        $file_path = 'thems/uploads/loans/' . $loan_id . '/' . $file_data['file_name'];

        // Check if document exists
        $existing = $this->Loan_Model->get_document($loan_id, $person_type, $doc_type);

        if ($existing) {
            // Remove old file

            // if (file_exists(FCPATH . $existing->file_path)) {
            //     unlink(FCPATH . $existing->file_path);
            // }
            // Update record
            $this->Loan_Model->update_document($existing->doc_id, [
                'file_path' => $file_path,
                'uploaded_by' => $this->session->userdata('user_id')
            ]);
        } else {
            // Insert new record
            $this->Loan_Model->save_document([
                'loan_id' => $loan_id,
                'person_type' => $person_type,
                'doc_type' => $doc_type,
                'file_path' => $file_path,
                'uploaded_by' => $this->session->userdata('user_id')
            ]);
        }

        echo json_encode(['status' => 'success', 'file_path' => base_url($file_path)]);
    }

    public function get_documents($loan_id)
    {
        $docs = $this->Loan_Model->get_documents_by_loan($loan_id);

        foreach ($docs as &$doc) {
            $doc->file_url = base_url($doc->file_path);
        }

        echo json_encode($docs);
    }

    public function get_end_date()
    {

        $loan_date   = $this->input->post('loan_date');   // e.g. 2025-08-21
        $no_of_terms = $this->input->post('no_of_terms'); // e.g. 50
        $loan_payment_term = $this->input->post('loan_payment_term'); // e.g. 50


        //$loan_date   = '23-10-2025';   // e.g. 2025-08-21
        ///$no_of_terms = 75; // e.g. 50
        //$loan_payment_term = 1; // e.g. 50
        $no_of_terms_new = $no_of_terms;

        $this->load->model('holiday_model');
        $loan_year = date('Y', strtotime($loan_date));
        $next_year = $loan_year + 1;
        // Get holidays for both current and next year
        $holidays_current = $this->holiday_model->get_holidays($loan_year);
        $holidays_next    = $this->holiday_model->get_holidays($next_year);
        // Merge into one array
        $holidays = array_merge($holidays_current, $holidays_next);
        //$holidays = $this->holiday_model->get_holidays(date('Y', strtotime($loan_date)));
        //echo '<pre>',print_r($holidays); die();
        $date = new DateTime($loan_date);


        if ($loan_payment_term == 1) {
            // Daily
            $end_date = calculate_end_date($loan_date, $no_of_terms, $holidays);
        } elseif ($loan_payment_term == 2) {
            // Weekly terms, but 4 = 1 month, 8 = 2 months, etc.
            $months_to_add = floor($no_of_terms / 4);
            $date = new DateTime($loan_date);
            // Move to the 1st day of (loan_date + months_to_add)
            $date->modify("first day of +{$months_to_add} month");
            // Subtract 1 day → last day of the previous month
            $date->modify("-1 day");
            $end_date = $date->format('Y-m-d');
        } elseif ($loan_payment_term == 3) {
            // Monthly
            $date->modify("+{$no_of_terms} months");
            $end_date = $date->format('Y-m-d');
        } elseif ($loan_payment_term == 4) {
            // Custom (same as daily, but no holidays skipped)
            $end_date = (new DateTime($loan_date))->modify("+{$no_of_terms} days")->format('Y-m-d');
        } elseif ($loan_payment_term == 5) {
            // Yearly
            $date->modify("+{$no_of_terms} years");
            $end_date = $date->format('Y-m-d');
        }



        // Number of days difference
        $start = new DateTime($loan_date);
        $end   = new DateTime($end_date);
        $days_count = $start->diff($end)->days;

        echo json_encode([
            'end_date'   => date('d-m-Y', strtotime($end_date)),
            'days_count' => $days_count
        ]);
    }

    public function get_reschedule_end_date()
    {
        $loan_date   = $this->input->post('loan_date');   // e.g. 2025-08-21
        $no_of_terms = $this->input->post('no_of_terms'); // e.g. 50
        $loan_payment_term = $this->input->post('loan_payment_term'); // e.g. 1,2,3...

        $this->load->model('holiday_model');
        //$holidays = $this->holiday_model->get_holidays(date('Y', strtotime($loan_date)));
        $loan_year = date('Y', strtotime($loan_date));
        $next_year = $loan_year + 1;
        // Get holidays for both current and next year
        $holidays_current = $this->holiday_model->get_holidays($loan_year);
        $holidays_next    = $this->holiday_model->get_holidays($next_year);
        // Merge into one array
        $holidays = array_merge($holidays_current, $holidays_next);
        $date = new DateTime($loan_date);

        if ($loan_payment_term == 1) {
            // Daily (start from today)
            $end_date = calculate_reschedule_end_date($loan_date, $no_of_terms, $holidays);
        } elseif ($loan_payment_term == 2) {
            // Weekly
            $months_to_add = floor($no_of_terms / 4);
            $date->modify("first day of +{$months_to_add} month");
            $date->modify("-1 day");
            $end_date = $date->format('Y-m-d');
        } elseif ($loan_payment_term == 3) {
            // Monthly
            $date->modify("+{$no_of_terms} months");
            $end_date = $date->format('Y-m-d');
        } elseif ($loan_payment_term == 4) {
            // Custom (same as daily, but no holidays skipped, start from today)
            $end_date = (new DateTime($loan_date))->modify("+" . ($no_of_terms - 1) . " days")->format('Y-m-d');
        } elseif ($loan_payment_term == 5) {
            // Yearly
            $date->modify("+{$no_of_terms} years");
            $end_date = $date->format('Y-m-d');
        }

        // Number of days difference
        $start = new DateTime($loan_date);
        $end   = new DateTime($end_date);
        $days_count = $start->diff($end)->days;

        echo json_encode([
            'end_date'   => date('d-m-Y', strtotime($end_date)),
            'days_count' => $days_count
        ]);
    }


    public function get_holidays()
    {
        $this->db->select("holiday_date");
        $this->db->from("holiday");
        $this->db->where("status", 1);
        $this->db->where("is_deleted", 0);
        $query = $this->db->get();
        $holidays = [];
        foreach ($query->result() as $row) {
            $holidays[] = date("d/m/Y", strtotime($row->holiday_date));
        }

        echo json_encode($holidays);
    }


    public function download_word_old($id)
    {
        $agreement = $this->Loan_Model->get_loan_details_by_loan_id($id);
        //echo '<pre>',print_r($agreement),'</pre>'; die();
        if (!$agreement) {
            show_error('Agreement not found.');
        }

        $get_business_info = $this->Customer_Model->get_business_info($agreement['cus_id']);
        $get_personal_info = $this->Customer_Model->get_personal_info($agreement['cus_id']);
        $schedule = $this->Loan_Model->get_loan_terms_by_loan_id($id);
        //echo '<pre>',print_r($schedule),'</pre>'; die();
        // Use PHPWord 0.13.0 directly (autoloaded via Composer)
        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $section = $phpWord->createSection();

        // Promissory Note Section
        $section->addTitle('PROMISSORY NOTE', 1);
        $section->addText('(Capital Sum: ' . number_format($agreement['loan_tot_amount'], 0) . '/-)', array('bold' => true));
        $textRun = $section->addTextRun();
        $textRun->addText("On Demand, I the undersigned {$agreement['approval_comment']} (holder of National Identity Card No. {$agreement['approval_comment']}) and {$agreement['approval_comment']} (holder of National Identity Card No. {$agreement['approval_comment']}) Both are residing at {$agreement['approval_comment']} Directors of {$agreement['approval_comment']} (Registered No: {$agreement['approval_comment']}) at {$agreement['approval_comment']} promise to pay to {$agreement['approval_comment']} (Registered No: {$agreement['approval_comment']}) of {$agreement['approval_comment']} or order the sum of Rupees " . $this->number_to_words($agreement['approval_comment']) . " (LKR " . number_format($agreement['loan_tot_amount'], 0) . "/-) with interest calculated thereon at the rate of {$agreement['loan_interest']}% per mensem, in {$agreement['loan_no_of_terms']} equal daily installments of " . number_format($agreement['loan_term_amount'], 0) . "/- commencing from " . date('jS of F Y', strtotime($agreement['loan_date'])) . " and Ending on " . date('jS of F Y', strtotime($agreement['loan_close_date'])) . ".");
        $section->addText('Provided however that demand shall not be made unless there is a default in payment as aforesaid.');
        $section->addText("In the event of default by me in duly paying installments as aforesaid, {$get_business_info->business_name} have the right to charge a penal interest of 10% per annum on such overdue payments until payment in full.");
        $section->addText('In the event of early settlement charges will not be refunded in any circumstances.');
        $section->addText("In the event of loan reschedule requested by me {$get_business_info->business_name} have right to charge 7% per month on such extensions.");
        $section->addText("In the event that I failed to pay five agreed upon installments, {$get_business_info->business_name} shall have the rights to terminate the agreement and demand immediate settlement of the total outstanding and incase legal proceeding to recover the due.");
        $section->addText("In the event of a default by the borrower in repaying the loan amount {$get_business_info->business_name} shall have the right to take possession of and liquidate the Borrower`s stock held as security, to the extent of the outstanding dues including principal, interest, and delay charges. The valuation of such stock shall be based on the prevailing market price at the time of enforcement.");
        $section->addText("In the event that the Borrower intends to close down, discontinue, or otherwise cease operations of the business for any reason during the tenure of the loan, the Borrower shall provide prior written notice to {$get_business_info->business_name} at least 10 days in advance. Upon such closure, all outstanding dues, including the principal loan amount, accrued interest, and any applicable charges, shall become immediately due and payable.");
        $section->addText('Payment Collection Will Start Anytime From 11.00 a.m. to 07.00 p.m.');
        $section->addText('On this ' . date('jS (dS) Day of F Y', strtotime($agreement['loan_date'])) . ' at Colombo.');
        $section->addText($get_business_info->business_name);
        $section->addText($get_personal_info['full_name']);
        $section->addText('Witnesses:-');
        $section->addText('1.');
        $section->addText('2.');

        // Loan Agreement Section
        $section->addTitle('LOAN AGREEMENT', 1);
        $section->addText('THIS MEMORANDUM OF AGREEMENT made and entered into at Colombo in the Democratic Socialist Republic of Sri Lanka on this Ninth (09th) Day of September Two Thousand and Twenty Five (2025) by and between ' . $get_business_info->business_name . ' (Registered No : ' . $get_business_info->registration_number . ') of ' . $get_business_info->registered_address . ' in the said Republic of Sri Lanka, (hereinafter called and referred to as "the Lender" which term or expression as herein used shall where the context so requires or admits mean and include the said ' . $get_business_info->business_name . ', theirs, executors, administrators and assigns of the One Part.');
        $section->addText('AND');
        $section->addText(
            $get_business_info->business_name . " (holder of National Identity Card No. " . $get_personal_info['cus_nic'] . ") and " .
                $get_personal_info['full_name'] . " (holder of National Identity Card No. " . $get_personal_info['cus_nic'] . ") Both are residing at " .
                $get_business_info->registered_address . " Directors of " . $get_business_info->business_name . " (Registered No: " . $get_business_info->registration_number . ") at " .
                $get_business_info->registered_address . " (hereinafter called and referred to as 'the Borrower' which term or expression as herein used shall where the context so requires or admits mean and include the said " .
                $get_business_info->business_name . " & " . $get_personal_info['full_name'] . " and his, heirs, executors, administrators and assigns of the Other Part."
        );

        $section->addText('WITNESSETH');
        $section->addText('WHEREAS the Borrower has requested from the Lender and the Lender has agreed to grant to the Borrower a loan in a sum of Rupees ' . $this->number_to_words($agreement['loan_tot_amount']) . ' (LKR ' . number_format($agreement['loan_tot_amount'], 0) . '/-)upon the following terms and conditions;');
        $section->addText('NOW THIS AGREEMENT WITNESSETH and the parties do hereby agree as follows:-');
        $section->addText('1. The Lender has given to the Borrower and the Borrower has obtained from the Lender a total sum of Rupees ' . $this->number_to_words($agreement['loan_tot_amount']) . ' (LKR ' . number_format($agreement['loan_tot_amount'], 0) . '/-)the receipt of which the Borrower hereby admits and acknowledges:');
        $section->addText('2. This Agreement shall be valid and remains in force until the said principal sum of Rupees ' . $this->number_to_words($agreement['loan_tot_amount']) . ' (LKR ' . number_format($agreement['loan_tot_amount'], 0) . '/-)and the interest thereon as hereinafter set out are finally paid and settled by the Borrower;');
        $section->addText('3. The Borrower hereby agrees and undertake to repay the aforesaid principal sum of Rupees ' . $this->number_to_words($agreement['loan_tot_amount']) . ' (LKR ' . number_format($agreement['loan_tot_amount'], 0) . '/-) with interest calculated thereon at the rate of ' . $agreement['loan_interest'] . ' (6%) per mensem, in ' . $agreement['loan_no_of_terms'] . ' equal daily installments of ' . number_format($agreement['loan_no_of_terms'], 0) . '/- commencing from ' . date('jS of F Y', strtotime($agreement['loan_date'])) . ' and Ending on ' . date('jS of F Y', strtotime($agreement['loan_close_date'])) . '.');
        $section->addText('4. In the event of default by the Borrower in duly paying installments as aforesaid, the Lender has the right to charge a penal interest of 10% per month on such overdue payments until payment in full.');
        $section->addText('5. In the event of loan reschedule requested by me Beanstalk Investments Limited have right to charge 7% per month on such extensions. At the time of the execution hereof, borrower shall execute a promise note & new loan agreement in favour of lender with the extension charges at the office premises of Beanstalk Investments Limited.');
        $section->addText('6. In the event that borrower failed to pay five agreed upon installments, Beanstalk Investments Ltd shall have the rights to terminate the agreement and demand immediate settlement of the total outstanding and indicate legal proceeding to recover the due.');
        $section->addText('7. At the same time as the execution hereof, the Borrower shall execute a promissory note in favour of the Lender in the amount of LKR ' . number_format($agreement['loan_tot_amount'], 0) . '/-');
        $section->addText('8. A Schedule showing the aforesaid payments due from the Borrower is appended hereto as follows:-');

        // Schedule Table
        $section->addTitle('SCHEDULE', 2);
        $table = $section->addTable();
        $table->addRow();
        $table->addCell(1000)->addText('NO');
        $table->addCell(2000)->addText('Date');
        $table->addCell(2000)->addText('Amount');
        foreach ($schedule as $entry) {
            $table->addRow();
            $table->addCell(1000)->addText(($entry->term_no));
            $table->addCell(2000)->addText(date('d-M-y', strtotime($entry->term_date)));
            $table->addCell(2000)->addText(number_format($entry->term_amount, 2));
        }

        $section->addText('IN WITNESS WHEREOF the Lender and the Borrower have set their respective hands hereunto and to another at the place and on the date as hereinbefore mentioned.');
        $section->addText('Lender - ……………………');
        $section->addText('Borrower- …………………………..');
        $section->addText('Witnesses');
        $section->addText('1.');
        $section->addText('2.');
        if (ob_get_level()) {
            ob_end_clean(); // safer than ob_clean()
        }
        flush();
        // Save and download
        $filename = 'Promissory_Note_Loan_Agreement_' . $id . '.docx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $writer->save('php://output');
        exit;
    }

    public function download_word($id)
    {
        // --- Prepare data ---
        $agreement = $this->Loan_Model->get_loan_details_by_loan_id($id);
        if (!$agreement) {
            show_error('Agreement not found.');
        }

        $get_business_info = $this->Customer_Model->get_business_info($agreement['cus_id']);
        $get_personal_info = $this->Customer_Model->get_personal_info($agreement['cus_id']);
        $schedule = $this->Loan_Model->get_loan_terms_by_loan_id($id);

        // --- Initialize PHPWord ---
        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $section = $phpWord->addSection();

        // --- Document content ---
        $section->addTitle('PROMISSORY NOTE', 1);
        $section->addText('(Capital Sum: ' . number_format($agreement['loan_tot_amount'], 0) . '/-)', ['bold' => true]);
        $section->addText("Hello this is a safe test export to verify DOCX output.");

        // --- Table example ---
        $section->addTitle('SCHEDULE', 2);
        $table = $section->addTable();
        $table->addRow();
        $table->addCell(1000)->addText('NO');
        $table->addCell(2000)->addText('Date');
        $table->addCell(2000)->addText('Amount');
        foreach ($schedule as $entry) {
            $table->addRow();
            $table->addCell(1000)->addText($entry->term_no);
            $table->addCell(2000)->addText(date('d-M-y', strtotime($entry->term_date)));
            $table->addCell(2000)->addText(number_format($entry->term_amount, 2));
        }

        // --- Safety: stop profiler / buffering / compression ---
        $this->output->enable_profiler(FALSE);
        error_reporting(0);
        ini_set('zlib.output_compression', 'Off');

        while (ob_get_level() > 0) {
            ob_end_clean();
        } // clear all active buffers
        flush();

        // --- Prepare file name ---
        $filename = 'Promissory_Note_Loan_Agreement_' . $id . '.docx';

        // --- Headers for Word 2007+ ---
        header("Content-Description: File Transfer");
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
        header('Content-Transfer-Encoding: binary');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Expires: 0');
        header('Pragma: public');

        // --- Output to browser ---
        $writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $writer->save('php://output');
        exit;
    }


    private function number_to_words($number)
    {
        // Simple conversion for LKR 450,000 -> "Four Hundred Fifty Thousand"
        $ones = array('', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');
        $tens = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');
        $triplets = array('', 'Thousand', 'Million');

        $num = (int) $number;
        $result = '';

        if ($num == 0) return 'Zero';

        $triplet = 0;
        while ($num > 0) {
            $chunk = $num % 1000;
            if ($chunk) {
                $chunkStr = '';
                if ($chunk >= 100) {
                    $chunkStr .= $ones[intval($chunk / 100)] . ' Hundred ';
                    $chunk %= 100;
                }
                if ($chunk >= 20) {
                    $chunkStr .= $tens[intval($chunk / 10)] . ' ';
                    $chunk %= 10;
                }
                if ($chunk > 0) {
                    $chunkStr .= $ones[$chunk] . ' ';
                }
                if ($triplet > 0) $chunkStr .= $triplets[$triplet] . ' ';
                $result = $chunkStr . $result;
            }
            $num = intval($num / 1000);
            $triplet++;
        }
        return trim($result);
    }

    public function word()
    {
        // Load PHPWord library
        $this->load->library('PHPWord');
        $PHPWord = $this->phpword->load();

        // Disable profiler & compression
        $this->output->enable_profiler(FALSE);
        error_reporting(0);
        ini_set('zlib.output_compression', 'Off');

        // Build document
        $section = $PHPWord->createSection();
        $section->addText('Hello world! Testing CI + PHPWord clean output.');

        // Prepare writer
        $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
        $filename = 'test_output.docx';

        // Safely clean output buffer
        while (ob_get_level() > 0) {
            ob_end_clean();
        }
        flush();

        // Force download headers
        header("Content-Description: File Transfer");
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
        header('Content-Transfer-Encoding: binary');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Expires: 0');
        header('Pragma: public');

        // Output the file directly
        $objWriter->save('php://output');
        exit;
    }

    public function generate_promissory_note($id)
    {

        // --- Prepare data ---
        $agreement = $this->Loan_Model->get_loan_details_by_loan_id($id);
        if (!$agreement) {
            show_error('Agreement not found.');
        }


        $get_business_info = $this->Customer_Model->get_business_info($agreement['cus_id']);
        $get_personal_info = $this->Customer_Model->get_personal_info($agreement['cus_id']);
        $schedule = $this->Loan_Model->get_loan_terms_by_loan_id($id);
        /*
        echo '<pre>',print_r($agreement),'</pre>'; 
        echo '<pre>',print_r($get_business_info),'</pre>'; 
        echo '<pre>',print_r($get_personal_info),'</pre>'; 
        die(); */
        // Set headers to force download as a Word document
        header("Content-type: application/vnd.ms-word");
        header("Content-Disposition: attachment; filename=Modified_Promissory_Note.doc");

        $html_content = '
        <html xmlns:o="urn:schemas-microsoft-com:office:office"
        xmlns:w="urn:schemas-microsoft-com:office:word"
        xmlns="http://www.w3.org/TR/REC-html40">

        <head>
        <meta http-equiv=Content-Type content="text/html; charset=windows-1252">
        <meta name=ProgId content=Word.Document>
        <meta name=Generator content="Microsoft Word 11">
        <meta name=Originator content="Microsoft Word 11">
        <style>
        <!--
         /* Style Definitions */
         p.MsoNormal, li.MsoNormal, div.MsoNormal
            {mso-style-parent:"";
            margin:0in;
            margin-bottom:.0001pt;
            mso-pagination:widow-orphan;
            font-size:12.0pt;
            font-family:"Times New Roman";
            mso-fareast-font-family:"Times New Roman";}
        p
            {mso-margin-top-alt:auto;
            text-align:justify;
            margin-right:0in;
            mso-margin-bottom-alt:auto;
            margin-left:0in;
            font-size:12.0pt;
            font-family:"Times New Roman";
            mso-fareast-font-family:"Times New Roman";}
        .center
            {text-align: center;}
        .left
            {text-align: left;}
        span.mark
            {background-color: yellow;}
        @page Section1
            {size:8.5in 11.0in;
            margin:1.0in 0.6in 1.0in 0.6in;
            mso-header-margin:.5in;
            mso-footer-margin:.5in;
            mso-paper-source:0;}
        div.Section1
            {page:Section1;}
        -->
        </style>
        </head>

        <body lang=EN-US style=\'tab-interval:.5in\'>
        <div class=Section1>

        <p class=center><b><u>PROMISSORY NOTE</u></b></p>
        <p class=center><b><u>(Capital Sum: ' . number_format($agreement['loan_tot_amount'], 0, '.', ',') . '/-)' . '</u></b></p>

        <p>On Demand, I the undersigned <span style=\'background:yellow\'>' . $get_business_info->business_name . ' (holder of National Identity Card No.' . $get_personal_info['cus_nic'] . ') and ' . $get_personal_info['full_name'] . ' (holder of National Identity Card No. ' . $get_personal_info['cus_nic'] . ') Both are residing at No. 43 1/1, Anula Road, Colombo 06</span> Directors of <span style=\'background:yellow\'>' . $get_personal_info['cus_nic'] . ' (Registered No: PV00284492)</span> at <span style=\'background:yellow\'>[No. 43 1/1, Anula Road, Colombo 06]</span> promise to pay to <b>BEANSTALK INVESTMENTS LTD</b> (Registered No: PB4173) of No. 71 3/1, Davidson Road, Colombo 04 or order the sum of Rupees <span style=\'background:yellow\'>' . $this->number_to_words($agreement['loan_tot_amount']) . ' ' . number_format($agreement['loan_tot_amount'], 0, '.', ',') . '/-)' . '</span> with interest calculated thereon at the rate of <span style=\'background:yellow\'>[' . $this->number_to_words((int)$agreement['loan_interest']) . ' (' . $agreement['loan_interest'] . '%)]</span> per mensem, in <span style=\'background:yellow\'>[' . $agreement['loan_no_of_terms'] . ']</span> equal daily installments of <span style=\'background:yellow\'>[' . number_format($agreement['loan_term_amount'], 0, '.', ',') . '/-]</span> commencing from <span style=\'background:yellow\'>[' . $this->formatDateWithSuffix($agreement['loan_date']) . ' and Ending on ' . $this->formatDateWithSuffix($agreement['loan_close_date']) . ']</span>.</p>

        <p>Provided however that demand shall not be made unless there is a default in payment as aforesaid.</p>

        <p>In the event of default by me in duly paying installments as aforesaid, <b>Beanstalk Investments Ltd</b> have the right to charge a penal interest of 10% per annum on such overdue payments until payment in full.</p>

        <p>In the event of early settlement charges will not be refunded in any circumstances.</p>

        <p>In the event of loan reschedule requested by me Beanstalk Investments Limited have right to charge 7% per month on such extensions.</p>

        <p>In the event that I failed to pay five agreed upon installments, Beanstalk Investments Ltd shall have the rights to terminate the agreement and demand immediate settlement of the total outstanding and incase legal proceeding to recover the due.</p>

        <p>In the event of a default by the borrower in repaying the loan amount <b>Beanstalk Investments</b> shall have the right to take possession of and liquidate the Borrower`s stock held as security, to the extent of the outstanding dues including principal, interest, and delay charges. The valuation of such stock shall be based on the prevailing market price at the time of enforcement.</p>

        <p>In the event that the Borrower intends to close down, discontinue, or otherwise cease operations of the business for any reason during the tenure of the loan, the Borrower shall provide prior written notice to Beanstalk Investments at least 10 days in advance. Upon such closure, all outstanding dues, including the principal loan amount, accrued interest, and any applicable charges, shall become immediately due and payable.</p>

        <p>Payment Collection Will Start Anytime From 11.00 a.m. to 07.00 p.m.</p>

        <p>On this <span style=\'background:yellow\'>[' . $this->formatDateWithSuffix($agreement['loan_date']) . ']</span> 2025 at Colombo.</p>

        <p class=left><b><span style=\'background:yellow\'>[' . $get_personal_info['full_name'] . ']</span></b></p>
        <p class=left><b><span style=\'background:yellow\'>[' . $get_personal_info['full_name'] . ']</span></b></p>

        <p class=left>Witnesses:-</p>
        <p class=left>1. _________________________</p>
        <p class=left>2. _________________________</p>

        <p class=center><b><u>LOAN AGREEMENT</u></b></p>

        <p>THIS MEMORANDUM OF AGREEMENT made and entered into at Colombo in the Democratic Socialist Republic of Sri Lanka on this <span style=\'background:yellow\'>[' . $this->formatDateWithSuffix($agreement['loan_date']) . ']</span> Two Thousand and Twenty Five (2025) by and between <b>BEANSTALK INVESTMENTS LTD</b> ( Registered No : PB4173) of No. 71 3/1, Davidson Road, Colombo 04 in the said Republic of Sri Lanka, (hereinafter called and referred to as "the Lender" which term or expression as herein used shall where the context so requires or admits mean and include the said <b>BEANSTALK INVESTMENTS LTD,</b> theirs, executors, administrators and assigns of the One Part.</p>

        <p class=center><b><u>AND</u></b></p>

        <p><span style=\'background:yellow\'>[' . $get_personal_info['full_name'] . '] (holder of National Identity Card No.[' . $get_personal_info['cus_nic'] . ']) and [' . $get_personal_info['full_name'] . '] (holder of National Identity Card No. [' . $get_personal_info['cus_nic'] . ']) Both are residing at No. 43 1/1, Anula Road, Colombo 06 Directors of [' . $get_business_info->business_name . '] (Registered No: ' . $get_business_info->registration_number . ') at ' . $get_business_info->registered_address . '</span> (hereinafter called and referred to as "the Borrower" which term or expression as herein used shall where the context so requires or admits mean and include the said <b>' . $get_personal_info['full_name'] . '</b> & <b>' . $get_personal_info['full_name'] . '</b> and his, heirs, executors, administrators and assigns of the Other Part.</p>

        <p class=center><b><u>WITNESSETH</u></b></p>

        <p>WHEREAS the Borrower has requested form the Lender and the Lender has agreed to grant to the Borrower a loan in a sum of Rupees <span style=\'background:yellow\'>[' . $this->number_to_words($agreement['loan_tot_amount']) . ' ' . number_format($agreement['loan_tot_amount'], 0, '.', ',') . '/-)' . ']</span> upon the following terms and conditions;</p>

        <p>NOW THIS AGREEMENT WITNESSETH and the parties do hereby agree as follows:-</p>

        <ol>
          <li>The Lender has given to the Borrower and the Borrower has obtained from the Lender a total sum of Rupees <span style=\'background:yellow\'>[' . $this->number_to_words($agreement['loan_tot_amount']) . ' ' . number_format($agreement['loan_tot_amount'], 0, '.', ',') . '/-)' . ']</span> the receipt of which the Borrower hereby admits and acknowledges:</li>
          
          <li>This Agreement shall be valid and remains in force until the said principal sum of Rupees <span style=\'background:yellow\'>[' . $this->number_to_words($agreement['loan_tot_amount']) . ' ' . number_format($agreement['loan_tot_amount'], 0, '.', ',') . '/-)' . ']</span> and the interest thereon as hereinafter set out are finally paid and settled by the Borrower;</li>
          
          <li>The Borrower hereby agrees and undertake to repay the aforesaid principal sum of Rupees <span style=\'background:yellow\'>[' . $this->number_to_words($agreement['loan_tot_amount']) . ' ' . number_format($agreement['loan_tot_amount'], 0, '.', ',') . '/-)' . ']</span> with interest calculated thereon at the rate of <span style=\'background:yellow\'>[' . $this->number_to_words((int)$agreement['loan_interest']) . ' (' . $agreement['loan_interest'] . '%)]</span> per mensem, in <span style=\'background:yellow\'>[' . $agreement['loan_no_of_terms'] . ']</span> equal daily installments of <span style=\'background:yellow\'>[' . number_format($agreement['loan_term_amount'], 0, '.', ',') . '/-]</span> commencing from <span style=\'background:yellow\'>[' . $this->formatDateWithSuffix($agreement['loan_date']) . ' and Ending on ' . $this->formatDateWithSuffix($agreement['loan_close_date']) . ']</span>.</li>
          
          <li>In the event of default by the Borrower in duly paying installments as aforesaid, the Lender has the right to charge a penal interest of 10% per month on such overdue payments until payment in full.</li>
          
          <li>In the event of loan reschedule requested by me Beanstalk Investments Limited have right to charge 7% per month on such extensions. At the time of the execution hereof, borrower shall execute a promise note & new loan agreement in favour of lender with the extension charges at the office premises of Beanstalk Investments Limited.</li>
          
          <li>In the event that borrower failed to pay five agreed upon installments, Beanstalk Investments Ltd shall have the rights to terminate the agreement and demand immediate settlement of the total outstanding and indicate legal proceeding to recover the due.</li>
          
          <li>At the same time as the execution hereof, the Borrower shall execute a promissory note in favour of the Lender in the amount of LKR <span style=\'background:yellow\'>[450,000]</span>/-</li>
          
          <li>A Schedule showing the aforesaid payments due from the Borrower is appended hereto as follows:-</li>
        </ol>

        <p class=center><b><u>SCHEDULE</u></b></p>

        <table border="1" cellspacing="0" cellpadding="5" width="100%" style="margin: 0 auto;">
        <tr>
        <td width="10%"><b>NO</b></td>
        <td width="45%"><b>Date</b></td>
        <td width="45%"><b>Amount</b></td>
        </tr>';

        if (!empty($schedule)) {
            foreach ($schedule as $entry) {
                $html_content .= '
                <tr>
                <td>[' . $entry->term_no . ']</td>
                <td>[' . date('d-M-y', strtotime($entry->term_date)) . ']</td>
                <td>[' . number_format($entry->term_amount, 2) . ']</td>
                </tr>';
            }
        }

        $html_content .= '
        </table>

        <p>IN WITNESS WHEREOF the Lender and the Borrower have set their respective hands hereunto and to another at the place and on the date as hereinbefore mentioned.</p>

        <p class=left>Lender - ________________</p>
        <p class=left>Borrower- ________________</p>

        <p class=left><b><u>Witnesses</u></b></p>
        <p class=left>1. _________________________</p>
        <p class=left>2. _________________________</p>

        </div>
        </body>
        </html>';

        echo $html_content;
        exit;
    }

    function formatDateWithSuffix($date)
    {
        $timestamp = strtotime($date);
        $day = date('j', $timestamp);
        $month = date('F', $timestamp);
        $year = date('Y', $timestamp);

        // Add day suffix (st, nd, rd, th)
        if ($day % 10 == 1 && $day != 11) {
            $suffix = 'st';
        } elseif ($day % 10 == 2 && $day != 12) {
            $suffix = 'nd';
        } elseif ($day % 10 == 3 && $day != 13) {
            $suffix = 'rd';
        } else {
            $suffix = 'th';
        }

        return $day . $suffix . ' of ' . $month . ' ' . $year;
    }

    // Alternative function with dynamic data parameters
    public function generate_custom_promissory_note($data = array())
    {
        // Set headers to force download as a Word document
        header("Content-type: application/vnd.ms-word");
        header("Content-Disposition: attachment; filename=Custom_Promissory_Note.doc");

        // Default values
        $default_data = array(
            'borrower_name' => '[YOUR NAME HERE]',
            'borrower_nic' => '[YOUR NIC HERE]',
            'co_borrower_name' => '[CO-BORROWER NAME]',
            'co_borrower_nic' => '[CO-BORROWER NIC]',
            'company_name' => '[YOUR COMPANY NAME]',
            'company_reg_no' => 'PV00284492',
            'address' => 'No. 43 1/1, Anula Road, Colombo 06',
            'amount' => 'Four Hundred Fifty Thousand (LKR 450,000/-)',
            'interest_rate' => 'Six (6%)',
            'installments' => '50',
            'installment_amount' => '9,000/-',
            'start_date' => '10th of September 2025',
            'end_date' => '08th of November 2025',
            'agreement_date' => 'Ninth (09th) Day of September'
        );

        // Merge with provided data
        $data = array_merge($default_data, $data);

        // Generate HTML content with dynamic data
        $html_content = $this->load->view('promissory_note_template', $data, TRUE);

        echo $html_content;
        exit;
    }
}
