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

	public function __construct()
	{
		parent::__construct();
		$this->load->model('msgmodel');
		$this->load->model('usersmodel');
		$this->load->model('outletsmodel');
		//$this->load->model('distributorsmodel');
		$this->load->model('notificationsmodel');
		$this->load->model('cmerchantmodel');
		$this->load->model('earnsmodel');
		$this->load->model('targetsmodel');
		$this->load->model('currentaccmodel');
		$this->load->model('earnhistorymodel');
		$this->load->model('auditmodel');
		$this->load->model('commonmodel');
		$this->load->model('regionsmodel');
		$this->load->model('territorymodel');
		$this->load->library('form_validation');
	}

	public function index()
	{
		show_404();
	}

	function checkOutlet()
	{
		$code = $this->input->get('code');
		$outlets = $this->outletsmodel->get(array('CUST_CD' => $code, 'record_state' => 0));
		if ($outlets->num_rows() > 0)
			echo json_encode(array('result' => 'FAIL', 'message' => 'Customer Code Already Exists'));
		else
			echo json_encode(array('result' => 'OK', 'message' => ''));
	}

	function getProductById()
	{
		$prodid = $this->input->get('prod');
		if (!empty($prodid)) {
			$id = base64_decode(urldecode($prodid));
			echo json_encode(array('result' => 'ok', 'data' => $this->outletsmodel->get(array('id' => $id, 'record_state' => 0))->result_array()));
		} else echo json_encode(array('result' => 'fail', 'data' => array()));
	}

	function generateCode(){
        $code = "D001";
        $outlets = $this->db->query("select * from outlets order by id desc limit 1");
        if($outlets->num_rows()>0){
			$row = $outlets->row(); 
			$code = $row->id;
            $cd = str_replace("D","",$code);
            $cd = (int) $cd+1;
            $code = "D". str_pad($cd,3,"0",STR_PAD_LEFT);

            $ml = $this->outletsmodel->get(array('CUST_CD',$code));
            if($ml->num_rows()>0)
                $this->generateCode();
        }
        return $code;
	} 


	function save_Outlet()
	{
		
		$this->form_validation->set_rules('desc', 'Retailer Name', 'required');
		$this->form_validation->set_rules('area', 'Physical location', 'required');
		$this->form_validation->set_rules('phone', 'Contact person Phone Number', 'required');
		$this->form_validation->set_rules('fname', 'Contact person firstname', 'required');
		$this->form_validation->set_rules('sname', 'Contact person secondname', 'required');
		$this->form_validation->set_rules('salesrep', 'County', 'required');
		$this->form_validation->set_rules('category', 'Region', 'required');
		//$this->form_validation->set_rules('isdoshi', 'Select if Doshi Outlet', 'required');

		$adding = $this->input->post('adding');

		if(strtoupper($adding)!=strtoupper("retailer"))
			$this->form_validation->set_rules('code', 'Retailer Code', 'required');

		$adding = ucfirst($adding);
		$action = $this->input->post('action');
		$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 {
			//validation OK
			$id = $this->input->post('id');
			$code = $this->input->post('code');
			$desc = $this->input->post('desc');
			$phone = $this->input->post('phone');
			$email = $this->input->post('email');

			if(strtoupper($adding)==strtoupper("retailer")  && $action  != "edit")
				$code =$this->generateCode();

			$code = strtoupper(trim($code));
			$desc = strtoupper(trim($desc)); 

			$outlets = $this->outletsmodel->get(array('CUST_CD' => $code, 'record_state' => 0));
			$phonenos = $this->outletsmodel->get(array('CUST_PHONE' => $phone, 'record_state' => 0));
			$usersphonenos = $this->usersmodel->get(array('UserCode' => $phone, 'recordstate' => 0));

			if (($outlets->num_rows() > 0 || $phonenos->num_rows() > 0 || $usersphonenos->num_rows() > 0) && empty($action)) {
				$this->auditmodel->insert("Tried to add an " . $adding . " in the sytem.  " . $adding . " code already exists (" . $code . "-" . $desc . ")", 0, "", json_encode($this->input->post()));
				$this->session->set_flashdata('tempdata', 'Sorry could not add new  ' . $adding . '.  ' . $adding . ' code, Phone number already exists.');
			} else {
				$outlet = array(
					'CUST_CD' => $code,
					'DIST_CD' => ucfirst($adding),
					'CUST_NAME' => $desc,
					'CUST_PHONE' =>  $this->input->post('phone'),
					'email' =>  $email,
					'LONGITUDE' => '0',
					'LATITUDE' => '0',
					'CUST_STATUS' => 1,
					'TERRITORY' => $this->input->post('category'), //this will hold region
					'ROUTE' => $this->input->post('salesrep'),	//this will hold territory
					'AREA' => $this->input->post('area'),
					'contactfname' =>  $this->input->post('fname'),
					'contactsname' =>  $this->input->post('sname'),
					'BE_CUST_CD' => '',
					'OBOS' => $this->input->post('isdoshi'),
					'CHANNEL' => '',
					'SUBCHANNEL' => '',
					'SEGMENT' => ''
				);

				if ($action == "edit") {
					$phonenos = $this->usersmodel->get(array('UserCode' => $phone, 'CUST_CD <>' => $code, 'recordstate' => 0));
					if ($phonenos->num_rows() > 0) {
						$this->session->set_flashdata('tempdata', "Sorry could not update details.Phone number is already used by another user.");
						$added = 0;
					} else {
						$this->outletsmodel->update($outlet, array('id' =>  $id));
						$added = 1;
						//update user details
						$users = $this->usersmodel->get(array('CUST_CD' => $code, 'recordstate' => 0));
						if ($users->num_rows() > 0) {
							$user = $users->row();
							if ($user->UserCode == $phone) {
								//update user details only.
								$owner_firstname = $this->input->post('fname');
								$owner_secondname = $this->input->post('sname');
								$owner_phone = $this->input->post('phone');
								$owner_email = $this->input->post('email');
								$euser = array(
									'recordstate' => 0,
									'Firstname' => $owner_firstname,
									'Secondname' => $owner_secondname,
									'email' => $owner_email,
									'phone' => $owner_phone,
									'UserEnabled' => 1
								);
								$this->usersmodel->update($euser, array('CUST_CD' => $code, 'recordstate' => 0));
							} else {
								//Changed phone number, hence create new login
								$this->usersmodel->update(array('recordstate' => 900), array('CUST_CD' => $code, 'recordstate' => 0));
								$this->save_user($outlet, $adding);
							}
						} else {
							//user does not exist save them
							$this->save_user($outlet, $adding);
						}
						$this->session->set_flashdata('tempdata', ucfirst($adding) . ' successfully editted.');
					}
				} else {
					$added = $this->outletsmodel->insert($outlet);
					if ($added > 0) {
						$this->session->set_flashdata('tempdata', ucfirst($adding) . ' successfully added.');
						//create user now.
						$this->save_user($outlet, $adding);
					} else
						$this->session->set_flashdata('tempdata', 'Sorry could not add ' . $adding . ' details. Please try again.');
				}
				$this->auditmodel->insert("Added a new " . $adding . " in the system (" . $code . "-" . $desc . ")", $added, "", json_encode($outlet));
			}
		}
		redirect(APP_BASE . strtolower($adding));
	}

	private function save_user($outlet, $usertype = 'Retailer', $addedby = 'upload user')
	{
		$cust_cd = $outlet['CUST_CD'];
		$dist_cd = $outlet['DIST_CD'];
		$owner_firstname = $outlet['contactfname'];
		$owner_secondname = $outlet['contactsname'];
		$owner_phone = $outlet['CUST_PHONE'];
		$owner_email = $outlet['email'];

		$password = $this->generatePass();
		$upassword =  password_hash($password, PASSWORD_BCRYPT);

		$u = $this->usersmodel->get(array('recordstate' => 0, 'UserCode' => $owner_phone));
		if ($u->num_rows() > 0) {
			$this->auditmodel->insert("Tried to register APP user details who already exists: Phone: " . $owner_phone . " name : " . $owner_firstname . $owner_secondname, 0, $addedby, json_encode($outlet));
			return;
		}

		$user = array(
			'recordstate' => 0,
			'CreationUser' => $this->session->userdata('username'),
			'CreationDate' => date('Y-m-d H:i:s'),
			'ApproveComment' => "Outlet User Created",
			'ApproveDate' => date('Y-m-d H:i:s'),
			'Firstname' => $owner_firstname,
			'Secondname' => $owner_secondname,
			'Surname' => '',
			'email' => $owner_email,
			'Password' => $upassword,
			'phone' => $owner_phone,
			'UserType' => $usertype,
			'UserCode' => $owner_phone,
			'UserEnabled' => 1,
			'BusinessID' => 1,
			'LastLoginTime' => date('Y-m-d H:i:s'),
			'region' => '',
			'route' => '',
			'CUST_CD' => $cust_cd
		);

		if (empty($addedby))
			$addedby =  $this->session->userdata('username');

		$result = $this->usersmodel->insertObj($user);

		if ($result > 0) {
			if ($usertype == "Retailer") {
				$msg = '<p>Your account has been created on ' . APP_NAME . '.</p>
								<p>Dial ' . APP_USSD . ' to check your balance and redeem.</p>
								<p>Use the following:</p>
								<table border="0" cellpadding="0" cellspacing="0">
								<tr><td>PIN: ' . $password . '</td></tr></tbody>
								</table><br>';
								$sms = $owner_firstname . ", thank you for registering into the " . APP_NAME . ".Your account has been created, PIN:  ". $password .".Dial " . APP_USSD . " to redeem.";
			} else {
				$msg = '<p>Your account has been created on ' . APP_NAME . '.</p>
						<p>Download the Doshi awarding app on playstore ' . APP_URL . '.</p>
						<p>Use the following:</p>
						<table border="0" cellpadding="0" cellspacing="0">
						<tr><td>Username: ' . $owner_phone . '</td></tr></tbody>
						<tr><td>PIN: ' . $password . '</td></tr></tbody>
						<tr><td>Alternatively log in on '. base_url() .'</td></tr></tbody>
						</table><br>';
				$sms = $owner_firstname . ", your account has been created on " . APP_NAME . ". Download Doshi app from " . APP_URL . " or visit ". base_url() ." to award points. Use username: ". $owner_phone  ." PIN: " . $password;
			}

			if (!empty($owner_email))
				$this->msgmodel->insert_comm($owner_email, "email", $msg, APP_NAME . ", account Created", $owner_firstname, $addedby);

			if (!empty($owner_phone))
				$this->msgmodel->insert_comm($owner_phone, "sms", $sms, APP_NAME . ", account Created", $owner_firstname, $addedby);

			$this->auditmodel->insert("Added APP user details: Email: " . $owner_email . " name : " . $owner_firstname . $owner_secondname, $result, $addedby, json_encode($outlet));
		} else {
			$this->auditmodel->insert("Tried to register APP user details: Email: " . $owner_email . " name : " . $owner_firstname . $owner_secondname, $result, $addedby, json_encode($outlet));
		}
	}

	function remove_redemption()
	{
		$this->form_validation->set_rules('code[]', '', 'required');

		if ($this->form_validation->run() == FALSE) {
			$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 {
			//validation OK
			$codes = $this->input->post('code');
			foreach ($codes as $code) {
				$this->cmerchantmodel->update(array('record_state' => 900), array('id' => $code));

				if ($this->db->affected_rows() > 0) {
					$this->auditmodel->insert("Removed outlet details in the system (" . $code . ")", 1, "", json_encode($this->input->post()));
					$this->session->set_flashdata('tempdata', 'Outlet successfully removed.');
				} else {
					$this->auditmodel->insert("Tried to remove a Outlet from the sytem. (" . $code . ")", 0, "", json_encode($this->input->post()));
					$this->session->set_flashdata('tempdata', 'Sorry could not remove outlet details.');
				}
			}
		}
		redirect(APP_BASE . "outlet");
	}

	function checkRedemptionPoint()
	{
		$code = $this->input->get('code');
		$outlets = $this->cmerchantmodel->get(array('merchantcode' => $code, 'record_state' => 0));
		if ($outlets->num_rows() > 0)
			echo json_encode(array('result' => 'FAIL', 'message' => 'Outlet Code Already Exists'));
		else
			echo json_encode(array('result' => 'OK', 'message' => ''));
	}

	private function generatePin()
	{
		$word = "";
		$pick = '123456789';
		$length = 4;
		while (strlen($word) < $length) {
			$word .= substr($pick, mt_rand() % (strlen($pick)), 1);
		}
		return $word;
	}

	function save_redemption_point()
	{
		$action = $this->input->post('action');

		$this->form_validation->set_rules('code', 'Outlet Code', 'required');
		$this->form_validation->set_rules('name', 'Outlet Name', 'required');
		$this->form_validation->set_rules('phoneno', 'Phone number', 'required');

		if ($this->form_validation->run() == FALSE) {
			$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 {
			//validation OK
			$code = $this->input->post('code');
			$desc = $this->input->post('name');
			$phone = $this->input->post('phoneno');

			$dists = $this->cmerchantmodel->get(array('merchantcode' => $code, 'record_state' => 0));

			if ($dists->num_rows() > 0  && empty($action)) {
				$this->auditmodel->insert("Tried to add a outlet in the sytem. Details already exists (" . $code . "-" . $desc . ")", 0, "", json_encode($this->input->post()));
				$this->session->set_flashdata('tempdata', 'Sorry could not add outlet.Code or phone number already exists.');
			} else {

				$rcode = $this->generatePin();
				$distsr = $this->cmerchantmodel->get(array('dmo_id' => $rcode, 'record_state' => 0));
				while ($distsr->num_rows() > 0) {
					$rcode = $this->generatePin();
					$distsr = $this->cmerchantmodel->get(array('dmo_id' => $rcode, 'record_state' => 0));
				}


				$distributor = array(
					'merchantcode' => strtoupper($code),
					'name' => $this->input->post('name'),
					'type' => $this->input->post('phoneno'),
					'description' => $this->input->post('email'),
					'dmo_id' => $rcode,
					'isexternal' => 0,
					'record_state' => 0
				);

				if ($action == "edit") {
					$id = $this->input->post('id');
					$distcode =  $this->input->post('code');
					$distcode = strtoupper($distcode);

					$phonenos = $this->cmerchantmodel->get(array('type' => $phone, 'id <>' => $id, 'record_state' => 0));
					$distss = $this->cmerchantmodel->get(array('merchantcode' => $distcode, 'id <>' => $id, 'record_state' => 0));

					if ($phonenos->num_rows() > 0 || $distss->num_rows() > 0) {
						$this->session->set_flashdata('tempdata', "Sorry could not update details. Phone number or code is already used by another outlet.");
						$added = 0;
					} else {
						$prevcodes =  $this->cmerchantmodel->get(array('id' => $id, 'record_state' => 0));
						$distributor['dmo_id'] = $prevcodes->row()->dmo_id;
						$this->cmerchantmodel->update($distributor, array('id' => $id));

						if ($prevcodes->num_rows() > 0) {
							$prevcode = $prevcodes->row();

							if ($prevcode->merchantcode != $distcode) {
								$this->outletsmodel->update(array('merchantcode' => $distcode), array('merchantcode' => $prevcode->merchantcode));
							}
						}
						$added = 1;
						$this->session->set_flashdata('tempdata', 'Outlet successfully editted.');
					}
				} else {
					$added = $this->cmerchantmodel->insert_local($distributor);
					if ($added > 0)
						$this->session->set_flashdata('tempdata', 'Outlet successfully added.');
					else
						$this->session->set_flashdata('tempdata', 'Sorry could not add outlet details. Please try again.');
				}
				$this->auditmodel->insert("Added a new Outlet in the system (" . $code . "-" . $desc . ")", $added, "", json_encode($distributor));
			}
		}
		redirect(APP_BASE . "outlet");
	}


	private function generatePass()
	{
		$word = "";
		$pick = '0123456789';
		$length = 4;
		while (strlen($word) < $length) {
			$word .= substr($pick, mt_rand() % (strlen($pick)), 1);
		}
		return $word;
	}

	function remove_wholesaler()
	{
		$this->form_validation->set_rules('code[]', 'Select record to remove', 'required');

		if ($this->form_validation->run() == FALSE) {
			$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 {
			//validation OK
			$codes = $this->input->post('code');
			$adding = $this->input->post('adding');
			foreach ($codes as $code) {
				$this->outletsmodel->update(array('record_state' => 900), array('CUST_CD' => $code, 'record_state' => 0));

				if ($this->db->affected_rows() > 0) { 
					$this->currentaccmodel->update(array('record_state' => 900), array('CUST_CD' => $code, 'record_state' => 0));
					$this->earnhistorymodel->update(array('record_state' => 900), array('CUST_CD' => $code, 'record_state' => 0));
					$this->usersmodel->update(array('recordstate' => 900), array('CUST_CD' => $code, 'recordstate' => 0));
					$this->targetsmodel->update(array('record_state' => 900), array('CUST_CD' => $code, 'record_state' => 0));
					$this->auditmodel->insert("Removed " . $adding . "  details in the system (" . $code . ")", 1, "", json_encode($this->input->post()));
					$this->session->set_flashdata('tempdata', ucfirst($adding) . ' successfully removed.');
				} else {
					$this->auditmodel->insert("Tried to remove " . $adding . " from the sytem. (" . $code . ")", 0, "", json_encode($this->input->post()));
					$this->session->set_flashdata('tempdata', 'Sorry could not remove ".$adding."  details.');
				}
			}
		}
		redirect(APP_BASE . "retailers");
	}
	/*
	function remove_opt_out(){
		$this->form_validation->set_rules('id', 'User', 'required');
		$this->form_validation->set_rules('reason', 'reason', 'required');
		$this->form_validation->set_rules('action', 'action', 'required');
		if ($this->form_validation->run() == FALSE){
			$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 {
			$code = $this->input->post('id');
			$reason = $this->input->post('reason');
			$action = $this->input->post('action');

			if($action=="opt"){
				$this->outletsmodel->update(array('record_state'=> 900,'SUBCHANNEL'=>$reason), array('id'=> $code,'record_state'=>0));
			
				if($this->db->affected_rows()>0){
					$this->auditmodel->insert("Confrimed opt out details in the system user id (".$code .")",1,"");
					$this->session->set_flashdata('tempdata','Opt out successfully confirmed.');
				}else{
					$this->auditmodel->insert("Tried to confirm opt out from the system. (".$code .")",0,"");
					$this->session->set_flashdata('tempdata','Sorry could not opt out details.');
				}
			}else{
				$this->outletsmodel->update(array('record_state'=> 0,'LONGITUDE'=>0), array('id'=> $code,'record_state'=>0));
				if($this->db->affected_rows()>0){
					$this->auditmodel->insert("Cancelled opt out details in the system user id (".$code .") reason (".$reason .")",1,"");
					$this->session->set_flashdata('tempdata','Cancelled opt out successfully confirmed.');
				}else{
					$this->auditmodel->insert("Tried to confirm opt out from the system. (".$code .") reason (".$reason .")",0,"");
					$this->session->set_flashdata('tempdata','Sorry could not cancel opt out details.');
				}
			}

			
		}
		redirect(APP_BASE ."opt_out");
	}*/

	function upload_Outlets()
	{
		$uploadFile = './_temp/';
		$config['upload_path'] = $uploadFile;
		$config['allowed_types'] = 'csv';
		$config['max_size']	= '25600';
		$uploadedFile = "";

		$this->load->library('upload', $config);

		if (!$this->upload->do_upload()) {
			$data =  $this->upload->display_errors();
			$flashdata = "Sorry could not upload the retailers file. Error " . $data;
		} else {
			$data = $this->upload->data();
			$uploadedFile = $data["file_name"];
			// [file_ext] => .xlsx 

			$user = $this->session->userdata('username');
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, base_url() . "outlets/readxls/" . urlencode(base64_encode($uploadedFile)) . "/" . urlencode(base64_encode($user)));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000);
			$apiresult = curl_exec($ch);
			curl_close($ch);
			$flashdata = "Retailers file uploaded. You shall be notified once all records are processed.";
		}
		$this->session->set_flashdata('tempdata', $flashdata);
		redirect(APP_BASE . 'retailer');
	}



	function readxls($filename, $user)
	{
		set_time_limit(0);

		$count = 0;
		$time = date('Y-m-d H:i:s');
		$filename = base64_decode(urldecode($filename));
		$user = base64_decode(urldecode($user));

		$outlets = array();
		$distributors = array();
		$targets = array();
		$line = 0;

		$file = fopen("./_temp/" . $filename, "r");
		$array = array();
		while (!feof($file)) {
			$array[] = fgetcsv($file);
		}
		fclose($file);

		foreach ($array as $row) {
			$added = 0;
			if ($line == 0) {
				$line++;
				continue;
			}

			$dboutlets = $this->outletsmodel->get(array('CUST_CD' => trim($row[0]), 'record_state' => 0));
			$dboutletsphone = $this->outletsmodel->get(array('CUST_PHONE' => trim($row[5]), 'record_state' => 0));

			if (strlen($row[5]) != 10) {
				$this->auditmodel->insert("Record processing failed rec (" . json_encode($row) . "). Invalid phone number provided " .  $row[5], $added, $user);
				continue;
			}
			/**
			 * Retailer Code,Physical location,Retailer name,Contact Firstname,
			 * Contact Second name,Contact phone,Contact email,Region (refer to system locations),
			 * Territory (refer to system locations)
			 */

			if (
				$dboutlets->num_rows() == 0  && $dboutletsphone->num_rows() == 0
				&& !empty($row[0])
				&&  !in_array($row[0], array_column($outlets, 'CUST_CD'))
				&&  !empty($row[1]) &&  !empty($row[2]) &&  !empty($row[3])
				&&  !empty($row[4]) &&  !empty($row[5])
				&&  !empty($row[7]) &&  !empty($row[8])
			) {

				$territories = $this->regionsmodel->get(array('region' => $row[8], 'recordstate' => 0));
				$regions = $this->territorymodel->get(array('territory' => $row[7], 'recordstate' => 0));

				if ($regions->num_rows() > 0 && $territories->num_rows() > 0) {
					$outlets[] = array(
						'CUST_CD' => strtoupper(trim($row[0])),
						'DIST_CD' => 'Retailer',
						'CUST_NAME' => strtoupper(trim($row[2])),
						'contactfname' => $row[3],
						'contactsname' => $row[4],
						'CUST_PHONE' =>  $row[5],
						'email' =>   $row[6],
						'TERRITORY' => $regions->row()->id, //this will hold region
						'ROUTE' =>  $territories->row()->id,
						'AREA' => $row[1],
						'BE_CUST_CD' => '',
						'CUST_STATUS' => '1',
						'OBOS' => '',
						'CHANNEL' => '',
						'SUBCHANNEL' => '',
						'SEGMENT' => '',
						'LONGITUDE' => 0,
						'LATITUDE' => 0,
						'addedon' => $time,
						'addedby' => $user
					);
					$count++;
				} else
					$this->auditmodel->insert("Record processing failed rec (" . json_encode($row) . ").Not Location details missing either region or territory missing.", $added, $user);
			} else
				$this->auditmodel->insert("Record processing failed rec (" . json_encode($row) . ").Not all columns are present.", $added, $user);

			$line++;
		}

		if (count($outlets) > 0) {
			$added = $this->outletsmodel->multi_insert($outlets);
			$this->auditmodel->insert("Added new retailer in the system via file upload (" . $filename . "). (" . $count . ") retailers saved.", $added, $user);
			for ($i = 0; $i < count($outlets); $i++) {
				$this->save_user($outlets[$i], 'Retailer', $user);
			}
		}

		$this->notificationsmodel->insert($user, " Retailers file successfully Processed. (" . $count . ") retailers saved.");
		//@unlink("./_temp/".$filename);
	}
}
