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

class Loans extends CI_Controller {
	
	function __construct()
	{
		parent::__construct();
		$this->login_model->authenticate();
		$this->load->library('form_validation');
		$this->load->model('loans_model');
	}
	
	public function loan_application()
	{
		$user_id = $this->login_model->user_id();
			
		$topbar_data['additional_css'] = array(NULL);
		$topbar_data['profile_photo'] = $this->main_model->create_thumbnail(160,160,$user_id);
		$sidebar_data['menu'] = $this->menu_control->get_menu($user_id);
		
		$data['member_no_member_name'] = $this->loans_model->get_member_details($user_id);
		$data['subject_id'] = $user_id;
		
		$jquery_data['additional_jquery'] = array(NULL);
		$jquery_data['functions'] = array(NULL);
		
		$this->load->view('sections/topbar',$topbar_data);
		$this->load->view('sections/sidebar',$sidebar_data);
		$this->load->view('loans/loan_application',$data);
		$this->load->view('sections/footer',$jquery_data);
	}
	
	public function add_guarantor()
	{
		$user_id = $this->login_model->user_id();
		
		$loan_id = $this->loans_model->get_loan_id($user_id);
			
		$topbar_data['additional_css'] = array('plugins/datatables/dataTables.bootstrap.css"');
		$topbar_data['profile_photo'] = $this->main_model->create_thumbnail(160,160,$user_id);
		$sidebar_data['menu'] = $this->menu_control->get_menu($user_id);
		
		$data['member_no_member_name'] = $this->loans_model->get_member_details($user_id);
		$data['subject_id'] = $user_id;
		$data['guarantors'] = $this->main_model->get_relevant_data('guarantors','loan_id',$loan_id);
		
		$jquery_data['additional_jquery'] = array('plugins/datatables/jquery.dataTables.min.js"',
												'plugins/datatables/dataTables.bootstrap.min.js"');
		$jquery_data['functions'] = array(
			' <script type="text/javascript">
				$(function () {
				  $("#guarantors_table").DataTable();
				});
			  </script>',
			
			'<script type="text/javascript">	
			
				function ajaxConfirmGuarantorExistence(id,type) 
				   {
					  event.preventDefault();				  
					  var member_no = $("#guarantor_member_no").val();
					  var member_no = String(member_no);
					  var national_id_no = $("#national_id_no").val();
					  var postForm = {\'member_no\' : member_no,\'national_id_no\' : national_id_no};
					  $.ajax({ 
						  type 		: \'POST\', 
						  url 		: url+\'loans/confirm_guarantor_for_Ajax\', 
						  data 		: postForm, 
						  dataType 	: \'text\',
						  success 	: function(reponse) 
									  {	
									  	var response = String(reponse);
										 $("#existence_status").val(reponse);	
										 //console.log(response);							
									  }
					  });
				  }
					  
			  </script>' 
			  );
		
		$this->load->view('sections/topbar',$topbar_data);
		$this->load->view('sections/sidebar',$sidebar_data);
		$this->load->view('loans/add_guarantor',$data);
		$this->load->view('sections/footer',$jquery_data);
	}
	
	
	public function loan_calculator()
	{
		$user_id = $this->login_model->user_id();
			
		$topbar_data['additional_css'] = array('plugins/jquery-steps/css/jquery.steps.css"');
		$topbar_data['profile_photo'] = $this->main_model->create_thumbnail(160,160,$user_id);
		$sidebar_data['menu'] = $this->menu_control->get_menu($user_id);
		
		$jquery_data['additional_jquery'] = array('plugins/jquery-steps/js/jquery.steps.min.js"');
		$jquery_data['functions'] = array(		
		'  <script>
                $(function ()
                {
                    $("#wizard").steps({
                        headerTag: "h2",
                        bodyTag: "section",
                        transitionEffect: "slideLeft"
                    });
                });
            </script>
		'		
		);
		
		$this->load->view('sections/topbar',$topbar_data);
		$this->load->view('sections/sidebar',$sidebar_data);
		$this->load->view('loans/loan_calculator');
		$this->load->view('sections/footer',$jquery_data);
	}
	
	 //this function inserts the details of a loan into the database	
	 public function insert_loan_details()
	  {	 
		  $user_id = $this->login_model->user_id();
		  $loan_id = $this->main_model->get_next_id('loan_application','loan_id');
		  $status = 1;  
		  
		  $this->form_validation->set_rules('principal', 'Principal', 'required|numeric');			
		  $this->form_validation->set_rules('repayment_duration','Repayment Duration', 'required|numeric|max_length[2]');						
		  $this->form_validation->set_rules('purpose', 'Purpose', 'required');
			  
		  $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
	  
		  if ($this->form_validation->run() == FALSE) // validation hasn't been passed
		  {		  
			  $this->loan_application();		  
		  }
		  else // passed validation proceed to post success logic
		  {
			 // build array for the model
			  $form_data = array(
							  'loan_id' => $loan_id,
							  'user_id' => $this->input->post('subject_id'),
							  'principal' => $this->input->post('principal'),
							  'repayment_duration' => $this->input->post('repayment_duration'),
							  'purpose' => $this->input->post('purpose'),
							  'date_applied' =>time(),
							  'applicant_id' =>$user_id,
							  'status' => $status							  
						  );
			  $table = 'loan_application';
			  //$this->main_model->lock_table($table);
			  $this->main_model->insert_data($table, $form_data);
			  
			 // $this->main_model->unlock_table($table);
			 //$insert_id = $this->db->insert_id();					 				  
			  redirect('loans/add_guarantor');						  
		  }		
	  }
	  
	  //this function inserts the details of a guarantor into the database	
	 public function insert_guarantor()
	  {	
	  	  $guarantor_member_no = $this->input->post('guarantor_member_no');
		  $guarantor_id_no = $this->input->post('national_id_no');
		  $corporation_id = $this->login_model->corp_id(); 
		  $user_id = $this->loans_model->confirm_guarantor($guarantor_member_no, $guarantor_id_no, $corporation_id);
		  $guarantor_id = $this->main_model->get_next_id('guarantors','guarantor_id');
		  $status = 1;  
		  
		  $this->form_validation->set_rules('guarantor_member_no', 'Member No.', 'required|numeric');			
		  $this->form_validation->set_rules('national_id_no','National Id No.', 'required|numeric|max_length[8]');						
		  $this->form_validation->set_rules('amount_offered', 'Amount Offered', 'required|numeric');
		  $this->form_validation->set_rules('existence_status', 'Status', 'callback_guarantor_existence_check');
			  
		  $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
	  
		  if ($this->form_validation->run() == FALSE || $user_id == 'Not Found') // validation hasn't been passed
		  {		  
			  $this->add_guarantor();		  
		  }
		  else // passed validation proceed to post success logic
		  {
			 // build array for the model
			  $form_data = array(
							  'guarantor_id' => $guarantor_id,
							  'loan_id' => $status,//$this->input->post('subject_id'),
							  'user_id' => $user_id,
							  'guarantor_member_no' => $this->input->post('guarantor_member_no'),
							  'guarantor_id_no' => $this->input->post('national_id_no'),
							  'amount' =>$this->input->post('amount_offered'),
							  'status' => $status							  
						  );
			  $table = 'guarantors';
			  $this->main_model->insert_data($table, $form_data);
			  
			 //$insert_id = $this->db->insert_id();					 				  
			  redirect('loans/add_guarantor');						  
		  }		
	  }
	 
	//validates the guarantor field contains "Exists"
	public function guarantor_existence_check($str)
	{
		if ($str != 'Exists')
		{
			$this->form_validation->set_message('guarantor_existence_check', 'The guarantor %s  MUST be confirmed.');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	//this function is called via ajax to confirm a guarantor's existence "hello";// 
	function confirm_guarantor_for_Ajax()
	{		
		$member_no=  $this->input->post('member_no');
		$national_id_no=   $this->input->post('national_id_no');
		$corporation_id = $this->login_model->corp_id();
		
		$guarantor_existence_status = $this->loans_model->confirm_guarantor($member_no, $national_id_no, $corporation_id);
		
		if(is_numeric($guarantor_existence_status) && $guarantor_existence_status != 'Not Found')
		{
			echo  "Exists";
		}else
		{
			echo  "Non-existent";
		}
	}

}
?>