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

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

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

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

		$this->getList();
	}

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

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

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

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

		$this->getForm();
	}

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

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

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

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			//echo json_encode($this->request->post);
			$this->model_reward_reward_promotion->editRewardPromotionSetting($this->request->get['reward_promotion_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_promotion', 'user_token=' . $this->session->data['user_token'] . $url, true));
		}

		$this->getForm();
	}

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

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

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

		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $reward_promotion_setting_id) {
				$this->model_reward_reward_promotion->deleteRewardPromotionSetting($reward_promotion_setting_id);
				$this->model_error_log->writeLogs('Trace', 'DeleteRewardPromotionSetting', 'Reward Promotion Setting Id ' . $reward_promotion_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_promotion', 'user_token=' . $this->session->data['user_token'] . $url, true));
		}

		$this->getList();
	}

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

		$this->load->model('reward/reward');
		$reward_info = $this->model_reward_reward->getRewardSetting($this->request->get['reward_setting_id']);
		if ($reward_info) {
			$json = array(
				'reward_setting_id' => $reward_info['reward_setting_id'],
				'point'       		 => $reward_info['point'],
				'value'       		=> $reward_info['value'],
				'expiry'      		=> $reward_info['expiry'],
				'description'    	=> $reward_info['description'],
				'term_and_condition' => $reward_info['term_and_condition'],
				'start_date'   		=> date($this->language->get('date_format_short'), strtotime($reward_info['start_date'])),
				'end_date'   		=> (($reward_info['end_date'] == NULL) ? '-' : date($this->language->get('date_format_short'), strtotime($reward_info['end_date'])))
			);
		}
		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	protected function getList() {
		
		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'reward_setting_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['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_promotion', 'user_token=' . $this->session->data['user_token'] . $url, true)
		);

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

		$data['reward_promotions'] = 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_promotion->getTotalRewardPromotionSettings();

		$results = $this->model_reward_reward_promotion->getRewardPromotionSettings($filter_data);

		foreach ($results as $result) {
            $data['reward_promotions'][] = array(
				'reward_promotion_setting_id'		=> $result['reward_promotion_setting_id'],
				'reward_setting_id'		            => $result['reward_setting_id'],
				'reward_setting_name'	            => $result['reward_setting_name'],
				'point'   				            => $result['point'],
				'start_date'   		                => date($this->language->get('date_format_short'), strtotime($result['start_date'])),
				'end_date'   		                => 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_promotion/edit', 'user_token=' . $this->session->data['user_token'] . '&reward_promotion_setting_id=' . $result['reward_promotion_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_reward'] = $this->url->link('reward/reward_promotion', 'user_token=' . $this->session->data['user_token'] . '&sort=reward_setting_name' . $url, true);
		$data['sort_status'] = $this->url->link('reward/reward_promotion', 'user_token=' . $this->session->data['user_token'] . '&sort=status' . $url, true);
		$data['sort_date_added'] = $this->url->link('reward/reward_promotion', '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_promotion', '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_promotion_list', $data));
	}

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

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

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

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

		if (isset($this->request->get['reward_promotion_setting_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
			$reward_promotion_info = $this->model_reward_reward_promotion->getRewardPromotionSetting($this->request->get['reward_promotion_setting_id']);
		}

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

		$this->load->model('reward/reward');
		$rewards = $this->model_reward_reward->getActiveRewardSettings();

		foreach ($rewards as $reward) {
            $data['rewards'][] = array(
				'reward_setting_id'		=> $reward['reward_setting_id'],
				'reward_setting_name'	=> $reward['reward_setting_name'],
				'point'   				=> $reward['point'],
				'start_date'   			=> date($this->language->get('date_format_short'), strtotime($reward['start_date'])),
				'end_date'   			=> (($reward['end_date'] == NULL) ? '-' : date($this->language->get('date_format_short'), strtotime($reward['end_date'])))
			);
		}

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

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

		if (isset($this->request->post['start_date'])) {
			$data['start_date'] = $this->request->post['start_date'];
		} elseif (!empty($reward_promotion_info)) {
			$data['start_date'] = date('Y-m-d', strtotime($reward_promotion_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_promotion_info)) {
			$data['end_date'] = date('Y-m-d', strtotime($reward_promotion_info['end_date']));
		} else {
			$data['end_date'] = '';
		}

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

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

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

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

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

		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) ) {
			$this->error['start_date'] = $this->language->get('error_start_date');
			if(!isset($this->request->get['reward_promotion_setting_id'])) {
				$this->error['start_date'] = $this->language->get('error_start_date');
			}
			else
			{
				$promotion_info = $this->model_reward_reward_promotion-> getRewardPromotionSetting($this->request->get['reward_promotion_setting_id']);
				if(strtotime($start_date)  != strtotime($promotion_info['start_date'])){
					$this->error['start_date'] = $this->language->get('error_start_date');
				}
			}
		}

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

		$this->load->model('reward/reward');
		$reward_info = $this->model_reward_reward->getRewardSetting($this->request->post['reward_setting_id']);
		
		if(strtotime($start_date) < strtotime($reward_info['start_date']))
		{
			$this->error['start_date'] = $this->language->get('error_start_date2');
		}

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

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

		if($this->model_reward_reward_promotion->getRewardPromotionSettingByRewardSettingId($this->request->post['reward_setting_id'],$start_date ,$end_date))
		{
			if(!isset($this->request->get['reward_promotion_setting_id'])) {
				$this->error['warning'] = $this->language->get('error_active_reward_promotion');
			}
		}
		return !$this->error;
	}

	protected function validateDelete() {
		if (!$this->user->hasPermission('modify', 'reward/reward_promotion')) {
			$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;
	}
}