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

/**
 * Quiz CRUD (Firestore collection: Quaiz).
 * Each quiz stores MCQ questions with 3–6 options and correct answer.
 */
class Aoust_quiz extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->helper(array('url', 'form'));
		$this->load->library('session');
		$this->load->database();

		if (!isset($this->session->userdata['session_data'])) {
			redirect(base_url('login'));
			return;
		}
	}

	public function index()
	{
		$data['page_title'] = 'AOUST — Quiz Module';
		$rows = $this->common->readdatafromcollectionwhereclause('Quaiz');
		$list = array();
		if (!empty($rows)) {
			foreach ($rows as $id => $r) {
				if (is_array($r)) {
					$r['id'] = $id;
					$list[] = $r;
				}
			}
		}
		usort($list, function ($a, $b) {
			$ta = isset($a['timeStamp']) ? (int) $a['timeStamp'] : 0;
			$tb = isset($b['timeStamp']) ? (int) $b['timeStamp'] : 0;
			return $tb <=> $ta;
		});
		$data['quizzes'] = $list;
		$this->template->template_render('admin/quiz/index', $data);
	}

	public function create()
	{
		$data['page_title'] = 'AOUST — Add Quiz';
		$data['mode'] = 'create';
		$data['quiz'] = $this->_empty_quiz();
		$this->template->template_render('admin/quiz/form', $data);
	}

	public function store()
	{
		$payload = $this->_read_payload_from_post();
		$errors = $this->_validate_quiz($payload);
		if (!empty($errors)) {
			$this->session->set_flashdata('warningmessage', implode(' ', $errors));
			redirect(base_url('aoust_quiz/create'));
			return;
		}

		$docId = 'quiz_' . uniqid();
		$payload['timeStamp'] = round(microtime(true) * 1000);
		$payload['createdAt'] = date('c');
		$payload['updatedAt'] = date('c');

		$ok = $this->common->adddatamodel('Quaiz', $docId, $payload);
		if ($ok) {
			$this->session->set_flashdata('successmessage', 'Quiz created.');
			redirect(base_url('aoust_quiz'));
			return;
		}
		$this->session->set_flashdata('warningmessage', 'Failed to create quiz.');
		redirect(base_url('aoust_quiz/create'));
	}

	public function edit($id = '')
	{
		$id = trim((string) $id);
		if ($id === '') {
			redirect(base_url('aoust_quiz'));
			return;
		}
		$row = $this->common->readdatadocument('Quaiz', $id);
		if (empty($row) || !is_array($row)) {
			$this->session->set_flashdata('warningmessage', 'Quiz not found.');
			redirect(base_url('aoust_quiz'));
			return;
		}
		$row['id'] = $id;
		$data['page_title'] = 'AOUST — Edit Quiz';
		$data['mode'] = 'edit';
		$data['quiz'] = array_merge($this->_empty_quiz(), $row);
		$this->template->template_render('admin/quiz/form', $data);
	}

	public function update($id = '')
	{
		$id = trim((string) $id);
		if ($id === '') {
			redirect(base_url('aoust_quiz'));
			return;
		}
		$existing = $this->common->readdatadocument('Quaiz', $id);
		if (empty($existing) || !is_array($existing)) {
			$this->session->set_flashdata('warningmessage', 'Quiz not found.');
			redirect(base_url('aoust_quiz'));
			return;
		}

		$payload = $this->_read_payload_from_post();
		$errors = $this->_validate_quiz($payload);
		if (!empty($errors)) {
			$this->session->set_flashdata('warningmessage', implode(' ', $errors));
			redirect(base_url('aoust_quiz/edit/' . rawurlencode($id)));
			return;
		}

		$payload['updatedAt'] = date('c');
		$ok = $this->common->updatedatamodel('Quaiz', $id, $payload);
		if ($ok) {
			$this->session->set_flashdata('successmessage', 'Quiz updated.');
			redirect(base_url('aoust_quiz'));
			return;
		}
		$this->session->set_flashdata('warningmessage', 'Failed to update quiz.');
		redirect(base_url('aoust_quiz/edit/' . rawurlencode($id)));
	}

	public function delete($id = '')
	{
		$id = trim((string) $id);
		if ($id === '') {
			redirect(base_url('aoust_quiz'));
			return;
		}
		$this->common->deletedatamodel('Quaiz', $id);
		$this->session->set_flashdata('successmessage', 'Quiz deleted.');
		redirect(base_url('aoust_quiz'));
	}

	private function _empty_quiz()
	{
		$sessiondata = $this->session->userdata['session_data'];
		$userId = isset($sessiondata['userId']) ? (string) $sessiondata['userId'] : '';
		return array(
			'id' => '',
			'type' => 'au_pair',
			'title' => '',
			'description' => '',
			'userId' => $userId,
			'questions' => array(),
		);
	}

	private function _read_payload_from_post()
	{
		$sessiondata = $this->session->userdata['session_data'];
		$userId = isset($sessiondata['userId']) ? (string) $sessiondata['userId'] : '';

		$type = (string) $this->input->post('type');
		$title = (string) $this->input->post('title');
		$desc = (string) $this->input->post('description');
		$userIdPost = (string) $this->input->post('userId');

		$qjson = (string) $this->input->post('questions_json');
		$questions = array();
		if ($qjson !== '') {
			$decoded = json_decode($qjson, true);
			if (is_array($decoded)) $questions = $decoded;
		}

		return array(
			'type' => trim($type),
			'title' => trim($title),
			'description' => trim($desc),
			'userId' => $userIdPost !== '' ? trim($userIdPost) : $userId,
			'questions' => $questions,
		);
	}

	private function _validate_quiz($payload)
	{
		$errors = array();
		$allowedTypes = array('au_pair', 'family_host');
		$ptype = isset($payload['type']) ? (string) $payload['type'] : '';
		if (!in_array($ptype, $allowedTypes, true)) {
			$errors[] = 'Type must be Au pair or Family host.';
		}
		if (empty($payload['title'])) $errors[] = 'Title is required.';
		if (!isset($payload['questions']) || !is_array($payload['questions']) || count($payload['questions']) === 0) {
			$errors[] = 'Add at least 1 question.';
			return $errors;
		}

		foreach ($payload['questions'] as $idx => $q) {
			$n = $idx + 1;
			$text = isset($q['text']) ? trim((string) $q['text']) : '';
			$options = isset($q['options']) && is_array($q['options']) ? $q['options'] : array();
			$correctIndex = isset($q['correctIndex']) ? (int) $q['correctIndex'] : -1;

			$options = array_values(array_filter(array_map(function ($o) {
				return trim((string) $o);
			}, $options), function ($o) { return $o !== ''; }));

			if ($text === '') $errors[] = "Question {$n}: text is required.";
			if (count($options) < 3) $errors[] = "Question {$n}: at least 3 options required.";
			if (count($options) > 6) $errors[] = "Question {$n}: max 6 options allowed.";
			if ($correctIndex < 0 || $correctIndex >= count($options)) $errors[] = "Question {$n}: choose a correct answer.";
		}
		return $errors;
	}
}

