<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Customers 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('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 checkUsers()
	{
		$users = $this->usersmodel->get(array('recordstate' => 0));
		$available = array();
		if ($users->num_rows() > 0 && !empty($this->username)) {
			foreach ($users->result_array() as $row)
				array_push($available, array('user' => $row['UserCode'], 'names' => $row['Firstname'] . " " . $row['Secondname']));
			echo json_encode(array('result' => 'OK', 'message' => $available));
		} else
			echo json_encode(array('result' => 'FAIL', 'message' => ''));
	}

	function getById()
	{
		$id = $this->input->get('prod');
		$id = base64_decode($id);
		$customers = $this->customersmodel->get(array('id' => $id, 'record_state' => 0));
		if ($customers->num_rows() > 0 && !empty($this->username)) {
			$o = $customers->result_array()[0];
			unset($o['client_extid']);
			unset($o['consumer_secret']);
			unset($o['consumer_key']);
			echo json_encode(array('result' => 'OK', 'data' =>  $o));
		} else 
		echo json_encode(array('result' => 'FAIL', 'message' => ''));
	}

	function save_Customer()
	{ 
		$this->form_validation->set_rules('contact_person', 'Contact person', 'required');
		$this->form_validation->set_rules('contact_phone', 'Contact person Phone', '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 {
			$id = $this->input->post('id');
			$technician = $this->input->post('technician');
			$name = $this->input->post('contact_person'); 

			$customers = $this->customersmodel->get(array('name' => $name, 'record_state' => 0));

			if ($customers->num_rows() > 0  && empty($id)) {
				$this->auditmodel->insert("Tried to add client details in the sytem.Client already exists (" . $name  . ")", 0, "", json_encode($this->input->post()));
				$this->session->set_flashdata('tempdata', 'Sorry could not add new  client,client already exists.');
			} else {

				if (!empty($id)) {
					$custs = $this->customersmodel->get(array('name' => $name, 'id <>' => $id, 'record_state' => 0));
					if ($custs->num_rows() > 0) {
						$this->session->set_flashdata('tempdata', "Sorry could not update details.Client already exists in the system.");
						$added = 0;
					} else {
						$data = array(
							'name' => $name,
							'url' => $this->input->post("url"),
							'bsn_phone' => $this->input->post("contact_phone"),
							'account_manager' => $this->input->post("account_manager"),
							'technician' => $this->input->post("technician"),
							'contact_person' => $this->input->post("contact_person"),
							'contact_phone' => $this->input->post("contact_phone"),
							'opt_crossindusry' => $this->input->post("crossindustry"),
							'opt_discounts' => $this->input->post("discount"),
							'opt_cashback' => $this->input->post("cashback"),
							'opt_localredemption' => $this->input->post("localredemption")
						);

						$this->customersmodel->update($data, array('id' =>  $id));
						$added = 1;
						$this->session->set_flashdata('tempdata', 'Client details successfully adjusted.');
					}
				} else {
					$key = random_string('alnum', 10);
					$secret = random_string('alnum', 20);
					$id = $this->generateClientId($name);

					$added = $this->customersmodel->insert($id, $secret, $key);
					if ($added > 0) {
						$this->session->set_flashdata('tempdata', 'Client details successfully added.');
					} else
						$this->session->set_flashdata('tempdata', 'Sorry could not add client details. Please try again.');
				}
				$this->auditmodel->insert("Added a new customer details in the system (" . $name  . ")", $added, "", json_encode($this->input->post()));
			}
		}
		redirect(APP_BASE . 'client');
	}

	function generateClientId($name)
	{
		$customers = $this->customersmodel->get(array('client_extid' => sha1($name), 'record_state' => 0));
		if ($customers->num_rows() > 0)
			$this->generateClientId(random_string('alnum', 20));
		else
			return sha1($name);
	}

	function regenerate()
	{
		$recid = $this->input->post('cid');
		$action = $this->input->post('action');
		$username = $this->session->userdata('username');
		$role = $this->session->userdata('role');
		$client = $this->customersmodel->get(array('id' => $recid));

		if (!empty($username) && strtolower($role) == "admin" && $client->num_rows() > 0) {

			$row = $client->row();
			if(empty($action)){
				$key = $row->consumer_key;
				$secret = $row->consumer_secret;
				$id = $row->client_extid;
			} else {
				$key = random_string('alnum', 10);
				$secret = random_string('alnum', 20);
				$id = $this->generateClientId(random_string('alnum', 20));
			} 

			$this->auditmodel->insert("Requested API credentials change for " . $row->name, 1, "", json_encode($this->input->post()));
			$this->session->set_flashdata('tempdata', 'API credentials reset.');
			//send comms on apis
			$msg = '<p>Credentials for ' . $row->name . ' have been reset: **Highly confidential</p>
						<table border="0" cellpadding="0" cellspacing="0"><tbody>
						<tr><td>Secret    : ' . $secret . '</td></tr>
						<tr><td>Key       : ' . $key . '</td></tr>
						<tr><td>client id : ' . $id . '</td></tr></tbody> 
						</table><br> 
						<p>Note these are live crentials keep them secret.</p>';

			if (!empty($row->technician))
				$this->msgmodel->insert_comm($row->technician, "email", $msg, APP_NAME . ", account Created", 'System Dev.', $username);
		} else {
			$this->auditmodel->insert("Tried to Request API credentials change for id " . $recid, 0, "", json_encode($this->input->post()));
			$this->session->set_flashdata('tempdata', 'Sorry could not add client details. Please try again.');
		}

		redirect(APP_BASE . 'client_apis');
	}


	function getClients()
	{
		if (!empty($this->username)) {
			$this->datatables->select("name,url,bsn_phone, concat(a.firstname,' ',a.secondname) as acc, 
			concat(b.firstname,' ',b.secondname) as tech,concat(c.firstname,' ',c.secondname) as added,addedon,
			contact_person, contact_phone,opt_crossindusry,opt_discounts,opt_cashback,opt_localredemption,account_manager,technician,id")
				->from('customers')
				->join('users as a', 'customers.account_manager=a.UserCode', 'left')
				->join('users as b', 'customers.technician=b.UserCode', 'left')
				->join('users as c', 'customers.addedby=c.UserCode', 'left')
				->where('record_state', 0);
			echo $this->datatables->generate();
		}
	}
}
