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

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

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

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

		$this->getList();
	}

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

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

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

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_reward_reward->addRewardSetting($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('reward/reward', 'user_token=' . $this->session->data['user_token'] . $url, true));
		}

		$this->getForm();
	}

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

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

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

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_reward_reward->editRewardSetting($this->request->get['reward_setting_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('reward/reward', 'user_token=' . $this->session->data['user_token'] . $url, true));
		}

		$this->getForm();
	}

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

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

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

		if (isset($this->request->get['reward_setting_id']) && $this->validateDelete()) {
			$reward_setting_id = $this->request->get['reward_setting_id'];
			$this->model_reward_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('reward/reward', 'user_token=' . $this->session->data['user_token'] . $url, true));
		}

		$this->getList();
	}

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

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

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

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

		$this->load->model('tool/image');

		$reward_total = $this->model_reward_reward->getTotalRewardSettings();

		$results = $this->model_reward_reward->getRewardSettings($filter_data);

		foreach ($results as $result) {
			if (is_file(DIR_IMAGE . $result['image'])) {
				$image = $this->model_tool_image->resize($result['image'], 40, 40);
			} else {
				$image = $this->model_tool_image->resize('no_image.png', 40, 40);
			}

			$member_count = $this->model_reward_reward->getTotalMembersByRewardSetting($result['reward_setting_id']);

			$data['rewards'][] = array(
				'reward_setting_id'				=> $result['reward_setting_id'],
				'image'		 					=> $image,
				'title'   						=> $result['title'],
				'reward_type'   				=> $result['reward_type_name'],
				'description'   				=> $result['description'],
				'term_and_condition'   			=> $result['term_and_condition'],
				'point'   						=> $result['point'],
				'value'   						=> $result['value'],
				'min_tier_name'   				=> $result['min_tier_name'],
				'expiry'   						=> $result['expiry'],
				'redemption_environment_name'   => $result['redemption_environment_name'],
				'start_date'   					=> date($this->language->get('date_format_short'), strtotime($result['start_date'])),
				'end_date'   					=> (($result['end_date'] == NULL) ? '-' : date($this->language->get('date_format_short'), strtotime($result['end_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('reward/reward/edit', 'user_token=' . $this->session->data['user_token'] . '&reward_setting_id=' . $result['reward_setting_id'] . $url, true),
				'delete'       					=> $member_count > 0 ? null:$this->url->link('reward/reward/delete', 'user_token=' . $this->session->data['user_token'] . '&reward_setting_id=' . $result['reward_setting_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('reward/reward', 'user_token=' . $this->session->data['user_token'] . '&sort=title' . $url, true);
		$data['sort_reward_type'] = $this->url->link('reward/reward', 'user_token=' . $this->session->data['user_token'] . '&sort=reward_type_name' . $url, true);
		$data['sort_status'] = $this->url->link('reward/reward', 'user_token=' . $this->session->data['user_token'] . '&sort=status' . $url, true);
		$data['sort_date_added'] = $this->url->link('reward/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('reward/reward', 'user_token=' . $this->session->data['user_token'] . $url . '&page={page}', true);

		$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('reward/reward_list', $data));
	}

	protected function getForm() {
		$data['text_form'] = !isset($this->request->get['reward_setting_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['title'])) {
			$data['error_title'] = $this->error['title'];
		} else {
			$data['error_title'] = '';
		}

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

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

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

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

		if (isset($this->error['end_date'])) {
			$data['error_end_date'] = $this->error['end_date'];
		} else {
			$data['error_end_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('reward/reward', 'user_token=' . $this->session->data['user_token'] . $url, true)
		);

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

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

		if (isset($this->request->get['reward_setting_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
			$reward_info = $this->model_reward_reward->getRewardSetting($this->request->get['reward_setting_id']);
			$data['reward_setting_id'] = $this->request->get['reward_setting_id'];
		}

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

		$data['reward_types'] = $this->model_reward_reward->getRewardTypes();

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

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

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

		$this->load->model('tool/image');

		if (isset($this->request->post['image']) && is_file(DIR_IMAGE . $this->request->post['image'])) {
			$data['thumb'] = $this->model_tool_image->resize($this->request->post['image'], 100, 100);
		} elseif (!empty($reward_info) && $reward_info['image'] && is_file(DIR_IMAGE . $reward_info['image'])) {
			$data['thumb'] = $this->model_tool_image->resize($reward_info['image'], 100, 100);
		} else {
			$data['thumb'] = $this->model_tool_image->resize('no_image.png', 100, 100);
		}
		
		$data['placeholder'] = $this->model_tool_image->resize('no_image.png', 100, 100);

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

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

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

		// TODO: Need to move to Tier Setting Model.
		$data['min_tiers'] = $this->model_reward_reward->getActiveTierSettings();

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

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

		$data['redemption_environments'] = $this->model_reward_reward->getRedemptionEnvironments();

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

		$data['assignment_types'] = $this->model_reward_reward->getAssignmentTypes();

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

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

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

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

		$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('reward/reward_form', $data));
	}

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

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

		$active_reward = $this->model_reward_reward->getActiveRewardSettingByTitle($this->request->post['title']);

		if (!isset($this->request->get['reward_setting_id'])) {
			if ($active_reward) {
				$this->error['warning'] = $this->language->get('error_exists_title');
			}
		} else {
			if ($active_reward && ($this->request->get['reward_setting_id'] != $active_reward['reward_setting_id'])) {
				$this->error['warning'] = $this->language->get('error_exists_title');
			}
		}

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

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

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

		date_default_timezone_set('Asia/Kuala_Lumpur');

        $today_date = date("Y-m-d");
        $start_date = $this->request->post['start_date'];
        $end_date = $this->request->post['end_date'];

		
		if (strtotime($start_date) < strtotime($today_date) ) {
			if(!isset($this->request->get['reward_setting_id'])) {
				$this->error['start_date'] = $this->language->get('error_start_date');
			}
			else
			{
				$reward_info = $this->model_reward_reward-> getRewardSetting($this->request->get['reward_setting_id']);
				if(strtotime($start_date)  != strtotime($reward_info['start_date'])){
					$this->error['start_date'] = $this->language->get('error_start_date');
				}
			}
		}

	    if (!empty($end_date) && strtotime($start_date) > strtotime($end_date)) {
			$this->error['end_date'] =$this->language->get('error_end_date');
		}

		return !$this->error;
	}

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

		$member_count = $this->model_reward_reward->getTotalMembersByRewardSetting($this->request->get['reward_setting_id']);

		if($member_count > 0)
		{
			$this->error['warning'] = $this->language->get('error_reward');
		}

		return !$this->error;
	}
}