<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Management extends CI_Controller {

    var $main_menu_name = "loan";
	var $sub_menu_name = "list_loan";

	public function __construct()
	{
		parent::__construct();

		$this->load->model('Management_Model');
		$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('Holiday_Model');
		date_default_timezone_set('asia/colombo');		
	}
	
	//undifine index
	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 pending_approval()
	{		 
		$data['main_menu_name'] = "loan_approval";
		$data['sub_menu_name'] = "approval_penidng_loan";
        $this->load->view('management_approval_penidng_loan',$data);
	}	  
	  
	  public function get_list_loan_pending_approval($value='')
	{		
		$wareh_id='';
		if($this->session->userdata('ss_group_id')==2){			
		}else {
			$wareh_id=$this->session->userdata('ss_warehouse_id');
		}
	        $values = $this->Management_Model->getLoan(0);
			$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, '.', ',');																				
					$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"></i> Loan Details</a></li>
							<li><a href="#" onClick="approval('.$users->loan_id.')"><i class="fa fa-edit"></i> Approval</a></li>
							<li><a href="#" onClick="reject('.$users->loan_id.')"><i class="fa fa-edit"></i> Reject</a></li>	
							   <li><a href="' . base_url() . 'loan/loan_modify/' . $users->loan_id . '"><i class="fa fa-edit"></i> Update Loan Details</a></li>								
                       </ul></div>';										
				$row[]=$row_action;				
				$data[] = $row;
	            }
	            $output = array('data' =>$data);
	            echo json_encode($output);
	        }else{
	            $output = array('data' =>'');
	            echo json_encode($output);
	        }
	   }
	   
	   
	   
	   //-------------------------------------------------------------
	   
	   
	public function approved_loan()
	{		 
		$data['main_menu_name'] = "loan_approval";
		$data['sub_menu_name'] = "approved_loan";
        $this->load->view('management_approved_loan',$data);
	}	  
	  
	public function get_list_loan_approved($value='')
	{		
		
		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');
		}
		 $start            = $this->input->get('start');
    	 $length           = $this->input->get('length');
    	 $search           = $this->input->get('search');	
		 			
			$values = $this->Management_Model->getLoan_approved($wareh_id,$start,$length,$search['value']);
			$count = $this->Management_Model->getLoan_approved($wareh_id,"","",$search['value']);
			$totalData =$count;
			$totalFiltered = $totalData;  
	        
			$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, '.', ',');																				
					$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-file-text"></i> Loan Details</a></li>
							<li><a href="#" onClick="reject('.$users->loan_id.')"><i class="fa fa-ban"></i> Reject</a></li>
							<li><a href="#" onClick="delete_loan('.$users->loan_id.')"><i class="fa fa-trash-o"></i> Delete</a></li>
							 <li><a href="' . base_url() . 'loan/loan_modify/' . $users->loan_id . '"><i class="fa fa-edit"></i> Update Loan Details</a></li>
							 
							  <li><a href="' . base_url() . 'management/loan_details/' . $users->loan_id . '"><i class="fa fa-edit"></i> Manage Loan payment & Panalty & Due</a></li>
									
                       </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); 
	        }
	   }
	   //-----------------------------------------------------------------
	   
	   
	   
	   function change_approval_status()
	   {
		   $loan_id=$this->input->get('id');
		   $status=$this->input->get('status');	
		   $user_id=$this->session->userdata('ss_user_id');	
		   date_default_timezone_set('asia/colombo');
		   $date_time=date('Y-m-d H:i:s');
		   $comment=$this->input->get('comment');	   
		   
		   $data=array(
		   'approval_by'=>$user_id,
		   'approval_status'=>$status,
		   'approval_date_time'=>$date_time,
		   'approval_comment'=>$comment,
		   'loan_issue_status'=>1		   
		   );
		   		     
		  $result=$this->Management_Model->update_aproval_status($loan_id,$data);
		  
		  if($result==1)
		  {
			$json_data=array('id'=>$loan_id,'error'=>'0','message'=>'Approved Successfully'); 
		  }
		  else
		  {
			$json_data=array('id'=>$loan_id,'error'=>'1','message'=>'Error !');  
		  }
		  
		  echo json_encode($json_data);
		   
	   }
	   
	   //-------------------------------------------------------------------
	   
	   
	   
	   public function rejected_loan()
	{		 
		$data['main_menu_name'] = "loan_approval";
		$data['sub_menu_name'] = "rejected_loan";
        $this->load->view('management_rejected_loan',$data);
	}	  
	  
	public function get_list_loan_rejected($value='')
	{		
		$wareh_id='';
		if($this->session->userdata('ss_group_id')==10){			
		}else {
			$wareh_id=$this->session->userdata('ss_warehouse_id');
		}
	        $values = $this->Management_Model->getLoan_rejected(0);
			$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 label-danger">Reject</span>';
						}						
					$row[] = $app_status;	
					$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-file-text"></i> Loan Details</a></li>
							<li><a href="#" onClick="approval('.$users->loan_id.')"><i class="fa fa-file-text"></i> Approval</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 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;	
					}
					
					
					$data['arreas_amount']=$oustanding_value;
              
        $this->load->view('loan_management', $data);
    }
	
	 public function delete_payment()
    {
        $paymnt_id = $this->input->post('id');
       
        if ($this->Management_Model->delete_payment($paymnt_id)) {
            $st = array(
                'status' => 1,
                'validation' => 'Done!'
            );
            echo json_encode($st);
        }
       
    }
	
	public function delete_panalty()
    {
		$this->load->model('Loan_Payment_Received_Model');
		
		$id = $this->input->post('id');		
		$loan=$this->Management_Model->get_panalty_loan_id($id);		
		if(isset($loan['loan_id'])){
		$loan_id=$loan['loan_id'];			
		}
		else{
		$loan_id='';	
		}
		//-------------------------------------------------			
        if ($this->Management_Model->delete_panalty($id)) {
            $st = array(
                'status' => 1,
                'validation' => 'Done!'
            );
            echo json_encode($st);
        }
		else
		{
		$st = array(
                'status' => 10,
                'validation' => 'Error!'
            );
            echo json_encode($st);	
			
		}
		//-------------------------------------------------	
		if($loan_id){
		$total_panalty = $this->Loan_Payment_Received_Model->get_total_panalty_by_loan_id($loan_id);
		$total_paid_panalty = $this->Loan_Payment_Received_Model->get_total_paid_panalty_by_loan_id($loan_id);
		
		if(isset($total_panalty['panalty_amount']))
		{
		$total_panalty_amount= $total_panalty['panalty_amount'];			
		}
		else
		{
		$total_panalty_amount=0;	
		}		
		if(isset($total_paid_panalty['panalty_received']))
		{
		$total_paid_panalty_amount=$total_paid_panalty['panalty_received'];			
		}
		else
		{
		$total_paid_panalty_amount=0;	
		}
		}		
	//-----------------------------------
	$panalty_balance=$total_paid_panalty_amount-$total_panalty_amount;	
	
	
	if($panalty_balance>0)
	{
		//--------------------------------------------------------------
		
		//start : get_data from db relevent to loan
			$details_confirm = $this->Loan_Model->get_loan_details_by_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);			
			$total_paid_capital=$this->Loan_Payment_Received_Model->get_total_paid_capital_by_loan_id($loan_id);
			$total_paid_interest=$this->Loan_Payment_Received_Model->get_total_paid_interest_by_loan_id($loan_id);
			//End : get_data from db relevent to loan
			//start:calculate currant recived capital and interest received %
			$tot_loan_amount=$details_confirm['loan_payable_total_amount'];
			$tot_paid_loan=$total_paid_loan['loan_received'];
			$tot_capital=$details_confirm['loan_tot_amount'];
			$tot_interest=$details_confirm['total_interest'];
			$tot_paid_capital=$total_paid_capital['capital_received'];
			$tot_paid_interest=$total_paid_interest['loan_interest_recived'];
			$tot_balance_capital=$tot_capital-$tot_paid_capital;
			$tot_balance_interest=$tot_interest-$tot_paid_interest;
			$tot_balance_loan=$tot_loan_amount-$tot_paid_loan;
			if($tot_balance_loan==0)
			{
			$temp_tot_balance_loan=1;	
			}
			else
			{
			$temp_tot_balance_loan=$tot_balance_loan;
			}					
			$capital_presentage=($tot_balance_capital/$temp_tot_balance_loan)*100;
			$interest_presentage=($tot_balance_interest/$temp_tot_balance_loan)*100;		
			//end:calculate currant recived capital and interest received %				
			
			$total_loan_payment=$panalty_balance;
				//start : cal capital and interest payment amount
				$loan_capital_payment=round(($total_loan_payment/100)*$capital_presentage,2);
				$loan_interest_payment=round(($total_loan_payment/100)*$interest_presentage,2);
				$loan_excess_payment=$total_loan_payment-$loan_capital_payment-$loan_interest_payment;	
				//end : cal capital and interest payment amount
				
				$reduce_panalty=$panalty_balance*-1;			
		
		$data=array(
			'loan_id'=>$loan_id, 
			'cus_id'=>$details_confirm['cus_id'],
			'warehouse_id'=>$details_confirm['warehouse_id'],
			'route_id'=>$details_confirm['route_id'],
			'pymnt_paying_by'=>"Cash",
			'pymnt_date_time'=>date("Y-m-d"),			
			'pymnt_amount'=>0,			
			'pymnt_added_date_time'=>date("Y-m-d H:i:s"),
			'user_id'=>$this->session->userdata('ss_user_id'),	
			'pymnt_collected'=>1,
			'pymnt_deposited'=>1,
			'panalty_received'=>$reduce_panalty,
			'due_received'=>0,
			'loan_received'=>$total_loan_payment,
			'excess_received'=>0,
			'capital_received'=>$loan_capital_payment,
			'loan_interest_recived'=>$loan_interest_payment,
			'pymnt_ref_no'=>$this->Common_Model->gen_ref_number('paymnt_id','loan_payment','RCPT/'),
			'pymnt_note'=>"Panalty Automatic balance for delete panalty amount: ".$panalty_balance,
			'tracking_number'=>"DPAB:".$id				
			);						
			$result1=$this->Loan_Payment_Received_Model->save_loan_payment($data);	
		
		//-------------------------------------------------------------
	}
       
    }
	
	public function delete_due()
    {
		$this->load->model('Loan_Payment_Received_Model');
        $id = $this->input->post('id');
		$loan=$this->Management_Model->get_due_loan_id($id);		
		if(isset($loan['loan_id'])){
		$loan_id=$loan['loan_id'];			
		}
		else{
		$loan_id='';	
		}
		//-------------------------------------------------		
       
        if ($this->Management_Model->delete_due($id)) {
            $st = array(
                'status' => 1,
                'validation' => 'Done!'
            );
            echo json_encode($st);
        }
		//-------------------------------------------------	
		if($loan_id)
		{
			$total_due=$this->Loan_Payment_Received_Model->get_total_due_by_loan_id($loan_id);	
			$total_paid_due=$this->Loan_Payment_Received_Model->get_total_paid_due_by_loan_id($loan_id);
			if(isset($total_due['due_amount']))
			{
				$total_due_amount= $total_due['due_amount'];			
			}
			else
			{
				$total_due_amount=0;	
			}		
			if(isset($total_paid_due['due_received']))
			{
				$total_paid_due_amount=$total_paid_due['due_received'];			
			}
			else
			{
				$total_paid_due_amount=0;	
			}
		} 		
	//-----------------------------------
	$due_balance=$total_paid_due_amount-$total_due_amount;

		if($due_balance>0)
	{
		//--------------------------------------------------------------
		
		//start : get_data from db relevent to loan
			$details_confirm = $this->Loan_Model->get_loan_details_by_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);			
			$total_paid_capital=$this->Loan_Payment_Received_Model->get_total_paid_capital_by_loan_id($loan_id);
			$total_paid_interest=$this->Loan_Payment_Received_Model->get_total_paid_interest_by_loan_id($loan_id);
			//End : get_data from db relevent to loan
			//start:calculate currant recived capital and interest received %
			$tot_loan_amount=$details_confirm['loan_payable_total_amount'];
			$tot_paid_loan=$total_paid_loan['loan_received'];
			$tot_capital=$details_confirm['loan_tot_amount'];
			$tot_interest=$details_confirm['total_interest'];
			$tot_paid_capital=$total_paid_capital['capital_received'];
			$tot_paid_interest=$total_paid_interest['loan_interest_recived'];
			$tot_balance_capital=$tot_capital-$tot_paid_capital;
			$tot_balance_interest=$tot_interest-$tot_paid_interest;
			$tot_balance_loan=$tot_loan_amount-$tot_paid_loan;
			if($tot_balance_loan==0)
			{
			$temp_tot_balance_loan=1;	
			}
			else
			{
			$temp_tot_balance_loan=$tot_balance_loan;
			}					
			$capital_presentage=($tot_balance_capital/$temp_tot_balance_loan)*100;
			$interest_presentage=($tot_balance_interest/$temp_tot_balance_loan)*100;		
			//end:calculate currant recived capital and interest received %				
			
			$total_loan_payment=$due_balance;
				//start : cal capital and interest payment amount
				$loan_capital_payment=round(($total_loan_payment/100)*$capital_presentage,2);
				$loan_interest_payment=round(($total_loan_payment/100)*$interest_presentage,2);
				$loan_excess_payment=$total_loan_payment-$loan_capital_payment-$loan_interest_payment;	
				//end : cal capital and interest payment amount
				
				$reduce_due=$due_balance*-1;			
		
		$data=array(
			'loan_id'=>$loan_id, 
			'cus_id'=>$details_confirm['cus_id'],
			'warehouse_id'=>$details_confirm['warehouse_id'],
			'route_id'=>$details_confirm['route_id'],
			'pymnt_paying_by'=>"Cash",
			'pymnt_date_time'=>date("Y-m-d"),			
			'pymnt_amount'=>0,			
			'pymnt_added_date_time'=>date("Y-m-d H:i:s"),
			'user_id'=>$this->session->userdata('ss_user_id'),	
			'pymnt_collected'=>1,
			'pymnt_deposited'=>1,
			'panalty_received'=>0,
			'due_received'=>$reduce_due,
			'loan_received'=>$total_loan_payment,
			'excess_received'=>0,
			'capital_received'=>$loan_capital_payment,
			'loan_interest_recived'=>$loan_interest_payment,
			'pymnt_ref_no'=>$this->Common_Model->gen_ref_number('paymnt_id','loan_payment','RCPT/'),
			'pymnt_note'=>"Due Automatic balance for delete due amount: ".$due_balance,
			'tracking_number'=>"DDAB:".$id				
			);						
			$result1=$this->Loan_Payment_Received_Model->save_loan_payment($data);	
		
		//-------------------------------------------------------------
	}	
	
	}
       
   public function disable_panalty()
    {
		$id = $this->input->post('id');	
		if($id>0){	
		$result=$this->Management_Model->disable_panalty($id);
		}
		else{
			$result=0;
		}
		
		 if ($result==1) {
            $st = array(
                'status' => 1,
                'validation' => 'Updated'
            );
            echo json_encode($st);
        }
		else
		{
			 $st = array(
                'status' => 0,
                'validation' => 'Error!. Please contact administrator'
            );
            echo json_encode($st);			
		}		
	}
	
	public function enable_panalty()
    {
		$id = $this->input->post('id');	
		if($id>0){	
		$result=$this->Management_Model->enable_panalty($id);
		}
		else{
			$result=0;
		}
		
		 if ($result==1) {
            $st = array(
                'status' => 1,
                'validation' => 'Updated'
            );
            echo json_encode($st);
        }
		else
		{
			 $st = array(
                'status' => 0,
                'validation' => 'Error!. Please contact administrator'
            );
            echo json_encode($st);			
		}		
	}
	
	
	  public function disable_due()
    {
		$id = $this->input->post('id');	
		if($id>0){	
		$result=$this->Management_Model->disable_due($id);
		}
		else{
			$result=0;
		}
		
		 if ($result==1) {
            $st = array(
                'status' => 1,
                'validation' => 'Updated'
            );
            echo json_encode($st);
        }
		else
		{
			 $st = array(
                'status' => 0,
                'validation' => 'Error!. Please contact administrator'
            );
            echo json_encode($st);			
		}		
	}
	
	public function enable_due()
    {
		$id = $this->input->post('id');	
		if($id>0){	
		$result=$this->Management_Model->enable_due($id);
		}
		else{
			$result=0;
		}
		
		 if ($result==1) {
            $st = array(
                'status' => 1,
                'validation' => 'Updated'
            );
            echo json_encode($st);
        }
		else
		{
			 $st = array(
                'status' => 0,
                'validation' => 'Error!. Please contact administrator'
            );
            echo json_encode($st);			
		}		
	}
	
	public function reduce_p_penalty()
    {
		$this->load->model('Loan_Payment_Received_Model');
		$this->load->model('Loan_Panalty_Process_Model');				
		$loan_id = $this->input->post('loan_id');	
		$red_p_panalty = $this->input->post('red_p_panalty');
		$msg="Error!";
		$error=1;
		$status=0;				
		//-------------------------------------------------	
		if($loan_id){			
			$total_panalty = $this->Loan_Payment_Received_Model->get_total_panalty_by_loan_id($loan_id);
			$total_paid_panalty = $this->Loan_Payment_Received_Model->get_total_paid_panalty_by_loan_id($loan_id);
		
			if(isset($total_panalty['panalty_amount']))
			{
			$total_panalty_amount= $total_panalty['panalty_amount'];			
			}
			else
			{
			$total_panalty_amount=0;	
			}		
			if(isset($total_paid_panalty['panalty_received']))
			{
			$total_paid_panalty_amount=$total_paid_panalty['panalty_received'];			
			}
			else
			{
			$total_paid_panalty_amount=0;	
			}
		}		
	//-----------------------------------
	if($loan_id)
	{
	$panalty_balance=$total_panalty_amount-$total_paid_panalty_amount;			
	}
	else
	{
	$total_panalty_amount=0;
	$total_paid_panalty_amount=0;
	$panalty_balance=0;	
	}		
	if($total_paid_panalty_amount>0&&$total_paid_panalty_amount>=$red_p_panalty&&$red_p_panalty>0)
	{
		//--------------------------------------------------------------		
		//start : get_data from db relevent to loan
			$details_confirm = $this->Loan_Model->get_loan_details_by_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);			
			$total_paid_capital=$this->Loan_Payment_Received_Model->get_total_paid_capital_by_loan_id($loan_id);
			$total_paid_interest=$this->Loan_Payment_Received_Model->get_total_paid_interest_by_loan_id($loan_id);
			//End : get_data from db relevent to loan
			//start:calculate currant recived capital and interest received %
			$tot_loan_amount=$details_confirm['loan_payable_total_amount'];
			$tot_paid_loan=$total_paid_loan['loan_received'];
			$tot_capital=$details_confirm['loan_tot_amount'];
			$tot_interest=$details_confirm['total_interest'];
			$tot_paid_capital=$total_paid_capital['capital_received'];
			$tot_paid_interest=$total_paid_interest['loan_interest_recived'];
			$tot_balance_capital=$tot_capital-$tot_paid_capital;
			$tot_balance_interest=$tot_interest-$tot_paid_interest;
			$tot_balance_loan=$tot_loan_amount-$tot_paid_loan;
			if($tot_balance_loan==0)
			{
			$temp_tot_balance_loan=1;	
			}
			else
			{
			$temp_tot_balance_loan=$tot_balance_loan;
			}					
			$capital_presentage=($tot_balance_capital/$temp_tot_balance_loan)*100;
			$interest_presentage=($tot_balance_interest/$temp_tot_balance_loan)*100;		
			//end:calculate currant recived capital and interest received %				
			$total_loan_payment=$red_p_panalty;
				//start : cal capital and interest payment amount
				$loan_capital_payment=round(($total_loan_payment/100)*$capital_presentage,2);
				$loan_interest_payment=round(($total_loan_payment/100)*$interest_presentage,2);
				$loan_excess_payment=$total_loan_payment-$loan_capital_payment-$loan_interest_payment;	
				//end : cal capital and interest payment amount				
				$reduce_panalty=$panalty_balance*-1;		
		$data=array(
			'loan_id'=>$loan_id, 
			'cus_id'=>$details_confirm['cus_id'],
			'warehouse_id'=>$details_confirm['warehouse_id'],
			'route_id'=>$details_confirm['route_id'],
			'pymnt_paying_by'=>"Cash",
			'pymnt_date_time'=>date("Y-m-d"),			
			'pymnt_amount'=>0,			
			'pymnt_added_date_time'=>date("Y-m-d H:i:s"),
			'user_id'=>$this->session->userdata('ss_user_id'),	
			'pymnt_collected'=>1,
			'pymnt_deposited'=>1,
			'panalty_received'=>$red_p_panalty*-1,
			'due_received'=>0,
			'loan_received'=>$total_loan_payment,
			'excess_received'=>0,
			'capital_received'=>$loan_capital_payment,
			'loan_interest_recived'=>$loan_interest_payment,
			'pymnt_ref_no'=>$this->Common_Model->gen_ref_number('paymnt_id','loan_payment','PPDAD/'),
			'pymnt_note'=>"Panalty Automatic balance for reduce panalty amount: ".$red_p_panalty,
			//'tracking_number'=>"APPDAB:".$loan_id.""				
			);						
			$result1=$this->Loan_Payment_Received_Model->save_loan_payment($data);	
			
			if($result1==1)
			{
				$data_item=array
						(					
						'loan_id'=> $loan_id ,
						'panalty_amount'=>$red_p_panalty*-1 ,
						'warehouse_id'=>$details_confirm['warehouse_id']  ,
						'cus_id'=>$details_confirm['cus_id']  ,
						'route_id'=> $details_confirm['route_id'] ,
						'loan_payment_term'=>$details_confirm['loan_payment_term'] ,
						'payment_date'=>$add_date=date("Y-m-d H:i:s"),	
						'remark'=>" (Recuce Penalty by admin)"			
						);									
					$result=$this->Loan_Panalty_Process_Model->save_today_panalty($data_item);
					if($result==1)
					{
					$msg="Paid Penalty Recuced";
					$error=0;
					$status=1;						
					}
					else
					{
					$msg="Penalty process Fail. Please contact your system administrator!";
					$error=1;
					$status=0;						
					}
			}
			else
			{				
			$msg="Payment process Fail. Please contact your system administrator!";
			$error=1;
			$status=0;
			}		
		//-------------------------------------------------------------
	}
	else
	{		
	$msg="Error! Can't proceed! Panalty paid amount is Rs: ".$total_paid_panalty_amount." .But you give Rs: ".$red_p_panalty.""  ;
	$error=1;
	$status=0;	
	}	
	$st = array(
                'status' => $status,
                'validation' => $msg
            );
            echo json_encode($st);	
       
    }
	
	
	
	public function reduce_up_penalty()
    {
		$this->load->model('Loan_Payment_Received_Model');
		$this->load->model('Loan_Panalty_Process_Model');				
		$loan_id = $this->input->post('loan_id');	
		$red_up_panalty = $this->input->post('red_up_panalty');
		$msg="Error!";
		$error=1;
		$status=0;				
		//-------------------------------------------------	
		if($loan_id){			
			$total_panalty = $this->Loan_Payment_Received_Model->get_total_panalty_by_loan_id($loan_id);
			$total_paid_panalty = $this->Loan_Payment_Received_Model->get_total_paid_panalty_by_loan_id($loan_id);
		
			if(isset($total_panalty['panalty_amount']))
			{
			$total_panalty_amount= $total_panalty['panalty_amount'];			
			}
			else
			{
			$total_panalty_amount=0;	
			}		
			if(isset($total_paid_panalty['panalty_received']))
			{
			$total_paid_panalty_amount=$total_paid_panalty['panalty_received'];			
			}
			else
			{
			$total_paid_panalty_amount=0;	
			}
		}		
	//-----------------------------------
	if($loan_id)
	{
	$panalty_balance=$total_panalty_amount-$total_paid_panalty_amount;			
	}
	else
	{
	$total_panalty_amount=0;
	$total_paid_panalty_amount=0;
	$panalty_balance=0;	
	}
	$panalty_balance = round($panalty_balance, 2);		
	if($panalty_balance>0&&$panalty_balance>=$red_up_panalty&&$red_up_panalty>0)
	{
		//--------------------------------------------------------------		
		//start : get_data from db relevent to loan
			$details_confirm = $this->Loan_Model->get_loan_details_by_loan_id($loan_id);			
			$data_item=array
						(					
						'loan_id'=> $loan_id ,
						'panalty_amount'=>$red_up_panalty*-1 ,
						'warehouse_id'=>$details_confirm['warehouse_id']  ,
						'cus_id'=>$details_confirm['cus_id']  ,
						'route_id'=> $details_confirm['route_id'] ,
						'loan_payment_term'=>$details_confirm['loan_payment_term'] ,
						'payment_date'=>$add_date=date("Y-m-d H:i:s"),	
						'remark'=>" (Recuce Unpaid Penalty by admin)"			
						);									
					$result=$this->Loan_Panalty_Process_Model->save_today_panalty($data_item);
					if($result==1)
					{
					$msg="Paid Penalty Recuced";
					$error=0;
					$status=1;						
					}
					else
					{
					$msg="Penalty process Fail. Please contact your system administrator!";
					$error=1;
					$status=0;						
					}
			
		//-------------------------------------------------------------
	}
	else
	{		
	$msg="Error! Can't proceed! Panalty unpaid paid amount is Rs: ".$panalty_balance." .But you give Rs: ".$red_up_panalty.""  ;
	$error=1;
	$status=0;	
	}	
	$st = array(
                'status' => $status,
                'validation' => $msg
            );
            echo json_encode($st);	
       
    }
	
	
	
	
	
	
	public function reduce_p_due()
    {
		$this->load->model('Loan_Payment_Received_Model');
		$this->load->model('Loan_Due_Process_Model');				
		$loan_id = $this->input->post('loan_id');	
		$red_p_due = $this->input->post('red_p_due');
		$msg="Error!";
		$error=1;
		$status=0;				
		//-------------------------------------------------	
		if($loan_id)
		{
			$total_due=$this->Loan_Payment_Received_Model->get_total_due_by_loan_id($loan_id);	
			$total_paid_due=$this->Loan_Payment_Received_Model->get_total_paid_due_by_loan_id($loan_id);
			if(isset($total_due['due_amount']))
			{
				$total_due_amount= $total_due['due_amount'];			
			}
			else
			{
				$total_due_amount=0;	
			}		
			if(isset($total_paid_due['due_received']))
			{
				$total_paid_due_amount=$total_paid_due['due_received'];			
			}
			else
			{
				$total_paid_due_amount=0;	
			}
		} 		
	//-----------------------------------
	
	//-----------------------------------
	if($loan_id)
	{
	$due_balance=$total_due_amount-$total_paid_due_amount;			
	}
	else
	{
	$total_due_amount=0;
	$total_paid_due_amount=0;
	$due_balance=0;	
	}		
	if($total_paid_due_amount>0&&$total_paid_due_amount>=$red_p_due&&$red_p_due>0)
	{
	//--------------------------------------------------------------
		
		//start : get_data from db relevent to loan
			$details_confirm = $this->Loan_Model->get_loan_details_by_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);			
			$total_paid_capital=$this->Loan_Payment_Received_Model->get_total_paid_capital_by_loan_id($loan_id);
			$total_paid_interest=$this->Loan_Payment_Received_Model->get_total_paid_interest_by_loan_id($loan_id);
			//End : get_data from db relevent to loan
			//start:calculate currant recived capital and interest received %
			$tot_loan_amount=$details_confirm['loan_payable_total_amount'];
			$tot_paid_loan=$total_paid_loan['loan_received'];
			$tot_capital=$details_confirm['loan_tot_amount'];
			$tot_interest=$details_confirm['total_interest'];
			$tot_paid_capital=$total_paid_capital['capital_received'];
			$tot_paid_interest=$total_paid_interest['loan_interest_recived'];
			$tot_balance_capital=$tot_capital-$tot_paid_capital;
			$tot_balance_interest=$tot_interest-$tot_paid_interest;
			$tot_balance_loan=$tot_loan_amount-$tot_paid_loan;
			if($tot_balance_loan==0)
			{
			$temp_tot_balance_loan=1;	
			}
			else
			{
			$temp_tot_balance_loan=$tot_balance_loan;
			}					
			$capital_presentage=($tot_balance_capital/$temp_tot_balance_loan)*100;
			$interest_presentage=($tot_balance_interest/$temp_tot_balance_loan)*100;		
			//end:calculate currant recived capital and interest received %				
			
			$total_loan_payment=$red_p_due;
				//start : cal capital and interest payment amount
				$loan_capital_payment=round(($total_loan_payment/100)*$capital_presentage,2);
				$loan_interest_payment=round(($total_loan_payment/100)*$interest_presentage,2);
				$loan_excess_payment=$total_loan_payment-$loan_capital_payment-$loan_interest_payment;	
				//end : cal capital and interest payment amount
				
				$reduce_due=$red_p_due*-1;			
		
		$data=array(
			'loan_id'=>$loan_id, 
			'cus_id'=>$details_confirm['cus_id'],
			'warehouse_id'=>$details_confirm['warehouse_id'],
			'route_id'=>$details_confirm['route_id'],
			'pymnt_paying_by'=>"Cash",
			'pymnt_date_time'=>date("Y-m-d"),			
			'pymnt_amount'=>0,			
			'pymnt_added_date_time'=>date("Y-m-d H:i:s"),
			'user_id'=>$this->session->userdata('ss_user_id'),	
			'pymnt_collected'=>1,
			'pymnt_deposited'=>1,
			'panalty_received'=>0,
			'due_received'=>$reduce_due,
			'loan_received'=>$total_loan_payment,
			'excess_received'=>0,
			'capital_received'=>$loan_capital_payment,
			'loan_interest_recived'=>$loan_interest_payment,
			'pymnt_ref_no'=>$this->Common_Model->gen_ref_number('paymnt_id','loan_payment','DPDAD/'),
			'pymnt_note'=>"Paid Due reduce by admin amount: ".$reduce_due,
			//'tracking_number'=>"DDAB:".$id				
			);						
			$result1=$this->Loan_Payment_Received_Model->save_loan_payment($data);	
			
			if($result1==1)
			{
				$data_item=array(					
					'loan_id'=> $loan_id ,
					'due_amount'=>$reduce_due ,
					'warehouse_id'=>$details_confirm['warehouse_id']  ,
					'cus_id'=>$details_confirm['cus_id']  ,
					'route_id'=> $details_confirm['route_id'] ,
					'payment_term'=>$details_confirm['loan_payment_term'] 				
					);									
					$result=$this->Loan_Due_Process_Model->save_today_due($data_item);
					if($result==1)
					{
					$msg="Paid Due Recuced";
					$error=0;
					$status=1;						
					}
					else
					{
					$msg="Due process Fail. Please contact your system administrator!";
					$error=1;
					$status=0;						
					}
			}
			else
			{				
			$msg="Payment process Fail. Please contact your system administrator!";
			$error=1;
			$status=0;
			}		
		//-------------------------------------------------------------
	}
	else
	{		
	$msg="Error! Can't proceed! Due paid amount is Rs: ".$total_paid_due_amount." .But you give Rs: ".$red_p_due.""  ;
	$error=1;
	$status=0;	
	}	
	$st = array(
                'status' => $status,
                'validation' => $msg
            );
            echo json_encode($st);	
       
    }
	
	
public function reduce_up_due()
    {
		$this->load->model('Loan_Payment_Received_Model');
		$this->load->model('Loan_Due_Process_Model');				
		$loan_id = $this->input->post('loan_id');	
		$red_un_due = $this->input->post('red_un_due');
		$msg="Error!";
		$error=1;
		$status=0;				
		//-------------------------------------------------	
		if($loan_id)
		{
			$total_due=$this->Loan_Payment_Received_Model->get_total_due_by_loan_id($loan_id);	
			$total_paid_due=$this->Loan_Payment_Received_Model->get_total_paid_due_by_loan_id($loan_id);
			if(isset($total_due['due_amount']))
			{
				$total_due_amount= $total_due['due_amount'];			
			}
			else
			{
				$total_due_amount=0;	
			}		
			if(isset($total_paid_due['due_received']))
			{
				$total_paid_due_amount=$total_paid_due['due_received'];			
			}
			else
			{
				$total_paid_due_amount=0;	
			}
		} 		
	//-----------------------------------
	
	//-----------------------------------
	if($loan_id)
	{
	$due_balance=$total_due_amount-$total_paid_due_amount;			
	}
	else
	{
	$total_due_amount=0;
	$total_paid_due_amount=0;
	$due_balance=0;	
	}	
	$due_balance = round($due_balance, 2);	
	if($due_balance>0&&$due_balance>=$red_un_due&&$red_un_due>0)
	{
	//--------------------------------------------------------------		
		//start : get_data from db relevent to loan
			$details_confirm = $this->Loan_Model->get_loan_details_by_loan_id($loan_id);		
				$data_item=array(					
					'loan_id'=> $loan_id ,
					'due_amount'=>$red_un_due*-1 ,
					'warehouse_id'=>$details_confirm['warehouse_id']  ,
					'cus_id'=>$details_confirm['cus_id']  ,
					'route_id'=> $details_confirm['route_id'] ,
					'payment_term'=>$details_confirm['loan_payment_term'] 				
					);									
					$result=$this->Loan_Due_Process_Model->save_today_due($data_item);
					if($result==1)
					{
					$msg="Unpaid Due Recuced";
					$error=0;
					$status=1;						
					}
					else
					{
					$msg="Due process Fail. Please contact your system administrator!";
					$error=1;
					$status=0;						
					}		
		//-------------------------------------------------------------
	}
	else
	{		
	$msg="Error! Can't proceed! Due unpaid amount is Rs: ".$due_balance." .But you give Rs: ".$red_un_due.""  ;
	$error=1;
	$status=0;	
	}	
	$st = array(
                'status' => $status,
                'validation' => $msg
            );
            echo json_encode($st);	
       
    }
	
	
	
	public function adj_penalty_precentage()
    {				
		$loan_id = $this->input->post('loan_id');	
		$penalty_precentage = $this->input->post('penalty_precentage');
		$msg="Error!";
		$error=1;
		$status=0;				
	
	//-----------------------------------
	
	if($penalty_precentage>0&&$penalty_precentage<=100&&$loan_id>0)
	{
	//--------------------------------------------------------------		
		//start : get_data from db relevent to loan
					
				$data_item=array(					
					'panalty_presentage'=> $penalty_precentage ,		
					);									
					$result=$this->Management_Model->update_loan_table_common($loan_id,$data_item);
					if($result==1)
					{
					$msg="Penalty precentage Adjusted";
					$error=0;
					$status=1;						
					}
					else
					{
					$msg="Penalty precentage Adjuste process Fail. Please contact your system administrator!";
					$error=1;
					$status=0;						
					}		
		//-------------------------------------------------------------
	}
	else
	{		
	$msg="Error! Can't proceed! please check again"  ;
	$error=1;
	$status=0;	
	}	
	$st = array(
                'status' => $status,
                'validation' => $msg
            );
            echo json_encode($st);	
       
    }
	
	public function adj_due_precentage()
    {				
		$loan_id = $this->input->post('loan_id');	
		$due_precentage = $this->input->post('due_precentage');
		$msg="Error!";
		$error=1;
		$status=0;				
	
	//-----------------------------------
	
	if($due_precentage>0&&$due_precentage<=100&&$loan_id>0)
	{
	//--------------------------------------------------------------		
		//start : get_data from db relevent to loan
					
				$data_item=array(					
					'due_presentage'=>$due_precentage ,		
					);									
					$result=$this->Management_Model->update_loan_table_common($loan_id,$data_item);
					if($result==1)
					{
					$msg="Due due Adjusted";
					$error=0;
					$status=1;						
					}
					else
					{
					$msg="Penalty due Adjuste process Fail. Please contact your system administrator!";
					$error=1;
					$status=0;						
					}		
		//-------------------------------------------------------------
	}
	else
	{		
	$msg="Error! Can't proceed! please check again"  ;
	$error=1;
	$status=0;	
	}	
	$st = array(
                'status' => $status,
                'validation' => $msg
            );
            echo json_encode($st);	
       
    }
	  //-----------------------------------------------------------------
	   
	   
	   
	   function delete_loan()
	   {
		   $loan_id=$this->input->get('id');
		   $user_id=$this->session->userdata('ss_user_id');	
		   date_default_timezone_set('asia/colombo');
		   $date_time=date('Y-m-d H:i:s');
		   $comment=$this->input->get('comment');  
		  
		  $result1=$this->Management_Model->delete_all_due($loan_id);
		  $result2=$this->Management_Model->delete_all_penelty($loan_id);
		  $result3=$this->Management_Model->delete_all_payment($loan_id);
		  if($result1==1 && $result2==1 && $result3==1){
		  $result=$this->Management_Model->delete_loan($loan_id); 
		  }
		  else
		  {
			$result=0;  
		  }	  
		  if($result==1)
		  {
			$this->Common_Model->add_user_activitie("Delete_Loan LP".$loan_id."- Reason : ".$comment);
			$json_data=array('id'=>$loan_id,'error'=>'0','message'=>'Delete Successfully'); 			 
		  }
		  else
		  {
			$this->Common_Model->add_user_activitie("Delete_Loan_Fail LP".$loan_id);
			$json_data=array('id'=>$loan_id,'error'=>'1','message'=>'Error !');  
		  }		  
		  echo json_encode($json_data);		   
	   }
	   
	   //-------------------------------------------------------------------
	   
	//------- implemet 2021-12-20 sachith eranga on customer request (anura)
	function loan_close_manualy()
	   {
		   $loan_id=$this->input->get('id');
		   $status=$this->input->get('status');	
		   $user_id=$this->session->userdata('ss_user_id');	
		   date_default_timezone_set('asia/colombo');
		   $date_time=date('Y-m-d H:i:s');
		   $comment=$this->input->get('comment');
		   $data=array(
		   'close_by'=>$user_id,
		   'is_closed'=>1,
		   'system_close_date'=>$date_time,
		   'close_reason'=>$comment,
		   'manually_close_date_time'=>$date_time,
		   
		   );
		   		     
		  $result=$this->Management_Model->update_aproval_status($loan_id,$data);
		  
		  if($result==1)
		  {
			$json_data=array('id'=>$loan_id,'error'=>'0','message'=>'Successfully closed manually '); 
		  }
		  else
		  {
			$json_data=array('id'=>$loan_id,'error'=>'1','message'=>'Error !');  
		  }
		  
		  echo json_encode($json_data);
		   
	   }
	

}