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

class Loan_Payment_Received extends CI_Controller
{

	var $main_menu_name = "loan_payment_received";
	var $sub_menu_name = "";

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

		$this->load->model('Panalty_Model');
		$this->load->model('Loan_Payment_Received_Model');
		$this->load->model('Loan_Model');
		$this->load->model('Loan_Issue_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('Report_Loan_Model');
		date_default_timezone_set('asia/colombo');
		$this->load->helper('utility_helper');
	}

	//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 payment_pending_list()
	{
		$this->load->model('Route_Model');
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = "payment_pending_list";
		$data['payment_term_list'] = $this->Loan_Model->get_loan_payments_term();
		$data['routes_list'] = $this->Route_Model->get_all_active_routes();
		$this->load->view('payment_pending_list', $data);
	}



	public function get_payment_pending_list($value = '')
	{	//updated 2019-03-18	
		$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_Issue_Model->getLoan_approved_issued($wareh_id, $route, $payment_t, $start, $length, $search['value']);
		$count = $this->Loan_Issue_Model->getLoan_approved_issued($wareh_id, $route, $payment_t, "", "", $search['value']);
		$totalData = $count;
		$totalFiltered = $totalData;
		$columns = array();
		$data = array();
		//list panalty array start
		if (!empty($values)) {
			foreach ($values as $users) {
				$row = array();
				$loan_id = $users->loan_id;
				$payment_term = $users->loan_payment_term;
				$oustanding_value = 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);
				//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' => $users
				);
				//is_avalable_link(1, 1);
				$oustanding_value = common_outstanding_calculation($data2);
				// calcilation End ------------------------------------------------------------------					
				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;
				$last_panalty_details = $this->Loan_Payment_Received_Model->get_last_panalty_by_loan_id($loan_id);
				$panalty = $this->Panalty_Model->get_panalty_charge();
				$panalty_charge_total = $panalty_charge;
				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;
				}
				$due_balance = $due_charge - $paid_due_charge;
				$panlty_balance = $panalty_charge_total - $paid_panalty_charge;
				$total_need_to_pay = $users->loan_payable_total_amount + $panalty_charge_total + $due_charge;
				$row[] = '<a target="_blank" href="' . base_url() . 'loan/details/' . $users->loan_id . '">' . $users->loan_ref . '</a>';
				$row[] = $users->cus_name;
				$row[] = $users->loan_tot_amount;
				$row[] = $users->loan_payable_total_amount - $paid_loan_only;
				$row[] = $users->loan_term_amount;
				$row[] = $last_paid;
				$row[] = number_format($oustanding_value + $due_balance + $panlty_balance, 2, '.', ',');
				$row[] = $users->loan_date;
				$row[] = $users->loan_close_date;
				$row[] = $pTname;
				$clas = '';
				$row[] = $users->loan_no_of_terms;
				$loan_editable = false;
				$loan_editable = false;
				$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 target="_blank" href="' . base_url() . 'loan/details/' . $users->loan_id . '"> Loan Details</a></li>
						  <li><a target="_blank" href="' . base_url() . 'loan_payment_received/loan_payment/' . $users->loan_id . '"><i class="fa fa-file-text-o"></i> Pay Loan  </a></li>									
                       </ul></div>';
				$row[] = $row_action;
				$data[] = $row;
			}
			$json_data = array(
				//"draw"            => intval( $requestData['draw'] ),  
				"recordsTotal"    => intval($totalData),
				"recordsFiltered" => intval($totalFiltered),
				"data"            => $data
			);

			echo json_encode($json_data);
		} else {
			$json_data = array(
				//"draw"            => intval( $requestData['draw'] ),  
				"recordsTotal"    => intval(0),
				"recordsFiltered" => intval(0),
				"data"            => ""
			);
			echo json_encode($json_data);
		}
	}
	//-------------------------------------------------------------
	public function add_loan_payment()
	{	//not updated	 
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = "loan_payment";
		$data['loan_details'] = $this->Report_Loan_Model->get_all_loans();
		$loan_id = $this->uri->segment('3');
		if ($loan_id) {
			$data['details'] = $this->Loan_Model->get_loan_details_by_loan_id($loan_id);
			$data['terms'] = $this->Loan_Model->get_pendding_loan_terms_by_loan_id($loan_id);
			$data['loan_id'] = $loan_id;
			$today = date('Y-m-d');
			$users = $data['details'];
			$payment_term = $users['loan_payment_term'];
			$issue_amount = $this->Loan_Payment_Received_Model->get_loan_paid_total_by_loan_id($loan_id);

			if ($issue_amount['pymnt_amount'] > 0) {
				$data['pymnt_amount'] = $issue_amount['pymnt_amount'];
			} else {
				$data['pymnt_amount'] = 0;
			}
			$data['bank_list'] = $this->Bank_Model->get_all_bank();
			if ($payment_term == 3) {
				$loan_req_date = $users['loan_date'];
				$date1 = new DateTime($today);
				$date2 = new DateTime($loan_req_date);
				$diff = $date1->diff($date2);
				$mature_month = (($diff->format('%y') * 12) + $diff->format('%m'));
				$mature_month += 1;
				$loan_term_amount = $users['loan_term_amount'];
				$should_be_received_value = $loan_term_amount * $mature_month;
				$total_loan_amount = $users['loan_tot_amount'];
				if ($should_be_received_value > $total_loan_amount) {
					$should_be_received_value = $total_loan_amount;
				}
			}
			if ($payment_term == 1) {
				$date1 = date_create($users['loan_date']);
				$date2 = date_create($today);
				$diff = date_diff($date1, $date2);
				$days = $diff->format("%a");
				$mature_days = $days + 1;
				$loan_term_amount = $users['loan_term_amount'];
				$should_be_received_value = $loan_term_amount * $mature_days;
				$total_loan_amount = $users['loan_tot_amount'];
				if ($should_be_received_value > $total_loan_amount) {
					$should_be_received_value = $total_loan_amount;
				}
			}
			if ($payment_term == 2) {
				$date1 = date_create($users['loan_date']);
				$date2 = date_create($today);
				$diff = date_diff($date1, $date2);
				$days = $diff->format("%a");
				$week = floor($days / 7);
				$mature_week = $week + 1;
				$loan_term_amount = $users['loan_term_amount'];
				$should_be_received_value = $loan_term_amount * $mature_week;
				$total_loan_amount = $users['loan_tot_amount'];
				if ($should_be_received_value > $total_loan_amount) {
					$should_be_received_value = $total_loan_amount;
				}
			}
			if ($payment_term == 4) {
				$d1 = new DateTime($today);
				$d2 = new DateTime($users['loan_date']);
				$diff = $d2->diff($d1);
				$year_diff = $diff->y;
				$mature_year = $year_diff;
				$loan_term_amount = $users['loan_term_amount'];
				$should_be_received_value = $loan_term_amount * $mature_year;
				$total_loan_amount = $users['loan_tot_amount'];
				if ($should_be_received_value > $total_loan_amount) {
					$should_be_received_value = $total_loan_amount;
				}
			}
			//------------------------------------------------------------------
			$outstanding = $should_be_received_value - $data['pymnt_amount'];
			$data['outstanding'] = $outstanding;
		}
		$this->load->view('loan/add_loan_payment', $data);
	}

	public function add_loan_collector_payment()
	{	//not updated	 
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = "loan_payment";
		$this->load->view('loan/add_loan_collector_payment', $data);
	}


	public function loan_payment()
	{	//not updated	 
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = "loan_payment";
		$loan_id = $this->uri->segment('3');
		$data['details'] = $this->Loan_Model->get_loan_details_by_loan_id($loan_id);
		$today = date('Y-m-d');
		$users = $data['details'];
		$payment_term = $users['loan_payment_term'];
		$issue_amount = $this->Loan_Payment_Received_Model->get_loan_paid_total_by_loan_id($loan_id);
		if ($issue_amount['pymnt_amount'] > 0) {
			$data['pymnt_amount'] = $issue_amount['pymnt_amount'];
		} else {
			$data['pymnt_amount'] = 0;
		}
		$data['bank_list'] = $this->Bank_Model->get_all_bank();
		if ($payment_term == 3) {
			$loan_req_date = $users['loan_date'];
			$date1 = new DateTime($today);
			$date2 = new DateTime($loan_req_date);
			$diff = $date1->diff($date2);
			$mature_month = (($diff->format('%y') * 12) + $diff->format('%m'));
			$mature_month += 1;
			$loan_term_amount = $users['loan_term_amount'];
			$should_be_received_value = $loan_term_amount * $mature_month;
			$total_loan_amount = $users['loan_tot_amount'];
			if ($should_be_received_value > $total_loan_amount) {
				$should_be_received_value = $total_loan_amount;
			}
		}
		if ($payment_term == 1) {
			$date1 = date_create($users['loan_date']);
			$date2 = date_create($today);
			$diff = date_diff($date1, $date2);
			$days = $diff->format("%a");
			$mature_days = $days + 1;
			$loan_term_amount = $users['loan_term_amount'];
			$should_be_received_value = $loan_term_amount * $mature_days;
			$total_loan_amount = $users['loan_tot_amount'];
			if ($should_be_received_value > $total_loan_amount) {
				$should_be_received_value = $total_loan_amount;
			}
		}
		if ($payment_term == 2) {
			$date1 = date_create($users['loan_date']);
			$date2 = date_create($today);
			$diff = date_diff($date1, $date2);
			$days = $diff->format("%a");
			$week = floor($days / 7);
			$mature_week = $week + 1;
			$loan_term_amount = $users['loan_term_amount'];
			$should_be_received_value = $loan_term_amount * $mature_week;
			$total_loan_amount = $users['loan_tot_amount'];
			if ($should_be_received_value > $total_loan_amount) {
				$should_be_received_value = $total_loan_amount;
			}
		}
		if ($payment_term == 4) {
			$d1 = new DateTime($today);
			$d2 = new DateTime($users['loan_date']);
			$diff = $d2->diff($d1);
			$year_diff = $diff->y;
			$mature_year = $year_diff;
			$loan_term_amount = $users['loan_term_amount'];
			$should_be_received_value = $loan_term_amount * $mature_year;
			$total_loan_amount = $users['loan_tot_amount'];
			if ($should_be_received_value > $total_loan_amount) {
				$should_be_received_value = $total_loan_amount;
			}
		}
		//------------------------------------------------------------------
		$outstanding = $should_be_received_value - $data['pymnt_amount'];
		$data['outstanding'] = $outstanding;
		$this->load->view('loan_payment_update', $data);
	}



	public function get_list_loan_paid_amount_details_by_loan_id()
	{
		$loan_id = $this->input->get('id');
		$values = $this->Loan_Payment_Received_Model->getLoan_paid_list($loan_id);
		$columns = array();
		$data = array();
		if (!empty($values)) {
			foreach ($values as $users) {
				$row = array();
				$loan_id = $users->loan_id;
				$row[] = $users->paymnt_id;
				$row[] = $users->pymnt_ref_no;
				$row[] = date('Y-m-d', strtotime($users->pymnt_date_time));
				$row[] = $users->pymnt_paying_by;
				$row[] = $users->pymnt_amount;
				if ($users->pymnt_paying_by == "Cheque") {
					$row[] = $users->pymnt_cheque_no;
					$row[] = $users->pymnt_cheque_date;

					if ($users->pymnt_deposited == 0) {
						$row[] = "No";
					} else {
						$row[] = "Yes";
					}

					if ($users->pymnt_returned == 0) {
						$row[] = "No";
					} else {
						$row[] = "Yes";
					}
				}
				if ($users->pymnt_paying_by == "Cash") {
					$row[] = "";
					$row[] = "";
					$row[] = "";
					$row[] = "";
				}
				$row[] = $users->user_first_name;
				$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"> 
                       </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);
		}
	}
	//-----------------------------------------------------------------

	function update_pay_loan_details()
	{



		$loan_id = $this->input->post('loan_id');
		$cus_id = $this->input->post('cus_id');
		$route_id = $this->input->post('route_id');
		$warehouse_id = $this->input->post('warehouse_id');
		$payment_type = $this->input->post('payment_type');
		$loan_issue_date = $this->input->post('loan_issue_date');
		$cheqe_number = $this->input->post('cheqe_number');
		$chque_date = $this->input->post('chque_date');
		$contact_no = $this->input->post('contact_no');
		$issue_bank = $this->input->post('issue_bank');
		$issue_brnach = $this->input->post('issue_brnach');
		$amount = $this->input->post('amount');
		$loan_term_id = ($this->input->post('loan_term_id')) ? $this->input->post('loan_term_id') : 0;
		$reason       = $this->input->post('reason');
		$not_collected       = $this->input->post('not_collected');
		if ($not_collected) {
			$response = $this->Loan_Payment_Received_Model->mark_term_not_collected($loan_id, $loan_term_id, $reason);
			if ($response) {
				echo json_encode(array('loan_id' => $loan_id, 'error' => 0, 'msg' => 'Successfuly Saved'));
			} else {
				echo json_encode(array('loan_id' => $loan_id, 'error' => 1, 'msg' => 'Error'));
			}
			exit;
		}


		$payee = $this->input->post('payee');
		if (!$loan_issue_date) {
			$loan_issue_date = date("Y-m-d H:i:s");
		}
		//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 %			
		//start : validation amounts
		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 ($paid['pymnt_amount'] > 0) {
			$paid_amount = $paid['pymnt_amount'];
		} else {
			$paid_amount = 0;
		}
		//END : validation amounts			
		// start : cal due and panalty payment 			
		$panalty_balance = $panalty_charge - $paid_panalty_charge;
		$due_balance = $due_charge - $paid_due_charge;
		$currant_amount_balance = $amount;
		$total_loan_payment = 0;
		$due_payment = 0;
		$panalty_payment = 0;
		$loan_capital_payment = 0;
		$loan_interest_payment = 0;
		$loan_excess_payment = 0;
		//-------------------------------
		if ($amount > $due_balance) {
			$due_payment = $due_balance;
		} else {
			if ($amount > 0) {
				$due_payment = $amount;
			}
		}
		//-----------------------------------			
		$currant_amount_balance = $currant_amount_balance - $due_payment;
		if ($currant_amount_balance > $panalty_balance) {
			$panalty_payment = $panalty_balance;
		} else {
			if ($amount > 0) {
				$panalty_payment = $currant_amount_balance;
			}
		}
		$currant_amount_balance = $currant_amount_balance - $panalty_payment;
		// end : cal due and panalty payment 
		//start : cal loan payment

		if ($currant_amount_balance > 0) {
			$total_loan_payment = $currant_amount_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			
		}
		//end : cal loan payment			
		$c_pybl_total = $details_confirm['loan_payable_total_amount'] + $panalty_balance + $due_balance;
		$check = $c_pybl_total - $tot_paid_loan;
		if ($amount <= $check + 1 && $amount > 0) {
			if ($payment_type == "Cheque") {
				$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' => $payment_type,
					'payment_term' => $details_confirm['loan_payment_term'],
					'pymnt_date_time' => date('Y-m-d', strtotime($loan_issue_date)),
					'pymnt_amount' => $amount,
					'pymnt_cheque_no' => $cheqe_number,
					'pymnt_cheque_date' => date('Y-m-d', strtotime($chque_date)),
					'cheque_payee' => $payee,
					'bank_id' => $issue_bank,
					'pymnt_branch' => $issue_brnach,
					'pymnt_added_date_time' => date("Y-m-d H:i:s"),
					'user_id' => $this->session->userdata('ss_user_id'),
					'pymnt_collected' => 1,
					'panalty_received' => $panalty_payment,
					'due_received' => $due_payment,
					'loan_received' => $total_loan_payment,
					'excess_received' => $loan_excess_payment,
					'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/'),
				);
			} else {
				$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' => $payment_type,
					'pymnt_date_time' => date('Y-m-d', strtotime($loan_issue_date)),
					'pymnt_amount' => $amount,
					'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' => $panalty_payment,
					'due_received' => $due_payment,
					'loan_received' => $total_loan_payment,
					'excess_received' => $loan_excess_payment,
					'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/'),
				);
			}
			$result1 = $this->Loan_Payment_Received_Model->save_loan_payment($data, $loan_term_id);
			//check whether loan is ready to close and if rady automatical close by the system
			$paid = $this->Loan_Payment_Received_Model->get_loan_paid_total_by_loan_id($loan_id);
			if ($paid['pymnt_amount'] > 0) {
				$paid_amount = $paid['pymnt_amount'];
			} else {
				$paid_amount = 0;
			}
			$tot_to_be_payable = $tot_loan_amount + $panalty_charge + $due_charge;
			$tot_to_be_pay_balance_amount = $tot_to_be_payable - $paid_amount;

			if ($tot_to_be_pay_balance_amount <= 0) {	//echo"done";
				$data = array('is_closed' => 1, 'system_close_date' => date("Y-m-d"));
				$result2 = $this->Loan_Payment_Received_Model->update_loan_close_status($loan_id, $data);
			}


			if ($result1['status']) {
				echo json_encode(array('loan_id' => $loan_id, 'error' => 0, 'msg' => 'Successfuly Saved'));
			} else {
				echo json_encode(array('loan_id' => $loan_id, 'error' => 1, 'msg' => $result1['message']));
			}
		} else {
			echo json_encode(array('loan_id' => $loan_id, 'error' => 2, 'msg' => 'Payment Amount not match with currant loan. Please check the Amount'));
		}
	}
	//-----------------------------------------------------------------	   


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

	public function get_list_loan_issued($value = '')
	{
		$wareh_id = '';
		if ($this->session->userdata('ss_group_id') == 2) {
		} else {
			$wareh_id = $this->session->userdata('ss_warehouse_id');
		}
		$values = $this->Loan_Issue_Model->getLoan_approved_issued(0);
		$columns = array();
		$data = array();
		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_Model->get_total_paid_by_loan_id($loan_id);
				$pay_st = "undifine";

				if ($users->loan_issue_status == 0) {
					$pay_st = '<span class="label label-yellow">Pending</span>';
				}

				if ($users->loan_issue_status == 1) {
					$pay_st = '<span class="label label-success">Issued</span>';
				}

				if ($users->loan_issue_status == 2) {
					$pay_st = '<span class="label label-info">Partial Issue</span>';
				}
				$row[] = $pay_st;
				$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($total_paid_amount, 2, '.', ',');
				$row[] = number_format($users->loan_tot_amount - $total_paid_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 . '"> Loan Details</a></li>
						  <li><a href="' . base_url() . 'loan_issue/issue_appeoval_loan/' . $users->loan_id . '"><i class="fa fa-file-text-o"></i> Issue The Loan  </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 payment_pending_list_cash_collect()
	{
		$this->load->model('Route_Model');
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = "payment_pending_list_cash";
		$data['payment_term_list'] = $this->Loan_Model->get_loan_payments_term();
		$data['routes_list'] = $this->Route_Model->get_all_active_routes();
		$this->load->view('payment_pending_list_cash', $data);
	}
	public function get_payment_pending_list_cash_collect($value = '')
	{
		$start            = $this->input->get('start');
		$length           = $this->input->get('length');
		$search           = $this->input->get('search');
		$route = $this->input->get('route');
		$payment_t = $this->input->get('payment_t');
		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_Issue_Model->getLoan_approved_issued($wareh_id, $route, $payment_t, $start, $length, $search['value']);
		$count = $this->Loan_Issue_Model->getLoan_approved_issued($wareh_id, $route, $payment_t, "", "", $search['value']);
		$totalData = $count;
		$totalFiltered = $totalData;

		$columns = array();
		$data = array();
		if (!empty($values)) {
			foreach ($values as $users) {
				$row = array();
				$loan_id = $users->loan_id;
				$payment_term = $users->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' => $users
				);
				$oustanding_value = common_outstanding_calculation($data2);
				// calcilation End ------------------------------------------------------------------
				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;
				//$last_panalty_details=$this->Loan_Payment_Received_Model->get_last_panalty_by_loan_id($loan_id);			
				$panalty = $this->Panalty_Model->get_panalty_charge();

				$panalty_charge_total = $panalty_charge;

				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;
				}
				$due_balance = $due_charge - $paid_due_charge;
				$panlty_balance = $panalty_charge_total - $paid_panalty_charge;
				$total_need_to_pay = $users->loan_payable_total_amount + $panalty_charge_total + $due_charge;

				$row[] = '<a target="_blank" href="' . base_url() . 'loan/details/' . $users->loan_id . '">' . $users->loan_ref . '</a>';
				$row[] = $users->cus_name;
				$row[] = $users->loan_tot_amount;
				$row[] = $users->loan_payable_total_amount - $paid_loan_only;
				$row[] = $users->loan_term_amount;
				$row[] = $last_paid;
				$row[] = number_format($oustanding_value + $due_balance + $panlty_balance, 2, '.', ',');
				$row[] = $users->loan_date;
				$row[] = $users->loan_close_date;
				$row[] = $pTname;
				$clas = '';
				$row[] = $users->loan_no_of_terms;
				$row[] = "<input type='text' id='pay_amount_" . $users->loan_id . "' name='pay_amount' value='0.00' >";

				$loan_editable = false;
				$loan_editable = false;
				//$row[] = number_format($oustanding_value+$due_balance+$panlty_balance, 2, '.', ',');					
				//$row[] = number_format($users->loan_payable_total_amount, 2, '.', ',');					
				//$row[]="<input type='text' id='pay_amount_".$users->loan_id."' name='pay_amount' value='0.00' >";					
				//$row[] =number_format($total_need_to_pay-$total_paid_amount, 2, '.', ',');																				
				$row_action = '<div class="btn-group text-left">                       
					 <button  class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button" onclick="payment_proceed(' . $users->loan_id . ')">Pay </button>														
                     </div>';
				$row[] = $row_action;
				$data[] = $row;
			}
			$json_data = array(
				//"draw"            => intval( $requestData['draw'] ),  
				"recordsTotal"    => intval($totalData),
				"recordsFiltered" => intval($totalFiltered),
				"data"            => $data
			);

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



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





	public function get_terms_by_date()
	{
		$date = $this->input->post('date');

		if (!$date) {
			echo json_encode([]);
			return;
		}

		/* -----------------------------------------------------
       1. LOAD TERMS DUE ON SELECTED DATE (ONLY PENDING)
    ----------------------------------------------------- */
		$this->db->select("
        t.term_id,
        t.loan_id,
        t.term_no,
        t.term_amount,
        t.term_date,
        t.delay_charge,
        l.loan_ref AS loan_code,
        bi.business_name AS cus_name
    ");

		$this->db->from('loan_terms t');
		$this->db->join('loan l', 'l.loan_id = t.loan_id', 'left');
		$this->db->join('customer c', 'c.cus_id = l.cus_id', 'left');
		$this->db->join('business_information bi', 'bi.customer_id = c.cus_id', 'left');

		$this->db->where('t.term_date', $date);
		$this->db->where('t.status', 'Pending');
		$this->db->where('l.approval_status', 1);
		$due_terms = $this->db->get()->result_array();


		/* -----------------------------------------------------
       2. LOAD DELAY CHARGE BALANCES
          Rules:
          ✅ status != Pending
          ✅ delay_charge > 0
          ✅ Group by loan_id
    ----------------------------------------------------- */
		$term_delay = $this->db->select("
				t.loan_id,
				l.loan_ref AS loan_code,
				bi.business_name AS cus_name,
				SUM(t.delay_charge) AS term_delay_charge
			", false)
			->from('loan_terms t')
			->join('loan l', 'l.loan_id = t.loan_id', 'left')
			->join('customer c', 'c.cus_id = l.cus_id', 'left')
			->join('business_information bi', 'bi.customer_id = c.cus_id', 'left')
			->where('t.status !=', 'Pending')
			->where('t.delay_charge >', 0)
			->where('l.is_closed', 0)
			->group_by('t.loan_id')
			->get()->result_array();

		$paid_delay = $this->db->select("
				ldcp.loan_id,
				SUM(ldcp.delay_amount) AS paid_delay_charge
			", false)
			->from('loan_delay_charge_payments ldcp')
			->join('loan l', 'l.loan_id = ldcp.loan_id', 'inner')   // join loan table
			->where('l.is_closed', 0)                                // only open loans
			->group_by('ldcp.loan_id')
			->get()
			->result_array();

		$paid_map = [];
		foreach ($paid_delay as $p) {
			$paid_map[$p['loan_id']] = (float)$p['paid_delay_charge'];
		}
		$arrears = $this->db->select("
				la.loan_id,
				l.loan_ref AS loan_code,
				bi.business_name AS cus_name,
				SUM(la.arrears_charge) AS arrears_charge
			", false)
			->from('loan_arrears la')
			->join('loan l', 'l.loan_id = la.loan_id', 'inner')
			->join('customer c', 'c.cus_id = l.cus_id', 'left')
			->join('business_information bi', 'bi.customer_id = c.cus_id', 'left')
			->where('l.is_closed', 0)
			->group_by('la.loan_id')
			->get()->result_array();

		$data = [];
		// Term delay
		foreach ($term_delay as $row) {
			$loan_id = $row['loan_id'];

			$data[$loan_id] = [
				'loan_id'           => $loan_id,
				'loan_code'         => $row['loan_code'],
				'cus_name'          => $row['cus_name'],
				'term_delay_charge' => (float)$row['term_delay_charge'],
				'arrears_charge'    => 0,
				'paid_delay_charge' => $paid_map[$loan_id] ?? 0,
			];
		}
		//echo '<pre>',print_r($data);

		// Arrears merge
		foreach ($arrears as $row) {
			$loan_id = $row['loan_id'];

			if (!isset($data[$loan_id])) {
				$data[$loan_id] = [
					'loan_id'           => $loan_id,
					'loan_code'         => $row['loan_code'],
					'cus_name'          => $row['cus_name'],
					'term_delay_charge' => 0,
					'arrears_charge'    => (float)$row['arrears_charge'],
					'paid_delay_charge' => $paid_map[$loan_id] ?? 0,
				];
			} else {
				$data[$loan_id]['arrears_charge'] = (float)$row['arrears_charge'];
			}
		}

		//echo '<pre>',print_r($data);

		$final_delay_charges = [];

		foreach ($data as $row) {
			$total = $row['term_delay_charge'] + $row['arrears_charge'];
			$balance = $total - $row['paid_delay_charge'];

			if ($balance <= 0) continue;

			$final_delay_charges[] = [
				'loan_id'              => $row['loan_id'],
				'loan_code'            => $row['loan_code'],
				'cus_name'             => $row['cus_name'],
				'total_delay_charge'   => $total,
				'paid_delay_charge'    => $row['paid_delay_charge'],
				'balance_delay_charge' => $balance
			];
		}

		/* -----------------------------------------------------
           3. ARREARS (Overdue loans with balance)
        ----------------------------------------------------- */
		$today = date('Y-m-d');

		$this->db->select("
            l.loan_id,
            l.loan_ref AS loan_code,
            bi.business_name AS cus_name,
            l.loan_close_date,
            l.loan_tot_amount,
            IFNULL(SUM(lp.pymnt_amount), 0) AS total_received,
            (l.loan_tot_amount - IFNULL(SUM(lp.pymnt_amount), 0)) AS balance_amount
        ", false);

		$this->db->from('loan l');
		$this->db->join('loan_payment lp', 'lp.loan_id = l.loan_id', 'left');
		$this->db->join('customer c', 'c.cus_id = l.cus_id', 'left');
		$this->db->join('business_information bi', 'bi.customer_id = c.cus_id', 'left');

		$this->db->where('l.loan_close_date <', $today); // ✅ overdue
		$this->db->where('l.is_closed', 0);              // ✅ not closed
		$this->db->where_in('lp.type', array('terms', 'arrears'));
		$this->db->group_by('l.loan_id');

		$this->db->having('balance_amount >', 0);        // ✅ still balance

		$arrears = $this->db->get()->result_array();




		/* -----------------------------------------------------
       3. RETURN BOTH
    ----------------------------------------------------- */
		$response = [
			"terms"          => $due_terms,
			"delay_charges"  => $final_delay_charges,
			"arrears"       => $arrears
		];

		echo json_encode($response);
	}




	public function save_terms()
	{
		$pay_amount      = $this->input->post('pay_amount');        // normal terms
		$not_collected   = $this->input->post('not_collected');
		$reason          = $this->input->post('reason');

		$delay_amount    = $this->input->post('delay_pay_amount');  // delay charges
		$arrears_payments = $this->input->post('arrears_pay_amount');

		if (empty($pay_amount) && empty($delay_amount) && empty($arrears_payments)) {
			echo json_encode([
				'status' => 'error',
				'message' => 'No payment data received.'
			]);
			return;
		}
		$this->db->trans_start(); // 🔐 START TRANSACTION
		/* ----------------------------------------------------------
        ✅ PROCESS NORMAL LOAN TERMS
    ------------------------------------------------------------*/
		if (!empty($pay_amount)) {


			foreach ($pay_amount as $term_id => $amount) {


				// If ID is delay_xxxx (skip)
				if (strpos($term_id, 'delay_') !== false) continue;
				if ($amount <= 0) continue;

				$term = $this->db->get_where('loan_terms', ['term_id' => $term_id])->row();
				if (!$term) {
					$has_error = true;
					continue;
				}

				// ✅ If not collected
				if (!empty($not_collected[$term_id]) && $not_collected[$term_id] == 1) {

					$update = $this->db->where('term_id', $term_id)
						->update('loan_terms', [
							'status' => 'Not Collected',
							'not_collected_reason' => $reason[$term_id] ?? '',
							'updated_at' => date('Y-m-d H:i:s')
						]);

					if (!$update) $has_error = true;
				} else {

					// ✅ Payment received
					$paymentData = [
						'loan_id' => $term->loan_id,
						'pymnt_ref_no' => time(),
						'pymnt_paying_by' => 'Cash',
						'pymnt_amount' => $amount,
						'paymnt_cash' => $amount,
						'paymnt_balance' => 0,
						'pymnt_date_time' => date('Y-m-d'),
						'user_id' => $this->session->userdata('user_id'),
						'pymnt_added_date_time' => date('Y-m-d H:i:s'),
						'pymnt_note' => '',
						'cus_id' => 0,
						'warehouse_id' => 1,
						'loan_received' => $amount,
						'payment_type' => 'Cash',
						'payment_term' => $term_id
					];
					// Check existing payment
					$existing = $this->db->get_where('loan_payment', [
						'payment_term' => $term_id
					])->row();
					if ($existing) {

						$this->db->where('paymnt_id', $existing->paymnt_id)
							->update('loan_payment', [
								'pymnt_amount' => $amount,
								'paymnt_cash' => $amount,
								'updated_at' => date('Y-m-d H:i:s')
							]);

						$payment_id = $existing->paymnt_id;
					} else {

						$payment_id = $this->Loan_Payment_Received_Model->insert_payment($paymentData);
					}


					if (!$payment_id) {
						$has_error = true;
						continue;
					}

					// ✅ Update loan_terms as paid
					$update = $this->db->where('term_id', $term_id)
						->update('loan_terms', [
							'paid_amount' => $amount,
							'status' => 'Paid',
							'payment_date' => date('Y-m-d'),
							'paymnt_id' => $payment_id,
							'updated_at' => date('Y-m-d H:i:s'),
							'not_collected_reason' => NULL
						]);

					if (!$update) $has_error = true;
				}
			}
		}


		/* ----------------------------------------------------------
        ✅ PROCESS DELAY CHARGE PAYMENTS
        delay_pay_amount[delay_id] = amount
    ------------------------------------------------------------*/
		if (!empty($delay_amount)) {

			foreach ($delay_amount as $delay_id => $amount) {


				if ($amount > 0) {
					// ✅ Insert loan_payment for delay charge
					$paymentData = [
						'loan_id' => $delay_id,
						'pymnt_ref_no' => time(),
						'pymnt_paying_by' => 'Cash',
						'pymnt_amount' => $amount,
						'paymnt_cash' => $amount,
						'paymnt_balance' => 0,
						'pymnt_date_time' => date('Y-m-d'),
						'user_id' => $this->session->userdata('user_id'),
						'pymnt_added_date_time' => date('Y-m-d H:i:s'),
						'pymnt_note' => 'Delay Charge Payment',
						'cus_id' => 0,
						'warehouse_id' => 1,
						'loan_received' => $amount,
						'payment_type' => 'Cash',
						'type' => 'delay_charges',
					];

					$payment_id = $this->Loan_Payment_Received_Model->insert_payment($paymentData);
					// ✅ Update delay charge as paid
					$this->db->insert('loan_delay_charge_payments', [
						'loan_id'    => $delay_id,
						'delay_amount'      => $amount,
						'payment_date' => date('Y-m-d'),
						'payment_id'  => $payment_id,
						'created_at'  => date('Y-m-d H:i:s')
					]);
				}
			}
		}


		if (!empty($arrears_payments)) {

			foreach ($arrears_payments as $loan_id => $pay_amount) {
				if ($pay_amount <= 0) continue;

				// 🔹 Load loan once
				$loan = $this->db->get_where('loan', ['loan_id' => $loan_id])->row();
				if (!$loan) continue;

				// 🔹 Check last arrears for this loan
				$last_arrears = $this->db->order_by('arrears_date', 'DESC')
					->get_where('loan_arrears', ['loan_id' => $loan_id])
					->row();

				if ($last_arrears) {
					$arrears_amount = $last_arrears->balance_amount;
					$last_date = $last_arrears->arrears_date;
				} else {
					// first arrears
					// ✅ FIRST ARREARS (CORRECT WAY)
					$first_balance = $this->get_first_arrears_balance($loan_id);
					if (!$first_balance) continue;

					$arrears_amount = $first_balance->balance_amount;
					$last_date      = $first_balance->loan_close_date;
				}

				if ($arrears_amount <= 0) continue;

				// 🔹 Arrears days
				$arrears_days = (new DateTime(date('Y-m-d')))
					->diff(new DateTime($last_date))
					->days;

				if ($arrears_days <= 0) continue;

				// 🔹 Penalty
				$penalty_percentage = $loan->panalty_presentage;
				$arrears_charge     = (($arrears_amount * $penalty_percentage) / 30) * $arrears_days;
				$total_arrears      = $arrears_amount + $arrears_charge;

				// 🔹 Insert arrears snapshot
				$this->db->insert('loan_arrears', [
					'loan_id'              => $loan_id,
					'arrears_amount'       => $arrears_amount,
					'arrears_days'         => $arrears_days,
					'penalty_percentage'   => $penalty_percentage,
					'arrears_charge'       => $arrears_charge,
					'total_arrears_amount' => $total_arrears,
					'paid_amount'          => $pay_amount,
					'balance_amount'       => $arrears_amount - $pay_amount,
					'arrears_date'         => date('Y-m-d')
				]);

				$arrears_id = $this->db->insert_id();

				// 🔹 Save payment history
				$this->Loan_Payment_Received_Model->insert_payment([
					'loan_id'                  => $loan_id,
					'pymnt_ref_no'              => time(),
					'pymnt_paying_by'           => 'Cash',
					'pymnt_amount'              => $pay_amount,
					'paymnt_cash'               => $pay_amount,
					'paymnt_balance'            => 0,
					'pymnt_date_time'           => date('Y-m-d'),
					'user_id'                   => $this->session->userdata('user_id'),
					'pymnt_added_date_time'     => date('Y-m-d H:i:s'),
					'pymnt_note'                => 'Arrears Payment',
					'loan_received'             => $pay_amount,
					'payment_type'              => 'Cash',
					'type'                      => 'arrears'
				]);
			}
		}



		/* =====================================================
       🔐 COMPLETE TRANSACTION
    ======================================================*/

		$this->db->trans_complete();

		if ($this->db->trans_status() === FALSE) {

			echo json_encode([
				'status' => 'error',
				'message' => 'Transaction failed. Nothing saved.'
			]);
		} else {

			echo json_encode([
				'status' => 'success',
				'message' => 'Payments saved successfully.'
			]);
		}
	}


	private function get_first_arrears_balance($loan_id)
	{
		$today = date('Y-m-d');

		$this->db->select("
        l.loan_close_date,
        (l.loan_tot_amount - IFNULL(SUM(lp.pymnt_amount),0)) AS balance_amount
    ", false);

		$this->db->from('loan l');
		$this->db->join(
			'loan_payment lp',
			'lp.loan_id = l.loan_id AND lp.type = "terms"',
			'left'
		);

		$this->db->where('l.loan_id', $loan_id);
		$this->db->where('l.loan_close_date <', $today);
		$this->db->where('l.is_closed', 0);

		$this->db->group_by('l.loan_id');
		$this->db->having('balance_amount >', 0);

		return $this->db->get()->row();
	}
}
