<?php
defined('BASEPATH') or exit('No direct script access allowed');

require APPPATH . '/libraries/REST_Controller.php';
require APPPATH . '/libraries/Format.php';

use Restserver\Libraries\REST_Controller;

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");

class Api_home_activity_poin extends REST_Controller
{

	public function __construct()
	{
		parent::__construct();
		date_default_timezone_set("Asia/Jakarta");
		$this->load->helper(['jwt', 'authorization']);
	}


	public function index_post()
	{
		$mst_user_kode =  $this->mst_user_kode();
		$poin = $this->db->query("SELECT * FROM tbl_mst_poin where mst_poin_user_kode='$mst_user_kode'");
		if ($poin->num_rows() > 0) {
			foreach ($poin->result() as $row) {
				$data['poin'][] = array(
					'mst_poin_user_kode' => encrypt($row->mst_poin_user_kode, $this->config->item('key')),
					'mst_poin_jumlah' => encrypt(number_format($row->mst_poin_jumlah, 0, ',', '.'), $this->config->item('key')),
				);
			}

			$sess["status"] = "001";
			$sess["pesan"] = "Poin tersedia";
			$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
			$sess['data'] = array(
				'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
				'value' =>  encrypt(json_encode($data), $keytoken)
			);
			echo json_encode($sess);
		} else {
			$sess["status"] = "002";
			$sess["pesan"] = "Poin tidak ada";
			$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
			$sess['data'] = array(
				'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
				'value' =>  encrypt(json_encode(array()), $keytoken)
			);
			echo json_encode($sess);
		}
	}


	private function mst_user_kode()
	{
		$input = decrypt($this->input->post("mst_user_kode", true), $this->config->item('key'));
		$token = AUTHORIZATION::generateToken($input);
		try {
			$data = AUTHORIZATION::validateToken($token);
			if ($data === false) {
				$sess["status"] = "004";
				$sess["pesan"] = $this->config->item('error_parameter');
				$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
				$sess['data'] = array(
					'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
					'value' =>  encrypt(json_encode(array()), $keytoken)
				);
				echo json_encode($sess);
				exit();
			} else {
				return $data;
			}
		} catch (Exception $e) {
			$sess["status"] = "004";
			$sess["pesan"] = $this->config->item('error_parameter');
			$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
			$sess['data'] = array(
				'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
				'value' =>  encrypt(json_encode(array()), $keytoken)
			);
			echo json_encode($sess);
			exit();
		}
	}
}
