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

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

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

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

		$this->getList();
	}

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

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

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

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_member_reward->editMemberReward($this->request->get['member_reward_id'], $this->request->post);

			$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/reward', 'user_token=' . $this->session->data['user_token'] . $url, true));
		}

		$this->getForm();
	}

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

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

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

		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $reward_setting_id) {
				$this->model_member_reward->deleteRewardSetting($reward_setting_id);
				$this->model_error_log->writeLogs('Trace', 'DeleteRewardSetting', 'Reward Setting Id ' . $reward_setting_id . ' been deleted by User Id' . $this->session->data['user_id']);
			}

			$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/reward', 'user_token=' . $this->session->data['user_token'] . $url, true));
		}

		$this->getList();
	}

	public function export() {
		$export = new Export();
		$this->load->model('member/reward');

		if (isset($this->request->get['filter_reward_name'])) {
			$filter_reward_name = $this->request->get['filter_reward_name'];
			$data['filter_reward_name'] = $filter_reward_name;
		} else {
			$filter_reward_name = '';
			$data['filter_reward_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_is_redeemed'])) {
			$filter_is_redeemed = $this->request->get['filter_is_redeemed'];
			$data['filter_is_redeemed'] = $filter_is_redeemed;
		} else {
			$filter_is_redeemed = '';
			$data['filter_is_redeemed'] = '';
		}

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

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

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

		$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'];
		}

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

		$filter_data = array(
			'filter_reward_name'       => $filter_reward_name,
			'filter_email'             => $filter_email,
			'filter_phone_no' 		   => $filter_phone_no,
			'filter_is_redeemed'       => $filter_is_redeemed,
			'filter_is_cancelled'      => $filter_is_cancelled,
			'sort'  => $sort,
			'order' => $order
		);

		$results = $this->model_member_reward->getMemberRewards($filter_data);
		// Create an empty array to store the CSV data
		$csvData = array();
		// Add the headers as the first row
		$csvData[] = array(
			'Email',
			'Phone No',
			'Reward Name',
			'Value',
			'Used Point',
			'Expiry Date',
			'Is Redeemed',
			'Is Cancelled',
			'Redemption Date',
			'Date Added',
			'Edit'
		);

		foreach ($results as $result) {
			$csvData[] = array(
				$result['email'],
				$result['phone_no'],
				$result['reward_name'],
				$result['value'],
				$result['used_point'],
				date($this->language->get('date_format_short'), strtotime($result['expiry_date'])),
				$result['is_redeemed'],
				$result['is_cancelled'],
				!empty($result['redemption_date']) ? date($this->language->get('date_format_short'), strtotime($result['redemption_date'])) : "",
				date($this->language->get('date_format_short'), strtotime($result['created_date'])),
			);
		}
		$export -> exportToCSV($csvData);
	}

	protected function getList() {
		if (isset($this->request->get['filter_reward_name'])) {
			$filter_reward_name = $this->request->get['filter_reward_name'];
			$data['filter_reward_name'] = $filter_reward_name;
		} else {
			$filter_reward_name = '';
			$data['filter_reward_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_is_redeemed'])) {
			$filter_is_redeemed = $this->request->get['filter_is_redeemed'];
			$data['filter_is_redeemed'] = $filter_is_redeemed;
		} else {
			$filter_is_redeemed = '';
			$data['filter_is_redeemed'] = '';
		}

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

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

		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['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/reward', 'user_token=' . $this->session->data['user_token'] . $url, true)
		);
		$data['rewards'] = array();

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

		$reward_total = $this->model_member_reward->getTotalMemberRewards();
		$results = $this->model_member_reward->getMemberRewards($filter_data);

		foreach ($results as $result) {
			$data['member_rewards'][] = array(
				'email'   						=> $result['email'],
				'phone_no'   					=> $result['phone_no'],
				'reward_name'   			    => $result['reward_name'],
				'value'   						=> $result['value'],
				'used_point'   					=> $result['used_point'],
				'expiry_date'   				=> date($this->language->get('date_format_short'), strtotime($result['expiry_date'])),
				'is_redeemed'   				=> $result['is_redeemed'],
				'is_cancelled'   				=> $result['is_cancelled'],
				'redemption_date'   			=> !empty($result['redemption_date']) ? date($this->language->get('date_format_short'), strtotime($result['redemption_date'])) : "",
				'date_added' 					=> date($this->language->get('date_format_short'), strtotime($result['created_date'])),
				'edit'       					=> $this->url->link('member/reward/edit', 'user_token=' . $this->session->data['user_token'] . '&member_reward_id=' . $result['member_reward_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_title'] = $this->url->link('member/reward', 'user_token=' . $this->session->data['user_token'] . '&sort=title' . $url, true);
		$data['sort_reward_type'] = $this->url->link('member/reward', 'user_token=' . $this->session->data['user_token'] . '&sort=reward_type_name' . $url, true);
		$data['sort_status'] = $this->url->link('member/reward', 'user_token=' . $this->session->data['user_token'] . '&sort=status' . $url, true);
		$data['sort_date_added'] = $this->url->link('member/reward', 'user_token=' . $this->session->data['user_token'] . '&sort=created_date' . $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 = $reward_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_limit_admin');
		$pagination->url = $this->url->link('member/reward', 'user_token=' . $this->session->data['user_token'] . $url . '&page={page}', true);

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

		$data['results'] = sprintf($this->language->get('text_pagination'), ($reward_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($reward_total - $this->config->get('config_limit_admin'))) ? $reward_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $reward_total, ceil($reward_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/reward_list', $data));
	}

	protected function getForm() {
		$data['text_form'] = !isset($this->request->get['member_reward_id']) ? $this->language->get('text_add') : $this->language->get('text_edit');

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

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

		$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('member/reward', 'user_token=' . $this->session->data['user_token'] . $url, true)
		);

		$data['action'] = $this->url->link('member/reward/edit', 'user_token=' . $this->session->data['user_token'] . '&member_reward_id=' . $this->request->get['member_reward_id'] . $url, true);
		$data['cancel'] = $this->url->link('member/reward', 'user_token=' . $this->session->data['user_token'] . $url, true);

		if (isset($this->request->get['member_reward_id'])) {
			$reward_info = $this->model_member_reward->getMemberReward($this->request->get['member_reward_id']);
		}

		if (!empty($reward_info)) {
			$this->load->model('member/member');
			$member_info = $this->model_member_member->getMember($reward_info['member_id']);
		}

		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'];
			$data['reward_name'] = $reward_info['reward_name'];
			$data['used_point'] = $reward_info['used_point'];
			$data['value'] = $reward_info['value'];
			$data['redemption_date'] = (($reward_info['redemption_date'] == NULL) ? '' : date('Y-m-d', strtotime($reward_info['redemption_date'])));
		} else {
			$data['external_member_id'] = '';
			$data['phone_no'] = '';
			$data['email'] = '';
			$data['tier_setting_id'] = '';
			$data['tier_level'] = '';
			$data['reward_name'] = '';
		}

		if (isset($this->request->post['expiry_date'])) {
			$data['expiry_date'] = $this->request->post['expiry_date'];
		} elseif (!empty($reward_info)) {
			$data['expiry_date'] = (($reward_info['expiry_date'] == NULL) ? '' : date('Y-m-d', strtotime($reward_info['expiry_date'])));
		} else {
			$data['expiry_date'] = '';
		}

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

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

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

		$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_reward_form', $data));
	}

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

		if ($this->request->post['is_redeemed'] && $this->request->post['is_cancelled'] ) {
			$this->error['is_redeemed'] = $this->language->get('error_redeemed');
		}
		return !$this->error;
	}
}