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

class Questions extends Admin_Controller {

	public function __construct()
	{
		parent::__construct();

		/* Load :: Common */
		//$this->lang->load('admin/users');

		/* Title Page :: Common */
		$this->page_title->push('Questions');
		$this->data['pagetitle'] = $this->page_title->show();

		/* Breadcrumbs :: Common */
		$this->breadcrumbs->unshift(1, 'Questions', 'admin/questions');
		$this->output->delete_cache();
	}


	public function index(){
		if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
		{
			redirect('auth/login', 'refresh');
		}
		else
		{
			$this->load->model('admin/question_model');
			$this->data['breadcrumb'] = $this->breadcrumbs->show();
			$this->data['questions'] = $this->question_model->get_questions();
			//echo print_r($this->data['questions']);
			//return;
			$this->template->admin_render('admin/questions/index', $this->data);
		}
	}

	public function toggle_is_active(){
		$uid = $this->input->post('uid');
		$this->load->model('admin/question_model');
		echo $this->question_model->toggle_is_active($uid);
	}
	
	public function set_question(){
		$uid = $this->input->post('uid');
		$level = $this->input->post('level');
		$question = $this->input->post('question');
		$answers = $this->input->post('answers');
		$explain = $this->input->post('explain');
		$this->load->model('admin/question_model');
		echo $this->question_model->set_question($uid, $level, $question, $answers, $explain);
	}

	function gen_uid(){
		$data = random_bytes(16);
		$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
		$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
		return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
	}

	public function add_question(){
		$uid = $this->gen_uid();
		$level = $this->input->post('level');
		$question = $this->input->post('question');
		$answers = $this->input->post('answers');
		$explain = $this->input->post('explain');
		$this->load->model('admin/question_model');
		echo $this->question_model->add_question($uid, $level, $question, $answers, $explain);
	}

	public function get_missions(){
		$uid = $this->input->post('uid');
		$this->load->model('admin/question_model');
		$res = $this->user_level_model->get_missions($uid);
		header('Content-Type: application/json');
		echo json_encode($res);
	}
}
