<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Crossindustry extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('msgmodel');
		$this->load->model('cmerchantmodel');
		$this->load->model('cunitsmodel');
		$this->load->model('auditmodel');
		$this->load->model('mappingsmodel');
		$this->load->model('progressmodel');
		$this->load->model('dbmodel');
		$this->load->helper('string');
		$this->load->library('form_validation');
	}

	public function notifyclient()
	{
		header('Content-Type: text/event-stream');
		header('Cache-Control: no-cache');

		$row = $this->progressmodel->get();
		if ($row->num_rows() > 0) {
			echo "data: " . json_encode($row->row()) . "\n\n";
			flush();
		}
	}

	function init_egift()
	{
		$flashdata = "Egift setup in process.Please check on progress.";
		$this->session->set_flashdata('tempdata', $flashdata);
		$command = "php " . FCPATH . "index.php Crossindustry egift_setup > /dev/null &";
		$this->auditmodel->insert("Initiated data check to egift.", 1, "EGIFT");
		exec($command);
		redirect(APP_BASE . "egift");
	}

	function egift_setup()
	{
		if (!is_cli()) {
			$this->auditmodel->insert("Failed to start check, process is not server initiated.", 0, "EGIFT");
			return;
		}
		$this->auditmodel->insert("Starting setup...", 1, "");
		$curl_post_data = array(
			'client_id' =>  client_id,
			'client_secret' =>  client_secret,
			'grant_type' =>  grant_type,
			'scope' =>  scope
		);

		$data_string = "";
		foreach ($curl_post_data as $item => $value) {
			$data_string .= $item . "=" . $value . "&";
		}

		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, token_url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, rtrim($data_string, "&"));
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt(
			$curl,
			CURLOPT_HTTPHEADER,
			array(
				'Content-Type: application/x-www-form-urlencoded',
				"cache-control: no-cache",
			)
		);

		$curl_response = curl_exec($curl);
		if ($curl_response === false)
			$this->auditmodel->insert("Egift token generation failed " . curl_error($curl), 0, "EGIFT", $data_string);
		else {
			$this->auditmodel->insert("Egift token generated, fetching partners... ", 1, "EGIFT", $data_string);
			@$this->progressmodel->insert("Egift setup", "intializing...", 0.5);
			$resp = json_decode($curl_response);
			$token = $resp->access_token;
			$this->getRedeemables($token);
		}
		curl_close($curl);
	}

	function getRedeemables($token)
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, buyables_url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_POST, false);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt(
			$curl,
			CURLOPT_HTTPHEADER,
			array(
				'Content-Type: application/x-www-form-urlencoded',
				"cache-control: no-cache",
				"Authorization: Bearer " . $token
			)
		);

		$curl_response = curl_exec($curl);
		if ($curl_response === false)
			$this->auditmodel->insert("Egift partner fetching failed " . curl_error($curl), 0, "EGIFT");
		else {
			$data = json_decode($curl_response);
			$count = 0;
			$all = sizeof($data->payload);
			$this->auditmodel->insert("Egift " . $all . " partners found.", 1, "EGIFT", $data);
			foreach ($data->payload as $merchant) {
				$obj = array(
					'dmo_id' => $merchant->underlying_id,
					'type' => $merchant->type,
					'name' => $merchant->name,
					'termsconditions' => $merchant->tc,
					'description' => $merchant->description,
					'categories' => sizeof($merchant->categories) > 0 ? $merchant->categories[0] : "",
					'images' => implode(",", $merchant->imgs),
					'country' => $merchant->country,
					'merchantcode' => 'E-gift'
				);

				@$this->progressmodel->insert("Adding redemption partner ", $merchant->name, (($count / $all) * 100));
				$added = 0;
				if ($this->cmerchantmodel->get(array('dmo_id' => $merchant->underlying_id))->num_rows() == 0)
					$added = $this->cmerchantmodel->insert($obj);

				foreach ($merchant->units as $u) {
					$units = array(
						'dmo_id' => $merchant->underlying_id,
						'type' => $u->type,
						'unit' =>  $u->unit,
						'min' =>  isset($u->min) ? $u->min : '',
						'max' =>  isset($u->max) ? $u->max : '',
						'step' =>  isset($u->price) ? $u->price : '',
						'value' =>  isset($u->value) ? $u->value : ''
					);

					$search = array('dmo_id' => $merchant->underlying_id, 'type' => $u->type, 'unit' => $u->unit);
					if ($u->type == 'fixed')
						$search['value'] = $u->value;

					if ($this->cunitsmodel->get($search)->num_rows() == 0)
						$this->cunitsmodel->insert($units);

					@$this->progressmodel->insert("Redeemable Units for " . $merchant->name, "Adding " . $u->value . " type " . $u->type, (($count / $all) * 100));
				}
				$this->auditmodel->insert("Added " . $merchant->name . " to merchant .", $added, "");
				$count++;
			}
			@$this->progressmodel->insert("Setup Done", "", (($count / $all) * 100));
		}
		curl_close($curl);
	}
	/*
	function process(){
		$json = '{"orderId":"1575455460VGwua","state":"MZAWADI_INTERNAL_ORDER_ID","cards":[{"id":"1575455460Y2ZDP","dmo_id":"1481011677rFway","user":null,"status":"135024633118xiinl","status_name":"usable","fields":{"value":250,"number":"0602107102747621","expiration":"2020-06-04"},"created_at":1575455460,"updated_at":1575455460}]}';
		$j = json_decode($json);
		
	}
*/

	function assign_partners()
	{
		$this->form_validation->set_rules('code[]', 'Partner Code', 'required');
		$this->form_validation->set_rules('client', 'Client', '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 {
			$codes = $this->input->post('code');
			$client = $this->input->post('client');
			$assigned = false;
			foreach ($codes as $code) {
				$data = array(
					'record_state' => 0,
					'dmo_id' => $code,
					'client_id' => $client
				);

				if ($this->mappingsmodel->get(array('record_state' => 0, 'dmo_id' => $code, 'client_id' => $client))->num_rows() == 0)
					$added = $this->mappingsmodel->insert($data);
				else
					$added = 0;
				$this->auditmodel->insert("Added mapping for client id " . $client . " dmo_id " . $code, $added, "", json_encode($data));
				if ($added > 0) $assigned = true;
			}

			if ($assigned)
				$this->session->set_flashdata('tempdata', "Client mappings successful");
			else
				$this->session->set_flashdata('tempdata', "Sorry failed to map redemption partners.");
		}
		redirect(APP_BASE . "crossindustry");
	}

	function disable_partner()
	{
		$this->form_validation->set_rules('code[]', 'Partner Code', 'required');
		$action = $this->input->post('action');
		if (!empty($action))
			$this->form_validation->set_rules('client', 'Client', '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 {
			$codes = $this->input->post('code');
			$client = $this->input->post('client');

			foreach ($codes as $code) {

				if (empty($action)) {
					$this->cmerchantmodel->update(array('record_state' => 900), array('dmo_id' => $code));
					$added = $this->db->affected_rows();
					$this->mappingsmodel->update(array('record_state' => 900), array('dmo_id' => $code));
				} else
					$this->mappingsmodel->update(array('record_state' => 900), array('dmo_id' => $code, 'client_id' => $client));


				$this->auditmodel->insert("Suspended redemption partner dmo_id " . $code . " client id: " . $client, $added, "");
			}

			$this->session->set_flashdata('tempdata', "Partner suspended / removed from client redemption options.");
		}

		redirect(APP_BASE . (empty($action) ? "crossindustry" : "client_mappings"));
	}

	function enable_partner()
	{
		$this->form_validation->set_rules('code[]', 'Partner Code', 'required');
		$action = $this->input->post('action');
		if (!empty($action))
			$this->form_validation->set_rules('client', 'Client', '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 {
			$codes = $this->input->post('code');
			$client = $this->input->post('client');

			foreach ($codes as $code) {
				if (empty($action)) {
					$this->cmerchantmodel->update(array('record_state' => 0), array('dmo_id' => $code));
					$this->mappingsmodel->update(array('record_state' => 0), array('dmo_id' => $code));
				} else
					$this->mappingsmodel->update(array('record_state' => 0), array('dmo_id' => $code, 'client_id' => $client));

				$added = $this->db->affected_rows();
				$this->auditmodel->insert("Partner enabled dmo_id " . $code . " client id: " . $client, $added, "");
			}

			$this->session->set_flashdata('tempdata', "Partner enabled for client redemption.");
		}
		redirect(APP_BASE . "crossindustry");
	}

	function upload()
	{
		$uploadFile = './_temp/';
		$config['upload_path'] = $uploadFile;
		$config['allowed_types'] = 'png|jpg|jpeg|bmp';
		$config['max_size']	= '25600'; 
		$this->load->library('upload', $config);

		if (!$this->upload->do_upload()) {
			$data =  $this->upload->display_errors();
			$this->auditmodel->insert("Error uploading file ". $data,0, "", json_encode($data));
			return array('resp' => 'fail', 'img' => '');
		} else {
			$data = $this->upload->data();
			return array('resp' => 'ok', 'img' => $data["file_name"]);
		}
	}

	function get_vendor()
	{
		$prods = $this->dbmodel->get('local_partners');
		if ($prods->num_rows() > 0)
			echo json_encode(array('result' => 'OK', 'message' => $prods->result_array()));
		else
			echo json_encode(array('result' => 'fail', 'message' => ''));
	}

	public function add_partners()
	{
		$this->form_validation->set_rules('dmo_id', 'Partner Code', 'required');
		$this->form_validation->set_rules('name', 'Partner', 'required');
		$this->form_validation->set_rules('vendor', 'Vendor', 'required');
		$this->form_validation->set_rules('categories', 'Category', 'required');
		$this->form_validation->set_rules('type', 'Partner Type', 'required');
		$this->form_validation->set_rules('redemptionoption', 'Redemption Option', 'required');


		$action = $this->input->post('action');
		if (!empty($action))
			$this->form_validation->set_rules('id', 'Client', 'required');

		$redemptionoption = $this->input->post('type');
		if(strtolower($redemptionoption) =="discount" || strtolower($redemptionoption) =="redemption & discount" ){
			$this->form_validation->set_rules('discounttype', 'Discount type', 'required');
			$this->form_validation->set_rules('discount_amount', 'Discount Amount', 'required');
			$this->form_validation->set_rules('discountcode', 'Generate code', 'required'); 
		}

		$username = $this->session->userdata('username');
		$upload = $this->input->post('userfile');

		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 {
			$action = $this->input->post('action');
			$id = $this->input->post('id');

			$data = array(
				'name' => $this->input->post('name'),
				'dmo_id' => $this->input->post('dmo_id'),
				'type' => $this->input->post('type'),
				'termsconditions' => $this->input->post('terms'),
				'description' => $this->input->post('description'),
				'categories' => $this->input->post('categories'),
				'country' => "KE",
				'merchantcode' => $this->input->post('vendor'),
				'ussdcode' => 0,
				'record_state' => 0,
				'isexternal' => 0,
				'ussd_state' => 0,
			);

			$partners = $this->dbmodel->get('cross_industry_merchants', array('dmo_id' => $this->input->post('dmo_id'), 'record_state' => 0));

			if (!empty($action) && !empty($id)) {
				//edit 
				if(file_exists($_FILES['userfile']['tmp_name'][0])) {
					$ot = $this->upload();
					if ($ot['resp'] == "ok")
						$data['images'] =  base_url() ."_temp/". $ot['img'];
				}

				$partners = $this->dbmodel->get('cross_industry_merchants', array('id<>' => $id, 'dmo_id' => $this->input->post('dmo_id'), 'record_state' => 0));
				if ($partners->num_rows() > 0)
					$this->session->set_flashdata('tempdata', "Sorry partner already exists.");
				else {
					$this->dbmodel->update('cross_industry_merchants', $data, array('id' => $id));
				}
				$this->auditmodel->insert("Editted redemption partner details " . $this->input->post('dmo_id'), $this->db->affected_rows(), "", json_encode($data));
			} else {
				//new
				if(file_exists($_FILES['userfile']['tmp_name'][0])) {
					$ot = $this->upload();
					if ($ot['resp'] == "ok")
						$data['images'] = base_url() ."_temp/". $ot['img'];
				}

				$added = $this->dbmodel->insert('cross_industry_merchants', $data);
				if ($added > 0) {

					if(strtolower($redemptionoption) =="discount" || strtolower($redemptionoption) =="redemption & discount" ){
						$units = array(
							'dmo_id' => $this->input->post('dmo_id'),
							'type' => 'discount',
							'unit' => $this->input->post('discounttype'),
							'min' =>  0,
							'max' =>  0,
							'step' =>  0,
							'value' =>  $this->input->post('discount_amount')
						);
						$this->cunitsmodel->insert($units);

						if(strtolower($redemptionoption) =="redemption & discount"){
							$units = array(
								'dmo_id' => $this->input->post('dmo_id'),
								'type' => 'variable',
								'unit' => 'kes',
								'min' =>  1,
								'max' =>  100000,
								'step' =>  0,
								'value' =>  0
							);
							$this->cunitsmodel->insert($units);
						}
					} else {
						$units = array(
							'dmo_id' => $this->input->post('dmo_id'),
							'type' => 'variable',
							'unit' => 'kes',
							'min' =>  1,
							'max' =>  100000,
							'step' =>  0,
							'value' =>  0
						);
						$this->cunitsmodel->insert($units);
					} 

					$ccode = "";
					$discountcode = $this->input->post('discountcode');
					if($discountcode==0)
						$ccode = $this->input->post('actualcode'); 

					$vndors = $this->dbmodel->get('local_partners', array('partner' => $this->input->post('vendor')));
					if ($vndors->num_rows() > 0) {
						$v = $vndors->row()->dmo_ids . "," . $this->input->post('vendor');
						$this->dbmodel->update('local_partners', array('dmo_ids' => $v,'discount_code'=> $ccode), array('partner' => $this->input->post('vendor')));
					} else
						$this->dbmodel->insert('local_partners', array('dmo_ids' => $this->input->post('dmo_id'), 'discount_code'=> $ccode,'contact_phone' => $this->input->post('phone'), 'contact_person' => $this->input->post('cname'), 'contact_person_email' => $this->input->post('email'), 'partner' => $this->input->post('vendor')));
					
					$this->session->set_flashdata('tempdata', "Partner successfully added.");
				} else
					$this->session->set_flashdata('tempdata', "Sorry could not add partner, please try again.");

				$this->auditmodel->insert("Added redemption partner details " . $this->input->post('dmo_id'), $added, "", json_encode($data));
			}
			$this->session->set_flashdata('tempdata', "Partner enabled for client redemption.");
		}
		redirect(APP_BASE . "crossindustry_partner");
	}
}
