<?php
class ControllerMemberMember extends Controller {
	private $error = array();

	public function index() {
		$this->load->language('member/member');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('member/member');

		$this->getList();
	}

	public function add() {
		$this->load->language('member/member');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('member/member');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_member_member->addMember(
				$this->request->post['external_member_id'], 
				$this->request->post['first_name'],
				$this->request->post['last_name'],
				$this->request->post['email'],
				$this->request->post['phone_no'],
				$this->request->post['gender'],
				$this->request->post['date_of_birth'],
				$this->request->post['tier_setting_id'],
				$this->request->post['tier_expiry_date'],
				$this->request->post['total_tier_achieved_purchase'],
				$this->request->post['status']
			);

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('member/member', 'user_token=' . $this->session->data['user_token'] . $url, true));
		}

		$this->getForm();
	}

	public function edit() {
		$this->load->language('member/member');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('member/member');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_member_member->editMember(
			$this->request->get['member_id'], 
			$this->request->post['external_member_id'], 
			$this->request->post['first_name'],
			$this->request->post['last_name'],
			$this->request->post['email'],
			$this->request->post['phone_no'],
			$this->request->post['gender'],
			$this->request->post['date_of_birth'],
			$this->request->post['tier_setting_id'],
			$this->request->post['tier_expiry_date'],
			$this->request->post['total_tier_achieved_purchase'],
			$this->request->post['status']);

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('member/member', 'user_token=' . $this->session->data['user_token'] . $url, true));
		}

		$this->getForm();
	}

	public function delete() {
		$this->load->language('member/member');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('member/member');
		$log = new Log('Member.log');

		if (isset($this->request->post['selected']) && !empty($this->request->post['selected'])   && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $member_id) {
				$this->model_member_member->deleteMember($member_id);
				$log->write('Delete Member - Member Id: ' . $member_id . ' been deleted by User: ' . $this->session->data['user_id'] . ' ' . $this->session->data['username']);
			}
			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('member/member', 'user_token=' . $this->session->data['user_token'] . $url, true));
		}

		$this->getList();
	}

	public function export() {
		$export = new Export();
		$this->load->model('member/member');
		
		if (isset($this->request->get['filter_name'])) {
			$filter_name = $this->request->get['filter_name'];
		} else {
			$filter_name = '';
		}

		if (isset($this->request->get['filter_email'])) {
			$filter_email = $this->request->get['filter_email'];
		} else {
			$filter_email = '';
		}

		if (isset($this->request->get['filter_phone_no'])) {
			$filter_phone_no = $this->request->get['filter_phone_no'];
		} else {
			$filter_phone_no = '';
		}

		if (isset($this->request->get['filter_status'])) {
			$filter_status = $this->request->get['filter_status'];
		} else {
			$filter_status = '';
		}

		if (isset($this->request->get['filter_date_added'])) {
			$filter_date_added = $this->request->get['filter_date_added'];
		} else {
			$filter_date_added = '';
		}

		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'first_name';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'ASC';
		}

		$filter_data = array(
			'filter_name'        	   => $filter_name,
			'filter_email'             => $filter_email,
			'filter_phone_no' 		   => $filter_phone_no,
			'filter_status'            => $filter_status,
			'filter_date_added'        => $filter_date_added,
			'sort'                     => $sort,
			'order'                    => $order
		);
		$results = $this->model_member_member->getMembers($filter_data);

		// Create an empty array to store the CSV data
		$csvData = array();
		// Add the headers as the first row
		$csvData[] = array(
			'Member ID',
			'External Member ID',
			'First Name',
			'Last Name',
			'Email',
			'Phone No',
			'Gender',
			'Date of Birth',
			'Tier Setting ID',
			'Tier Level',
			'Tier Expiry Date',
			'Total Available Point',
			'Total Tier Achieved Purchase',
			'Updated By',
			'Updated Date',
			'Status',
			'Date Added'
		);

		foreach ($results as $result) {
			$csvData[] = array(
				$result['member_id'],
				$result['external_member_id'],
				$result['first_name'],
				$result['last_name'],
				$result['email'],
				$result['phone_no'],
				$result['gender'],
				!empty($result['date_of_birth']) ? date($this->language->get('date_format_short'), strtotime($result['date_of_birth'])) : "",
				$result['tier_setting_id'],
				$result['tier_level'],
				date($this->language->get('date_format_short'), strtotime($result['tier_expiry_date'])),
				$result['total_available_point'],
				$this->currency->format($result['total_tier_achieved_purchase'], 'MYR'),
				$result['updated_by'],
				date($this->language->get('date_format_long'), strtotime($result['updated_date'])),
				($result['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled')),
				date($this->language->get('date_format_short'), strtotime($result['created_date'])),
				);
		}
		$export -> exportToCSV($csvData);
	}

	public function addMemberReward(){
		$this->load->language('member/member');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('member/member');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateMemberRewardForm()) {
			$data = array(
				'memberid' => $this->request->get['member_id'],
				'rewardid' => $this->request->post['reward_setting_id'],
				'updatedby'  => $this->user->getUserName(),
				'hash' => MD5($this->request->get['member_id'].
				$this->request->post['reward_setting_id'].
				$this->user->getUserName().API_KEY)
			);
			if($this->redeemReward($data)){

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}
				$this->response->redirect($this->url->link('member/member', 'user_token=' . $this->session->data['user_token'] . $url, true));
			}
		}

		$this->getMemberRewardForm();
	}

	public function reward() {
		$json = array();

		$this->load->model('member/member');
		$reward_info = $this->model_member_member->getSelectedRewardInfo($this->request->get['reward_setting_id']);

		if ($reward_info) {
			$json = array(
				'reward_setting_id' => $reward_info['reward_setting_id'],
				'point'        		=> $reward_info['point'],
				'promotion_point'   => $reward_info['promotion_point'],
				'reward_promotion_setting_id'   => $reward_info['reward_promotion_setting_id'],
				'value'       		=> $reward_info['value'],
				'expiry'      		=> $reward_info['expiry']
			);
		}
		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	protected function getList() {
		if (isset($this->request->get['filter_name'])) {
			$filter_name = $this->request->get['filter_name'];
			$data['filter_name'] = $filter_name;
		} else {
			$filter_name = '';
			$data['filter_name'] = '';
		}

		if (isset($this->request->get['filter_email'])) {
			$filter_email = $this->request->get['filter_email'];
			$data['filter_email'] = $filter_email;
		} else {
			$filter_email = '';
			$data['filter_email'] = '';
		}

		if (isset($this->request->get['filter_phone_no'])) {
			$filter_phone_no = $this->request->get['filter_phone_no'];
			$data['filter_phone_no'] = $filter_phone_no;
		} else {
			$filter_phone_no = '';
			$data['filter_phone_no'] = '';
		}

		if (isset($this->request->get['filter_status'])) {
			$filter_status = $this->request->get['filter_status'];
			$data['filter_status'] = $filter_status;
		} else {
			$filter_status = '';
			$data['filter_status'] = '';
		}

		if (isset($this->request->get['filter_date_added'])) {
			$filter_date_added = $this->request->get['filter_date_added'];
			$data['filter_date_added'] = $filter_date_added;
		} else {
			$filter_date_added = '';
			$data['filter_date_added'] = '';
		}

		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'first_name';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'ASC';
		}

		if (isset($this->request->get['page'])) {
			$page = (int)$this->request->get['page'];
		} else {
			$page = 1;
		}

		$url = '';

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['user_token'] = $this->session->data['user_token'];

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('member/member', 'user_token=' . $this->session->data['user_token'] . $url, true)
		);

		$data['add'] = $this->url->link('member/member/add', 'user_token=' . $this->session->data['user_token'] . $url, true);
		$data['delete'] = $this->url->link('member/member/delete', 'user_token=' . $this->session->data['user_token'] . $url, true);

		$data['users'] = array();

		$filter_data = array(
			'filter_name'        	   => $filter_name,
			'filter_email'             => $filter_email,
			'filter_phone_no' 		   => $filter_phone_no,
			'filter_status'            => $filter_status,
			'filter_date_added'        => $filter_date_added,
			'sort'                     => $sort,
			'order'                    => $order,
			'start'                    => ($page - 1) * $this->config->get('config_limit_admin'),
			'limit'                    => $this->config->get('config_limit_admin')
		);

		$member_total = $this->model_member_member->getTotalMembers($filter_data);
		$results = $this->model_member_member->getMembers($filter_data);

		foreach ($results as $result) {
			$data['members'][] = array(
				'member_id'			           => $result['member_id'],
				'external_member_id'		   => $result['external_member_id'],
				'first_name'   				   => $result['first_name'],
				'last_name'   				   => $result['last_name'],
				'email'   		        	   => $result['email'],
				'phone_no'					   => $result['phone_no'],
				'gender'   	            	   => $result['gender'],
				'date_of_birth'   	    	   => !empty($result['date_of_birth']) ? date($this->language->get('date_format_short'), strtotime($result['date_of_birth'])) : "",
				'tier_setting_id'      	 	   => $result['tier_setting_id'],
				'tier_level'                   => $result['tier_level'],
				'tier_expiry_date'   		   => date($this->language->get('date_format_short'), strtotime($result['tier_expiry_date'])),
				'total_available_point'        => $result['total_available_point'],
				'total_tier_achieved_purchase' => $this->currency->format($result['total_tier_achieved_purchase'], 'MYR'),
				'updated_by'            	   => $result['updated_by'],
				'updated_date'          	   => date($this->language->get('date_format_short'), strtotime($result['updated_date'])),
				'status'     				   => ($result['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled')),
				'date_added' 				   => date($this->language->get('date_format_short'), strtotime($result['created_date'])),
				'edit'       				   => $this->url->link('member/member/edit', 'user_token=' . $this->session->data['user_token'] . '&member_id=' . $result['member_id'] . $url, true),
				'add_reward'       			   => $this->url->link('member/member/addMemberReward', 'user_token=' . $this->session->data['user_token'] . '&member_id=' . $result['member_id'] . $url, true),
				'add_point'       			   => $this->url->link('member/point/add', 'user_token=' . $this->session->data['user_token'] . '&member_id=' . $result['member_id'] . $url, true)
			);
		}

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->session->data['success'])) {
			$data['success'] = $this->session->data['success'];

			unset($this->session->data['success']);
		} else {
			$data['success'] = '';
		}

		if (isset($this->request->post['selected'])) {
			$data['selected'] = (array)$this->request->post['selected'];
		} else {
			$data['selected'] = array();
		}

		$url = '';

		if ($order == 'ASC') {
			$url .= '&order=DESC';
		} else {
			$url .= '&order=ASC';
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['sort_first_name'] = $this->url->link('member/member', 'user_token=' . $this->session->data['user_token'] . '&sort=first_name' . $url, true);
		$data['sort_status'] = $this->url->link('member/member', 'user_token=' . $this->session->data['user_token'] . '&sort=status' . $url, true);
		$data['sort_date_added'] = $this->url->link('member/member', 'user_token=' . $this->session->data['user_token'] . '&sort=date_added' . $url, true);

		$url = '';

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		$pagination = new Pagination();
		$pagination->total = $member_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_limit_admin');
		$pagination->url = $this->url->link('member/member', 'user_token=' . $this->session->data['user_token'] . $url . '&page={page}', true);

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($member_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($member_total - $this->config->get('config_limit_admin'))) ? $member_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $member_total, ceil($member_total / $this->config->get('config_limit_admin')));

		$data['sort'] = $sort;
		$data['order'] = $order;

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('member/member_list', $data));
	}

	protected function getForm() {
		$data['text_form'] = !isset($this->request->get['member_id']) ? $this->language->get('text_add') : $this->language->get('text_edit');
		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->error['first_name'])) {
			$data['error_first_name'] = $this->error['first_name'];
		} else {
			$data['error_first_name'] = '';
		}

		if (isset($this->error['last_name'])) {
			$data['error_last_name'] = $this->error['last_name'];
		} else {
			$data['error_last_name'] = '';
		}

		if (isset($this->error['external_member_id'])) {
			$data['error_external_member_id'] = $this->error['external_member_id'];
		} else {
			$data['error_external_member_id'] = '';
		}

		if (isset($this->error['email'])) {
			$data['error_email'] = $this->error['email'];
		} else {
			$data['error_email'] = '';
		}

		if (isset($this->error['phone_no'])) {
			$data['error_phone_no'] = $this->error['phone_no'];
		} else {
			$data['error_phone_no'] = '';
		}

		if (isset($this->error['phone_no'])) {
			$data['error_phone_no'] = $this->error['phone_no'];
		} else {
			$data['error_phone_no'] = '';
		}

		if (isset($this->error['total_tier_achieved_purchase'])) {
			$data['error_total_tier_achieved_purchase'] = $this->error['total_tier_achieved_purchase'];
		} else {
			$data['error_total_tier_achieved_purchase'] = '';
		}

		$url = '';

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('user/user', 'user_token=' . $this->session->data['user_token'] . $url, true)
		);

		if (!isset($this->request->get['member_id'])) {
			$data['action'] = $this->url->link('member/member/add', 'user_token=' . $this->session->data['user_token'] . $url, true);
		} else {
			$data['action'] = $this->url->link('member/member/edit', 'user_token=' . $this->session->data['user_token'] . '&member_id=' . $this->request->get['member_id'] . $url, true);
		}

		$data['cancel'] = $this->url->link('member/member', 'user_token=' . $this->session->data['user_token'] . $url, true);

		if (isset($this->request->get['member_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
			$member_info = $this->model_member_member->getMember($this->request->get['member_id']);
		}

		if (isset($this->request->post['external_member_id'])) {
			$data['external_member_id'] = $this->request->post['external_member_id'];
		} elseif (!empty($member_info)) {
			$data['external_member_id'] = $member_info['external_member_id'];
		} else {
			$data['external_member_id'] = '';
		}

		if (isset($this->request->post['first_name'])) {
			$data['first_name'] = $this->request->post['first_name'];
		} elseif (!empty($member_info)) {
			$data['first_name'] = $member_info['first_name'];
		} else {
			$data['first_name'] = '';
		}

		if (isset($this->request->post['last_name'])) {
			$data['last_name'] = $this->request->post['last_name'];
		} elseif (!empty($member_info)) {
			$data['last_name'] = $member_info['last_name'];
		} else {
			$data['last_name'] = '';
		}

		if (isset($this->request->post['email'])) {
			$data['email'] = $this->request->post['email'];
		} elseif (!empty($member_info)) {
			$data['email'] = $member_info['email'];
		} else {
			$data['email'] = '';
		}

		if (isset($this->request->post['phone_no'])) {
			$data['phone_no'] = $this->request->post['phone_no'];
		} elseif (!empty($member_info)) {
			$data['phone_no'] = $member_info['phone_no'];
		} else {
			$data['phone_no'] = '';
		}

		if (isset($this->request->post['gender'])) {
			$data['gender'] = $this->request->post['gender'];
		} elseif (!empty($member_info)) {
			$data['gender'] = $member_info['gender'];
		} else {
			$data['gender'] = '';
		}

		if (isset($this->request->post['date_of_birth'])) {
			$data['date_of_birth'] = $this->request->post['date_of_birth'];
		} elseif (!empty($member_info)) {
			$data['date_of_birth'] = $member_info['date_of_birth'];
		} else {
			$data['date_of_birth'] = '';
		}

		if (isset($this->request->post['tier_setting_id'])) {
			$data['tier_setting_id'] = $this->request->post['tier_setting_id'];
		} elseif (!empty($member_info)) {
			$data['tier_setting_id'] = $member_info['tier_setting_id'];
		} else {
			$data['tier_setting_id'] = '';
		}

		if (isset($this->request->post['tier_expiry_date'])) {
			$data['tier_expiry_date'] = $this->request->post['tier_expiry_date'];
		} elseif (!empty($member_info)) {
			$data['tier_expiry_date'] = $member_info['tier_expiry_date'];
		} else {
			$data['tier_expiry_date'] = '';
		}

		if (isset($this->request->post['total_available_point'])) {
			$data['total_available_point'] = $this->request->post['total_available_point'];
		} elseif (!empty($member_info)) {
			$data['total_available_point'] = $member_info['total_available_point'];
		} else {
			$data['total_available_point'] = '0';
		}

		if (isset($this->request->post['total_tier_achieved_purchase'])) {
			$data['total_tier_achieved_purchase'] = $this->request->post['total_tier_achieved_purchase'];
		} elseif (!empty($member_info)) {
			$data['total_tier_achieved_purchase'] = $member_info['total_tier_achieved_purchase'];
		} else {
			$data['total_tier_achieved_purchase'] = '0';
		}

		if (isset($this->request->post['status'])) {
			$data['status'] = $this->request->post['status'];
		} elseif (!empty($tier_info)) {
			$data['status'] = $tier_info['status'];
		} else {
			$data['status'] = 0;
		}
		$data['user_token'] = $this->session->data['user_token'];
		$this->load->model('reward/tier');

		$data['tier_levels'] = $this->model_reward_tier->getTiersLevel(); 

		$this->response->setOutput($this->load->view('member/member_form', $data));
	}

	protected function getMemberRewardForm() {
		$data['text_form'] = $this->language->get('text_add_member_reward');
		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->error['used_point'])) {
			$data['error_used_point'] = $this->error['used_point'];
		} else {
			$data['error_used_point'] = '';
		}

		if (isset($this->error['value'])) {
			$data['error_value'] = $this->error['value'];
		} else {
			$data['error_value'] = '';
		}

		if (isset($this->error['expiry_date'])) {
			$data['error_expiry_date'] = $this->error['expiry_date'];
		} else {
			$data['error_expiry_date'] = '';
		}

		$url = '';

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('user/user', 'user_token=' . $this->session->data['user_token'] . $url, true)
		);

		if (!isset($this->request->get['member_reward_id'])) {
			$data['action'] = $this->url->link('member/member/addMemberReward', 'user_token=' . $this->session->data['user_token'] . '&member_id=' . $this->request->get['member_id'] . $url, true);
		} else {
			$data['action'] = $this->url->link('member/member/editMemberReward', 'user_token=' . $this->session->data['user_token'] . '&member_id=' . $this->request->get['member_id'] . $url, true);
		}

		$data['cancel'] = $this->url->link('member/member', 'user_token=' . $this->session->data['user_token'] . $url, true);

		if (isset($this->request->get['member_id'])) {
			$member_info = $this->model_member_member->getMember($this->request->get['member_id']);
			$rewards = $this->model_member_member->getMemberAvailableRewards($this->request->get['member_id']);
		}

		foreach ($rewards as $reward) {
			$data['rewards'][] = array(
				'reward_setting_id'	=> $reward['reward_setting_id'],
				'title'		 		=> $reward['title']
			);
		}
		if (!empty($member_info)) {
			$data['external_member_id'] = $member_info['external_member_id'];
			$data['phone_no'] = $member_info['phone_no'];
			$data['email'] = $member_info['email'];
			$data['tier_setting_id'] = $member_info['tier_setting_id'];
			$data['tier_level'] = $member_info['tier_level'];
		} else {
			$data['external_member_id'] = '';
			$data['phone_no'] = '';
			$data['email'] = '';
			$data['tier_setting_id'] = '';
			$data['tier_level'] = '';
		}
		$data['user_token'] = $this->session->data['user_token'];
		$this->response->setOutput($this->load->view('member/assign_member_reward_form', $data));
	}

	protected function validateForm() {
		unset($error);

		if (!$this->user->hasPermission('modify', 'member/member')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		if ((utf8_strlen($this->request->post['external_member_id']) < 3) || (utf8_strlen($this->request->post['external_member_id']) > 200)) {
			$this->error['external_member_id'] = $this->language->get('error_external_id');
		}

		if ((utf8_strlen($this->request->post['first_name']) < 3) || (utf8_strlen($this->request->post['first_name']) > 200)) {
			$this->error['first_name'] = $this->language->get('error_first_name');
		}

		if ((utf8_strlen($this->request->post['last_name']) < 3) || (utf8_strlen($this->request->post['last_name']) > 200)) {
			$this->error['last_name'] = $this->language->get('error_last_name');
		}

		if ((utf8_strlen($this->request->post['email']) > 96) || !filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL)) {
			$this->error['email'] = $this->language->get('error_email');
		}

		$member_info = $this->model_member_member->getMemberByEmail($this->request->post['email']);

		if (!isset($this->request->get['member_id'])) {
			if ($member_info) {
				$this->error['warning'] = $this->language->get('error_exists_email');
			}
		} else {
			if ($member_info && ($this->request->get['member_id'] != $member_info['member_id'])) {
				$this->error['warning'] = $this->language->get('error_exists_email');
			}
		}

		if ((utf8_strlen($this->request->post['phone_no']) < 3) || (utf8_strlen($this->request->post['phone_no']) > 32)) {
			$this->error['phone_no'] = $this->language->get('error_phone_no');
		}

		$member_info2 = $this->model_member_member->getMemberByPhoneNo($this->request->post['phone_no']);

		if (!isset($this->request->get['member_id'])) {
			if ($member_info2) {
				$this->error['warning'] = $this->language->get('error_exists_phone_no');
			}
		} else {
			if ($member_info2 && ($this->request->get['member_id'] != $member_info2['member_id'])) {
				$this->error['warning'] = $this->language->get('error_exists_phone_no');
			}
		}

		if ((utf8_strlen(trim($this->request->post['date_of_birth'])) < 1)) {
			$this->error['date_of_birth'] = $this->language->get('error_date_of_birth');
		}

		if (!is_numeric($this->request->post['total_tier_achieved_purchase'])) {
			$this->error['total_tier_achieved_purchase'] = $this->language->get('total_tier_achieved_purchase');
		}

		return !$this->error;
	}

	protected function validateMemberRewardForm() {
		if (!$this->user->hasPermission('modify', 'member/member')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}
		return !$this->error;
	}

	protected function validateDelete() {
		if (!$this->user->hasPermission('modify', 'member/member')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		return !$this->error;
	}

	private function MD5Encrypt($message) {
        return md5($message);
    }

	public function tier() {
		$json = array();
		$this->load->model('reward/tier');
		$tier_info = $this->model_reward_tier->getTier($this->request->get['tier_setting_id']);
		if ($tier_info) {
			$json = array(
				'tier_setting_id' 	   => $tier_info['tier_setting_id'],
				'title'       		   => $tier_info['title'],
				'achieve_tier_amount'  => $tier_info['achieve_tier_amount'],
			);
		}
		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	protected function redeemReward($data)
	{
		$apiUrl = API_URL . "reward/redeemvoucherinternal";

		// Prepare the request headers
		$headers = [
			'Content-Type: application/json', // Set the content type to JSON if required
		];

		// Prepare the request options
		$options = [
			CURLOPT_URL => $apiUrl,
			CURLOPT_POST => true, // Set the request method to POST
			CURLOPT_POSTFIELDS => json_encode($data), // Convert the data to JSON format
			CURLOPT_HTTPHEADER => $headers,
			CURLOPT_RETURNTRANSFER => true, // Return the response as a string instead of outputting it
			CURLOPT_FOLLOWLOCATION => true, // Follow any redirects
		];

		// Initialize the cURL session
		$curl = curl_init();

		// Set the cURL options
		curl_setopt_array($curl, $options);

		// Execute the request and get the response
		$response = curl_exec($curl);

		// Check for cURL errors
		if (curl_errno($curl)) {
			$error = curl_error($curl);
			// Handle the error
			echo "cURL Error: " . $error;
		} else {
			// Process the response
			$responseData = json_decode($response, true); // Convert the response JSON string to an associative array
		
			// Check if the response is valid JSON
			if ($responseData === null) {
				throw new Exception($apiUrl."Invalid JSON response");
			} else {
				// Access and manipulate the data from the response
				$success = $responseData['success'];
				if($success == 'false')
				{
					$errormessage = $responseData['errormessage'];
					$this->error['warning'] = $errormessage;				
				}
				return !$this->error;
			}
		}
		// Close the cURL session
		
	}

}