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

class Surveys extends Admin_Controller {
	public function __construct(){
		parent::__construct();
		$this->page_title->push('Surveys');
		$this->data['pagetitle'] = $this->page_title->show();
		$this->breadcrumbs->unshift(1, 'Surveys', 'admin/surveys');
		$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/survey_model');
			$this->data['breadcrumb'] = $this->breadcrumbs->show();
			$this->data['questions'] = $this->survey_model->get_questions();
			$this->template->admin_render('admin/surveys/index', $this->data);
		}
	}

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

	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();
		$question = $this->input->post('question');
		$answers = $this->input->post('answers');
		$this->load->model('admin/survey_model');
		echo $this->survey_model->add_question($uid, $question, $answers);
	}
}
