<?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');
    }
    //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', $data);
    }
    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);
        }
        //echo $this->db->last_query();                                                  
        // $st = array('status' =>0);
        // 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_details_by_id($loan_id);
        $data['loan_panalty']       = $this->Loan_Panalty_Process_Model->get_loan_payments_by_loan_id($loan_id);
        $data['loan_due']           = $this->Loan_Due_Process_Model->get_loan_payments_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['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['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'));
		//$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);
					
					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;	
					}
					
					// If loan fully settled, no arrears
                    if (
                        $data['paid_summary']['loan_received'] >= $data['loan_details']->loan_payable_total_amount &&
                        $total_due['due_amount'] == 0 &&
                        $total_panalty['panalty_amount'] == 0
                    ) {
                        $oustanding_value = 0;
                    }
                    // Arrears should NEVER be negative
                    if ($oustanding_value < 0) {
                        $oustanding_value = 0;
                    }
					
					$data['arreas_amount']=$oustanding_value;
					
					
		
		//---------------------------------------------------------------
              
        $this->load->view('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);
    }
    //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['type']                  = 'add';
        $this->load->view('loan_add', $data);
    }
	
	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);
            } else {
                //no acsess
                redirect(base_url('dashboard'));
            }
        }
        $this->load->view('loan_modify', $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 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_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;
			//$total_days=$total_days-1;
            $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 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');
        $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);
        //$warehouse_code=$warehouse_dtls['code'];
        $loan_ref                  = "LP" . $ref_id_nxt;
        $error                     = false;
        $errtxt                    = '';
         if ($loan_payment_term == 1) {
            $total_days   = $loan_no_of_terms;
			//$total_days=$total_days-1;
            $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 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);
        //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); 
	        }
	   }
	   
	
	
	
}