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

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

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

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

		$this->getList();
	}

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

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

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

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

			$regular_total_price = number_format($this->request->post['regular_price_amount'], 2, '.', '');
			$sales_total_price = number_format($this->request->post['sales_total_price'], 2, '.', '');
			
			$data = array(
				'memberid' => $this->request->post['member_id'],
				'orderno' => $this->request->post['order_no'],
				'regulartotalprice' => $regular_total_price,
				'salestotalprice' => $sales_total_price,
				'expirydate'  => $this->request->post['expiry_date'],
				'updatedby'  => $this->user->getUserName(),
				'remark'  => $this->request->post['remark'],
				'hash' => MD5($this->request->post['member_id'].$this->request->post['order_no'].
				$regular_total_price.$sales_total_price.
				$this->request->post['expiry_date'].$this->user->getUserName().$this->request->post['remark'].API_KEY)
			);

			if($this->updateMemberPoint('member/updatetierandpointinternal',$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'];
				}

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

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

		$this->getForm();
	}

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

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

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

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->session->data['success'] = $this->language->get('text_success');
			$data = array(
					'memberid' => $this->request->post['member_id'],
					'memberpointid' => $this->request->post['member_point_id'],
					'updatedby'  => $this->user->getUserName(),
					'remark'  => $this->request->post['remark'],
					'hash' => MD5($this->request->post['member_id'].
					$this->request->post['member_point_id'].
					$this->user->getUserName().$this->request->post['remark'].API_KEY)
			);

			if($this -> updateMemberPoint('member/cancelpointtransactioninternal',$data)){
				$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/point', 'user_token=' . $this->session->data['user_token'] . $url, true));
			}
		}
		$this->getForm();
	}

	public function export() {
		$export = new Export();
		$this->load->model('member/point');
		
		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['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'];
		}

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

		$point_total = $this->model_member_point->getTotalMemberPoints();
		$results = $this->model_member_point->getMemberPoints($filter_data);

		foreach ($results as $result) {
			$data['member_points'][] = array(
				'email'   						=> $result['email'],
				'phone_no'   					=> $result['phone_no'],
				'order_no'   			    	=> $result['order_no'],
				'regular_price_amount'   		=> $result['regular_price_amount'],
				'sales_price_amount'   			=> $result['sales_price_amount'],
				'point'   						=> $result['point'],
				'expiry_date'   				=> date($this->language->get('date_format_short'), strtotime($result['expiry_date'])),
				'available_point'   			=> $result['available_point'],
				'used_point'   					=> $result['used_point'],
				'expired_point'   				=> $result['expired_point'],
				'is_cancelled'   				=> $result['is_cancelled'],
				'date_added' 					=> date($this->language->get('date_format_short'), strtotime($result['created_date'])),
				'edit'       					=> $this->url->link('member/point/edit', 'user_token=' . $this->session->data['user_token'] . '&member_point_id=' . $result['member_point_id'] . $url, true)
			);
		}


		// Create an empty array to store the CSV data
		$csvData = array();
		// Add the headers as the first row
		$csvData[] = array(
			'Email',
			'Phone No',
			'Order No',
			'Regular Price Amount',
			'Sales Price Amount',
			'Point',
			'Expiry Date',
			'Available Point',
			'Used Point',
			'Expired Point',
			'Is Cancelled',
			'Date Added'
		);

		foreach ($results as $result) {
			$csvData[] = array(
				$result['email'],
				$result['phone_no'],
				$result['order_no'],
				$result['regular_price_amount'],
				$result['sales_price_amount'],
				$result['point'],
				date($this->language->get('date_format_short'), strtotime($result['expiry_date'])),
				$result['available_point'],
				$result['used_point'],
				$result['expired_point'],
				$result['is_cancelled'],
				date($this->language->get('date_format_short'), strtotime($result['created_date'])),
			);
		}
		$export -> exportToCSV($csvData);
	}

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

		$data['add'] = $this->url->link('member/point/add', 'user_token=' . $this->session->data['user_token'] . $url, true);
		$data['delete'] = $this->url->link('member/point/delete', 'user_token=' . $this->session->data['user_token'] . $url, true);
		$filter_data = array(
			'filter_email'             => $filter_email,
			'filter_phone_no' 		   => $filter_phone_no,
			'sort'  => $sort,
			'order' => $order,
			'start' => ($page - 1) * $this->config->get('config_limit_admin'),
			'limit' => $this->config->get('config_limit_admin')
		);

		$point_total = $this->model_member_point->getTotalMemberPoints();
		$results = $this->model_member_point->getMemberPoints($filter_data);

		foreach ($results as $result) {
			$data['member_points'][] = array(
				'email'   						=> $result['email'],
				'phone_no'   					=> $result['phone_no'],
				'order_no'   			    	=> $result['order_no'],
				'regular_price_amount'   		=> $result['regular_price_amount'],
				'sales_price_amount'   			=> $result['sales_price_amount'],
				'point'   						=> $result['point'],
				'expiry_date'   				=> date($this->language->get('date_format_short'), strtotime($result['expiry_date'])),
				'available_point'   			=> $result['available_point'],
				'used_point'   					=> $result['used_point'],
				'expired_point'   				=> $result['expired_point'],
				'is_cancelled'   				=> $result['is_cancelled'],
				'date_added' 					=> date($this->language->get('date_format_short'), strtotime($result['created_date'])),
				'edit'       					=> $this->url->link('member/point/edit', 'user_token=' . $this->session->data['user_token'] . '&member_point_id=' . $result['member_point_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_point'] = $this->url->link('member/point', 'user_token=' . $this->session->data['user_token'] . '&sort=point' . $url, true);
		$data['sort_available_point'] = $this->url->link('member/point', 'user_token=' . $this->session->data['user_token'] . '&sort=available_point' . $url, true);
		$data['sort_expired_date'] = $this->url->link('member/point', 'user_token=' . $this->session->data['user_token'] . '&sort=expired_date' . $url, true);
		$data['sort_date_added'] = $this->url->link('member/point', '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 = $point_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_limit_admin');
		$pagination->url = $this->url->link('member/point', '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'), ($point_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($point_total - $this->config->get('config_limit_admin'))) ? $point_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $point_total, ceil($point_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/point_list', $data));
	}

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

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

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

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

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

		if (isset($this->request->get['member_point_id']))  {
			$point_info = $this->model_member_point->getMemberPoint($this->request->get['member_point_id']);
			$member_info = $this->model_member_member->getMember($point_info['member_id']);
			$data['member_point_id'] = ($this->request->get['member_point_id']);
			$data['available_point'] = $point_info['available_point'];
			$data['used_point'] = $point_info['used_point'];
			$data['point'] = $point_info['point'];
		}
		else if(isset($this->request->get['member_id']))
		{
			$member_info = $this->model_member_member->getMember($this->request->get['member_id']);
			$data['member_id'] = ($this->request->get['member_id']);
		}

		if (!empty($member_info)) {
			$data['member_id'] = $member_info['member_id'];
			$data['phone_no'] = $member_info['phone_no'];
			$data['email'] = $member_info['email'];
			$data['tier_level'] = $member_info['tier_level'];
		}

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

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

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

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

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

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

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

	protected function validateForm() {
		if (!$this->user->hasPermission('modify', 'member/point')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}
		if (!isset($this->request->get['member_point_id']) && !is_numeric($this->request->post['regular_price_amount'])) {
			$this->error['regular_price_amount'] = $this->language->get('error_regular_price_amount');
		}

		if (!isset($this->request->get['member_point_id']) && !is_numeric($this->request->post['sales_price_amount'])) {
			$this->error['sales_price_amount'] = $this->language->get('error_sales_price_amount');
		}
		return !$this->error;
	}

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

	protected function updateMemberPoint($method, $data)
	{
		$apiUrl = API_URL . $method;

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