<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Clientfloat extends CI_Controller
{

	var $username;

	public function __construct()
	{
		parent::__construct();
		$this->load->model('auditmodel');
		$this->load->model('msgmodel');
		$this->load->model('usersmodel');
		$this->load->model('customersmodel');
		$this->load->model('dbmodel');
		$this->load->model('floatmodel');
		$this->load->model('notificationsmodel');
		$this->load->helper('string');
		$this->load->library('Datatables');
		$this->load->library('form_validation');

		$this->username = $this->session->userdata('username');
	}

	public function index()
	{
		show_404();
	}

	function checkclients()
	{
		$type = $this->input->get('type');
		$type = strtolower($type);
		if($type=="client")
			$clients = $this->customersmodel->get(array('record_state' => 0));
		else
			$clients = $this->dbmodel->get('local_partners');

		$available = array();
		if ($clients->num_rows() > 0 && !empty($this->username)) {
			foreach ($clients->result_array() as $row){
				if($type=="client")
					array_push($available, array('id' => $row['id'], 'name' => $row['name']));
				else
					array_push($available, array('id' => $row['id'], 'name' => $row['partner']));
			}

			echo json_encode(array('result' => 'OK', 'message' => $available));
		} else
			echo json_encode(array('result' => 'FAIL', 'message' => ''));
	}

	function save_float()
	{
		$this->form_validation->set_rules('cpartner', 'Partner Type', 'required');
		$this->form_validation->set_rules('client', 'Client Name', 'required');
		$this->form_validation->set_rules('float', 'Float amount', 'required');
		$this->form_validation->set_rules('date', 'Topup Date', 'required');

		$username = $this->session->userdata('username');
		if ($this->form_validation->run() == FALSE || empty($username)) {
			$this->session->set_flashdata('tempdata', "Sorry there is an error on your data. Please fix the issues addressed and try again.<br>" . validation_errors());
		} else {

			$added = $this->floatmodel->insert(); 
			$amount =$this->input->post('float'); 
			$client =$this->input->post('client');
			$cpartner =$this->input->post('cpartner');
			$date =$this->input->post('date');  
			if ($added > 0) {
				$this->session->set_flashdata('tempdata', ucfirst($cpartner) .' float successfully added.');
				//send comms on apis
				$msg = '<p>'. ucfirst($cpartner) .' float has been added on the system.</p> 
						<p>Details:>
						<table border="0" cellpadding="0" cellspacing="0"><tbody>
						<tr><td>Float kes : ' . $amount . '</td></tr>
						<tr><td>Date      : ' . $date . '</td></tr>
						<tr><td>Added by  : ' . $this->usersmodel->get(array('UserCode'=>$username, 'recordstate'=>0))->row()->Firstname . '</td></tr></tbody> 
						</table>';

				if (!empty(MAIL_ALERT))
					$this->msgmodel->insert_comm(MAIL_ALERT, "email", $msg, APP_NAME . ", Float updated", 'System Dev.', $username);
			} else
				$this->session->set_flashdata('tempdata', 'Sorry could not add float details. Please try again.');
		}
		$this->auditmodel->insert("Added float for ". ucfirst($cpartner) ." id: ".$client ." float kes: ".$amount , $added, "", json_encode($this->input->post()));
		redirect(APP_BASE . 'issue_loan');
	} 

	function sendcomms($data){
		$data = base64_decode(urldecode($data));

		
		$clients = $this->dbmodel->get('customers' , array('id'=>$data))->row();
		$bal = $this->dbmodel->get('client_float_balance' , array('id'=>$data))->row();

		$msg = "Your loan balance as at ". date('d F') .' is ksh: '. $bal->balance .'. Pay your loan using M-pesa or using card by visiting '. base_url() .'home/pay/'.urlencode(base64_encode($data));

		$this->msgmodel->insert_comm($clients->contact_phone, "sms", $msg, "Loan status", 'System Dev.', ucfirst($clients->name));
		$this->session->set_flashdata('tempdata', 'Loan status message sent.');
		redirect(APP_BASE . 'simulate');
	
	}

	function getfloat()
	{
		if (!empty($this->username)) {
			$this->datatables->select("case when name is null then partner else name end,topped_on,client_float ,concat(c.firstname,' ',c.secondname) as added,client_float.addedon,client_float.id")
				->from('client_float')
				->join('customers', "customers.id=client_float.client_id and customers.record_state=0 and client_float.type like 'Client'", 'left') 
				->join('local_partners', "local_partners.id=client_float.client_id and client_float.type like 'Partner'", 'left') 
				->join('users as c', 'client_float.addedby=c.UserCode and c.recordstate=0', 'left')
				->where('client_float.record_state', 0);
			echo $this->datatables->generate();
		}
	}
}
