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

	public function __construct()
	{
		parent::__construct();
		$this->load->model('templatemodel');
		$this->load->model('earnsmodel');
		$this->load->model('redeemsmodel');
		$this->load->model('auditmodel');
		$this->load->model('outletsmodel');
		$this->load->model('currentaccmodel');
		$this->load->model('categoriesmodel');
		$this->load->model('dealsmodel');
		$this->load->model('productsmodel');
		$this->load->model('notificationsmodel');
		$this->load->library('form_validation');
	} 

    public function index(){
        show_404();
	}

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

		$uploadfrom = $this->input->post('uploadfrom');
		
		$this->load->library('upload', $config);

		if (!$this->upload->do_upload()) {
			$data =  $this->upload->display_errors();
			$flashdata = "Sorry could not upload the product grouping file. Error " . $data;
		} else {
			$data = $this->upload->data();
			$uploadedFile = $data["file_name"];
			$user = $this->session->userdata('username');
			$url = base_url() . "common/readxls" . "/" . urlencode(base64_encode($uploadedFile)) . "/" . urlencode(base64_encode($user));
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000);
			$apiresult = curl_exec($ch);
			curl_close($ch);
			$flashdata = "File uploaded. You shall be notified once all records are processed.";
		}
		$this->session->set_flashdata('tempdata', $flashdata);
		redirect(APP_BASE ."stockist_grouping");
	}


	function readxls($filename, $user)
	{
		set_time_limit(0);
		$count = 0;
		$filename = base64_decode(urldecode($filename));
		$user = base64_decode(urldecode($user));
		$line = 0;


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

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

			$categorycode = trim($row[0]);
			$categorycode = str_replace(" ","_", strtoupper($categorycode));
			$category = trim($row[0]);

			$cm = $this->categoriesmodel->get(array('categorycode'=> $categorycode,'recordstate'=>0));
			if($cm->num_rows()==0){
				$status = $this->categoriesmodel->insertobj($categorycode,$category,$user);
				$count += $status>0? 1 : 0;
			}else 
				$this->auditmodel->insert("Failed to save grouping  (" . $row[0] . ").Group already exists.", $added, $user);
		}  
		$this->auditmodel->insert("Product grouping file processing done.". $count ." records processed.", $added, $user);
		$this->notificationsmodel->insert($user, " Product grouping file successfully Processed. (" . $count . ") groups added.");
	}

	public function addCategory(){
		$this->form_validation->set_rules('catcode', 'Category Code', 'required');
		$this->form_validation->set_rules('category', 'category', 'required');
		
		$username = $this->session->userdata('username');
		
		$id = $this->input->post('id');
		$isstockist = $this->input->post('isstockist');

		$categorycode = $this->input->post('catcode');
		$categorycode = str_replace(" ","_", strtoupper($categorycode));
		$category = $this->input->post('category');

		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 {

			if(!empty($id)){ //update
				$this->categoriesmodel->update(array('categorycode'=> $categorycode,'category'=>$category),array('id'=>$id));
				$status = 900;
			} else {

				$cm = $this->categoriesmodel->get(array('categorycode'=> $categorycode,'recordstate'=>0));
				if($cm->num_rows()==0)
					$status = $this->categoriesmodel->insert();
				else 
					$status = -1;
			}

			if($status >0)
				$this->session->set_flashdata('tempdata',"Grouping successfully saved");
        	else if($status ==-1)
				$this->session->set_flashdata('tempdata',"Sorry could not save grouping. Grouping already exists.");
			else
				$this->session->set_flashdata('tempdata',"Sorry could not save grouping. Please try again.");

			$this->auditmodel->insert("Added a new grouping in the system: ". $category,$status,"", json_encode($this->input->post()));
		}

		if(empty($isstockist))
			redirect(APP_BASE ."brands");
		else 
			redirect(APP_BASE ."stockist_grouping");
	}

	public function deleteCategory(){
		$this->form_validation->set_rules('code[]', 'Product Code', 'required');
		$username = $this->session->userdata('username');
		$isstockist = $this->input->post('isstockist');

		


		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
			$codes = $this->input->post('code');
 
			foreach($codes as $code){

				$r = $this->categoriesmodel->get(array('categorycode'=> $code))->row(); 
				$this->productsmodel->update(array('brand'=>''),array('brand'=>$r->id)); 

				$this->categoriesmodel->update(array('recordstate'=> 900), array('categorycode'=> $code));
			
				if($this->db->affected_rows()>0){
					$this->auditmodel->insert("Removed product group in the system (".$code .")",1,"");
					$this->session->set_flashdata('tempdata','Product group successfully removed.');
				}else{
					$this->auditmodel->insert("Tried to remove product group in the sytem. (".$code .")",0,"",json_encode($this->input->post()));
					$this->session->set_flashdata('tempdata','Sorry could not remove product group.');
				}
			}
		}

		
		if(empty($isstockist) )
		redirect(APP_BASE ."brands");
		else
		redirect(APP_BASE ."stockist_grouping");

	}

	function prod_categories(){
		$prods = $this->categoriesmodel->get(array('recordstate'=>0));
		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 addSmsTemplate(){
		$this->form_validation->set_rules('template', 'SMS Template', 'required');
		$this->form_validation->set_rules('type', 'SMS Type', 'required');
		
		$username = $this->session->userdata('username');
		
		$msg = $this->input->post('template');
		$template = $this->input->post('title');
		$type = $this->input->post('type');
		$id = $this->input->post('id');

		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 {

			if(!empty($id)){ //update
				$this->templatemodel->update(array('template'=> $msg,'type'=>$type),array('id'=>$id));
				$status = 900;
			} else {
				$status = $this->templatemodel->insert();
			}

			if($status >0)
				$this->session->set_flashdata('tempdata',"SMS Template successfully saved");
        	else
				$this->session->set_flashdata('tempdata',"Sorry could not save SMS template. Please try again.");
			$this->auditmodel->insert("Added a new sms template in the system: ". $type,$status,"", json_encode($this->input->post()));
		}
		redirect(APP_BASE ."sms");
	}

	public function deleteSmsTemplate(){
		$id = $this->input->get('template');
		$id=base64_decode($id);
		$this->templatemodel->update(array('status'=> 0), array('id'=>$id));
				
		if($this->db->affected_rows() >0)
			$set_flashdata = "SMS Template successfully deleted.";
        else
			$set_flashdata ="Sorry could not delete SMS template. Please try again.";
		$this->auditmodel->insert("Deleted sms template in the system: ". $id, 1,"");
		echo $set_flashdata;
	}

	public function deleteAppMessage(){
		$id = $this->input->get('template');
		$id=base64_decode($id);
		$this->dealsmodel->update(array('status'=> 0), array('id'=>$id));
				
		if($this->db->affected_rows() >0)
			$set_flashdata="App message successfully deleted.";
        else
			$set_flashdata="Sorry could not delete app message. Please try again.";
		$this->auditmodel->insert("Deleted App message in the system: ". $id, 1,"");
		echo $set_flashdata;
	}

	function brands(){
		$brands = $this->productsmodel->getDistinct(array('record_state'=>0));
		if($brands->num_rows()>0 )
			echo json_encode(array('result'=>'OK', 'message'=>$brands->result_array()));
		else
			echo json_encode(array('result'=>'fail', 'message'=>''));
	}

	public function addAppMessage(){
		$this->form_validation->set_rules('dealname', 'Message title', 'required');
		$this->form_validation->set_rules('expiry', 'Message Expiry', 'required');
		$this->form_validation->set_rules('dealdata', 'Message content', 'required');
		$this->form_validation->set_rules('region', 'Territories covered', 'required');
		$this->form_validation->set_rules('route', 'Route covered', 'required');
 
		$template = $this->input->post('dealname');

		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 {
			$id = $this->input->post('id');
			if(!empty($id)){
				$uploadedFile = @$this->upload_imgs();
				$data = array();
				if(!empty($uploadedFile))
					$data['image'] = $uploadedFile;
				$data['dealname']  = $this->input->post('dealname');
				$data['dealdata']  = $this->input->post('dealdata');
				$expiry =  $this->input->post('expiry');
				$expiry = str_replace("/","-",$expiry);
				$data['expiry']  =  date('Y-m-d H:i:s', strtotime($expiry));
				$data['region']  = $this->input->post('region'); 
				$data['route']  = $this->input->post('route');
				$status = $this->dealsmodel->update($data,array('id'=>$id));
				if($this->db->affected_rows()>0)
					$this->session->set_flashdata('tempdata',"Message successfully editted.");
				else
					$this->session->set_flashdata('tempdata',"Sorry could not update message details.Please try again.");
				$this->auditmodel->insert("Updated app message in the system: ". $template,$status,"", json_encode($data));
			} else {
				$uploadedFile = $this->upload_imgs();
				if(!empty($uploadedFile)){
					$status = $this->dealsmodel->insert($uploadedFile);
					if($status >0)
						$this->session->set_flashdata('tempdata',"Message successfully added.");
					else
						$this->session->set_flashdata('tempdata',"Sorry could not add new App Message. Please try again.");
				} else {
					$this->session->set_flashdata('tempdata',"Sorry please upload a valid image file.");
					$status=0;
				}
				$this->auditmodel->insert("Added a new app message in the system: ". $template,$status,"", json_encode($this->input->post()));
			}
		}
		redirect(APP_BASE ."app_messages");
	}

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

		if ( ! $this->upload->do_upload())
		{
			$data =  $this->upload->display_errors();
		}
		else
		{
			$data =$this->upload->data();
			$uploadedFile = $data["file_name"];
		}
        return $uploadedFile;
	}
	

	function save_eParameters(){
		$this->form_validation->set_rules('awardon', 'Awarding On', 'required');
		//$this->form_validation->set_rules('minimumamount', 'Minimum amount spent', 'required');
		
		$username = $this->session->userdata('username');
		$type = $this->input->post('type');
		$awardon = $this->input->post('awardon');
		$rebates = $this->input->post('rebate');
		$minimumamount = $this->input->post('minimumamount');

		if(strtolower($type)=="percentage" && $awardon=="Total Volume"){
			$this->form_validation->set_rules('rebate', 'Rebate amount', 'required');
		}

		if( $awardon=="Product"){
			$items = $this->productsmodel->get(array('record_state'=>0))->result_array();
			foreach($items as $c){
				$this->form_validation->set_rules($c['product_code'], ucfirst(strtolower($c['product_desc'])). ' Points', 'required');
			}
		} else {
			$this->form_validation->set_rules('type', 'Awarding type', 'required');
			$this->form_validation->set_rules('rebate', 'Rebate amount', 'required');
		}
		
		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
			$rebate = array();

			$this->earnsmodel->update(array('record_state'=>900),array('record_state'=>0));
			$time = date('Y-m-d H:i:s');
			$user = $this->session->userdata('username');
			$data = $this->input->post();

			if($awardon=="Total Volume"){
				$rebate[] = array(
					'awardon' => $awardon,
					'type' => $type,
					'item' =>  'Rebate',
					'value' => $rebates, 
					'addedon' => $time,
					'addedby' => $user
				);
			} else {
				foreach($data as $item=>$value){
					if($item != 'id' && $item != 'type'  && $item != 'rebate'  && $item != 'minimumamount' && $item != 'awardon'){
						$rebate[] = array(
							'awardon' => $awardon,
							'type' => "Amount",
							'item' =>  $item,
							'value' => $value, 
							'addedon' => $time,
							'addedby' => $user
						);

						//update products with new points 
						$this->productsmodel->update(array('uom'=>$value), array('product_code'=>$item));
					}
				}
			}

			if(sizeof($rebate)>0)
				$added = $this->earnsmodel->multi_insert($rebate);
			else
				$added =900;
			$this->auditmodel->insert("Added a new earning details in the system ",$added,"",json_encode($rebate));
			$this->session->set_flashdata('tempdata',$added>0?'Earning  settings successfully added.':'Sorry could not add earning settings. Please try again.');
		}
		redirect(APP_BASE ."earn_settings");
	}
	 
	function save_rParameters(){
		$this->form_validation->set_rules('minimum', 'Minimum Redeemable value', 'required');
		$this->form_validation->set_rules('cash', 'Redemption currency rate', '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 {
			//validation OK
			$code = $this->input->post('minimum');
			$desc = $this->input->post('expiry');
			$expire = $this->input->post('expire');

			$rebate = array();

			$prev = $this->redeemsmodel->get(array('item'=>'Redemption Rate KSH','record_state'=>0));

			$this->redeemsmodel->update(array('record_state'=>900),array('record_state'=>0));
			$time = date('Y-m-d H:i:s');
			$user = $this->session->userdata('username');
			$mexpiry = $expire==1?$desc:0;

			$rebate[] = array(
				'item' => 'Redemption Rate KSH',
				'category' => '',
				'value' => $this->input->post('cash'),
				'addedon' => $time,
				'addedby' => $user
			);

			$rebate[] = array(
				'item' => 'Minimum Redeemable',
				'category' => '',
				'value' => $this->input->post('minimum'),
				'addedon' => $time,
				'addedby' => $user
			);

			if($expire==1){
				$rebate[] = array( 
					'item' => 'Expiry (Months)', 
					'category' => '',
					'value' => $this->input->post('expiry'), //months
					'addedon' => $time,
					'addedby' => $user
				);
			}

			$added = $this->redeemsmodel->multi_insert($rebate);
			
			$this->auditmodel->insert("Added a new redemption settings in the system : ". json_encode($rebate),$added,"",json_encode($rebate));
			$this->session->set_flashdata('tempdata',$added>0?'Parameters values successfully added.':'Sorry could not add redemption details. Please try again.');
		}
		redirect(APP_BASE ."redeem_settings");
	}
}
