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

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

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

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

		$this->getList();
	}

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

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

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

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {

			$custom_field = array(
				"bg_image" => $this->request->post['bg_image'],
				"card_image" => $this->request->post['card_image'],			
				"font_color" => $this->request->post['font_color'],
				"bg_color" => $this->request->post['bg_color']
			);

			$this->model_reward_tier->addTier(
				$this->request->post['title'], 
				$this->request->post['description'],
				$this->request->post['term_and_condition'],
				$this->request->post['achieve_tier_amount'],
				$this->request->post['maintain_tier_type_id'],
				$this->request->post['maintain_tier_amount'],
				$this->request->post['multiply_regular_item'],
				$this->request->post['multiply_sales_item'],
				$this->request->post['point_expiry'],
				$this->request->post['tier_expiry'],
				$this->request->post['is_hidden'],
				$this->request->post['status'],
				$custom_field
			);

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

		$this->getForm();
	}

	public function edit() {
		$this->load->language('reward/tier');
		$this->load->model('reward/tier');
		$this->document->setTitle($this->language->get('heading_title'));
		
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$custom_field = array(
				"bg_image" => $this->request->post['bg_image'],
				"card_image" => $this->request->post['card_image'],		
				"font_color" => $this->request->post['font_color'],
				"bg_color" => $this->request->post['bg_color'],
			);
			
			$this->model_reward_tier->editTier(
				$this->request->get['tier_setting_id'], 
				$this->request->post['title'], 
				$this->request->post['description'],
				$this->request->post['term_and_condition'],
				$this->request->post['achieve_tier_amount'],
				$this->request->post['maintain_tier_type_id'],
				$this->request->post['maintain_tier_amount'],
				$this->request->post['multiply_regular_item'],
				$this->request->post['multiply_sales_item'],
				$this->request->post['point_expiry'],
				$this->request->post['tier_expiry'],
				$this->request->post['is_hidden'],
				$this->request->post['status'],
				$custom_field);
			$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/tier', 'user_token=' . $this->session->data['user_token'] . $url, true));
		}

		$this->getForm();
	}

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

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

		$this->load->model('reward/tier');
		$log = new Log('TierSetting.log');

		if (isset($this->request->get['tier_setting_id']) && $this->validateDelete()) {		
			$tier_setting_id = $this->request->get['tier_setting_id'];
			$this->model_reward_tier->deleteTier($tier_setting_id);
			$log->write('DeleteTier - Tier Setting Id: ' . $tier_setting_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('reward/tier', '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/tier', 'user_token=' . $this->session->data['user_token'] . $url, true)
		);

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

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

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

		$tier_total = $this->model_reward_tier->getTotalTiers();

		$results = $this->model_reward_tier->getTiers($filter_data);
		$this->load->model('tool/image');
		foreach ($results as $result) {
			$custom_field = json_decode($result['custom_field'], true);
			if (is_file(DIR_IMAGE . $custom_field['card_image'])) {
				$image = $this->model_tool_image->resize($custom_field['card_image'], 40, 40);
			} else {
				$image = $this->model_tool_image->resize('no_image.png', 40, 40);
			} 

			$member_count =  $this->model_reward_tier->getTierTotalMemberCount($result['tier_setting_id']); 

			$data['tiers'][] = array(
				'tier_setting_id'		=> $result['tier_setting_id'],
				'image'		 			=> $image,
				'title'   				=> $result['title'],
				'maintain_tier_type_id' => $result['maintain_tier_type_id'],
				'description'   		=> $result['description'],
				'term_and_condition'   	=> $result['term_and_condition'],
				'achieve_tier_amount'	=> $this->currency->format($result['achieve_tier_amount'], 'MYR'),
				'maintain_tier_amount'  => $result['maintain_tier_type_id'] == 1 ?  $this->currency->format($result['maintain_tier_amount'], 'MYR'):$result['maintain_tier_amount'],
				'multiply_regular_item' => $result['multiply_regular_item'],
				'multiply_sales_item'   => $result['multiply_sales_item'],
				'point_expiry'          => $result['point_expiry'],
				'tier_expiry'           => $result['tier_expiry'],
				'is_hidden'           	=> $result['is_hidden'],
				'updated_by'            => $result['updated_by'],
				'updated_date'          => date($this->language->get('date_format_long'), 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('reward/tier/edit', 'user_token=' . $this->session->data['user_token'] . '&tier_setting_id=' . $result['tier_setting_id'] . $url, true),
				'delete'       			=> $member_count > 0 ? null : $this->url->link('reward/tier/delete', 'user_token=' . $this->session->data['user_token'] . '&tier_setting_id=' . $result['tier_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_username'] = $this->url->link('reward/tier', 'user_token=' . $this->session->data['user_token'] . '&sort=username' . $url, true);
		$data['sort_status'] = $this->url->link('reward/tier', 'user_token=' . $this->session->data['user_token'] . '&sort=status' . $url, true);
		$data['sort_date_added'] = $this->url->link('reward/tier', '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 = $tier_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_limit_admin');
		$pagination->url = $this->url->link('reward/tier', 'user_token=' . $this->session->data['user_token'] . $url . '&page={page}', true);

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

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

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

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

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

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

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

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

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

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

		$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['tier_setting_id'])) {
			$data['action'] = $this->url->link('reward/tier/add', 'user_token=' . $this->session->data['user_token'] . $url, true);
		} else {
			$data['action'] = $this->url->link('reward/tier/edit', 'user_token=' . $this->session->data['user_token'] . '&tier_setting_id=' . $this->request->get['tier_setting_id'] . $url, true);
		}

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

		if (isset($this->request->get['tier_setting_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
			$tier_info = $this->model_reward_tier->getTier($this->request->get['tier_setting_id']);
		}

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

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

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

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

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

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

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

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

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

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

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

		$this->load->model('tool/image');
		if (!empty($tier_info)) {
			$custom_field = json_decode($tier_info['custom_field'], true);
			if(!empty($custom_field))
			{
				$data['bg_image'] = $custom_field['bg_image'];
				$data['bg_thumb'] = $this->model_tool_image->resize($custom_field['bg_image'], 100, 100);
				$this->model_tool_image->resize($custom_field['bg_image'],432,327);
				$data['card_image'] = $custom_field['card_image'];
				$data['card_thumb'] = $this->model_tool_image->resize($custom_field['card_image'], 100, 100);
				$this->model_tool_image->resize($custom_field['card_image'],378,250);
				$data['font_color'] = $custom_field['font_color'];
				if(!empty($custom_field['bg_color']))
				{
					$data['bg_color'] = $custom_field['bg_color'];
				}
			}
			else
			{
				$data['bg_thumb'] = $this->model_tool_image->resize('no_image.png', 100, 100);
				$data['card_thumb'] = $this->model_tool_image->resize('no_image.png', 100, 100);
			}
		}

		if (isset($this->request->post['bg_image'])) {
			$data['bg_image'] = $this->request->post['bg_image'];
			$data['bg_thumb'] = $this->model_tool_image->resize($this->request->post['bg_image'], 100, 100);
		}

		if (isset($this->request->post['card_image'])) {
			$data['card_image'] = $this->request->post['card_image'];
			$data['card_thumb'] = $this->model_tool_image->resize($this->request->post['card_image'], 100, 100);
		}

		$data['placeholder'] = $this->model_tool_image->resize('no_image.png', 100, 100);

		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;
		}

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

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

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

		$tier_info = $this->model_reward_tier->getTierByTitle($this->request->post['title']);

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

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

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

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

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

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

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

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

		return !$this->error;
	}

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

		$total_count = $this->model_reward_tier->getTierTotalMemberCount($this->request->get['tier_setting_id']); 
		if($total_count > 0)
		{
			$this->error['warning'] = $this->language->get('error_tier');
		}

		return !$this->error;
	}
}