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

/**
 * Courses module (Firestore collection: Courses)
 * Each course stores:
 * - title, category, duration, video (URL after Storage upload), image, description, userId (session)
 * - mcqs: array of MCQ questions (3–6 options + correct answer)
 */
class Aoust_courses 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 — Courses';
		$rows = $this->common->readdatafromcollectionwhereclause('Courses');
		$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['courses'] = $list;
		$this->template->template_render('admin/courses/index', $data);
	}

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

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

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

		$titleSlug = $this->_slug($payload['title']);
		$payload['image'] = $this->_maybe_upload('image', 'courses/' . $docId . '/' . $titleSlug . '-cover', 'jpg');
		$payload['video'] = $this->_maybe_upload('video', 'courses/' . $docId . '/' . $titleSlug . '-video', 'mp4');

		$ok = $this->common->adddatamodel('Courses', $docId, $payload);
		if ($ok) {
			$this->session->set_flashdata('successmessage', 'Course created.');
			redirect(base_url('aoust_courses'));
			return;
		}
		$this->session->set_flashdata('warningmessage', 'Failed to create course.');
		redirect(base_url('aoust_courses/create'));
	}

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

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

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

		$payload['updatedAt'] = date('c');
		$titleSlug = $this->_slug($payload['title']);
		$newImage = $this->_maybe_upload('image', 'courses/' . $id . '/' . $titleSlug . '-cover', 'jpg');
		if ($newImage !== '') $payload['image'] = $newImage;
		else $payload['image'] = isset($existing['image']) ? (string) $existing['image'] : '';

		$newVideo = $this->_maybe_upload('video', 'courses/' . $id . '/' . $titleSlug . '-video', 'mp4');
		if ($newVideo !== '') $payload['video'] = $newVideo;
		else $payload['video'] = isset($existing['video']) ? (string) $existing['video'] : '';

		$ok = $this->common->updatedatamodel('Courses', $id, $payload);
		if ($ok) {
			$this->session->set_flashdata('successmessage', 'Course updated.');
			redirect(base_url('aoust_courses'));
			return;
		}
		$this->session->set_flashdata('warningmessage', 'Failed to update course.');
		redirect(base_url('aoust_courses/edit/' . rawurlencode($id)));
	}

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

	private function _empty_course()
	{
		$sessiondata = $this->session->userdata['session_data'];
		$userId = isset($sessiondata['userId']) ? (string) $sessiondata['userId'] : '';
		return array(
			'id' => '',
			'title' => '',
			'category' => '',
			'duration' => '',
			'video' => '',
			'image' => '',
			'description' => '',
			'userId' => $userId,
			'mcqs' => array(),
		);
	}

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

		$mcqs_json = (string) $this->input->post('mcqs_json');
		$mcqs = array();
		if ($mcqs_json !== '') {
			$d = json_decode($mcqs_json, true);
			if (is_array($d)) $mcqs = $d;
		}

		return array(
			'title' => trim((string) $this->input->post('title')),
			'category' => trim((string) $this->input->post('category')),
			'duration' => trim((string) $this->input->post('duration')),
			'description' => trim((string) $this->input->post('description')),
			'userId' => $userId,
			'mcqs' => $mcqs,
			'video' => '',
			'image' => '',
		);
	}

	private function _validate_course($payload)
	{
		$errors = array();
		if (empty($payload['title'])) $errors[] = 'Title is required.';
		if (!isset($payload['mcqs']) || !is_array($payload['mcqs']) || count($payload['mcqs']) === 0) {
			$errors[] = 'Add at least 1 course MCQ.';
		}

		$errors = array_merge($errors, $this->_validate_mcqs($payload['mcqs'], 'Course MCQ'));

		return $errors;
	}

	private function _validate_mcqs($questions, $labelPrefix)
	{
		$errors = array();
		if (!is_array($questions)) return $errors;
		foreach ($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[] = "{$labelPrefix} {$n}: text is required.";
			if (count($options) < 3) $errors[] = "{$labelPrefix} {$n}: at least 3 options required.";
			if (count($options) > 6) $errors[] = "{$labelPrefix} {$n}: max 6 options allowed.";
			if ($correctIndex < 0 || $correctIndex >= count($options)) $errors[] = "{$labelPrefix} {$n}: choose a correct answer.";
		}
		return $errors;
	}

	private function _slug($s)
	{
		$s = strtolower(trim((string) $s));
		$s = preg_replace('/[^a-z0-9]+/', '-', $s);
		$s = trim($s, '-');
		return $s ?: 'course';
	}

	private function _maybe_upload($field, $pathPrefix, $fallbackExt = 'jpg')
	{
		if (!isset($_FILES[$field]) || !is_array($_FILES[$field])) return '';
		if (!isset($_FILES[$field]['tmp_name']) || $_FILES[$field]['tmp_name'] === '') return '';
		if (!is_uploaded_file($_FILES[$field]['tmp_name'])) return '';

		$tmp = $_FILES[$field]['tmp_name'];
		$orig = isset($_FILES[$field]['name']) ? (string) $_FILES[$field]['name'] : '';
		$ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
		if ($ext === '') $ext = $fallbackExt;
		$objectName = $pathPrefix . '-' . date('YmdHis') . '.' . $ext;

		try {
			$firebase = $this->firebase->init();
			$storage = $firebase->createStorage();
			$bucket = $storage->getBucket();
			$bucket->upload(
				fopen($tmp, 'r'),
				array(
					'name' => $objectName,
					'predefinedAcl' => 'publicRead',
				)
			);
			$publicUrl = sprintf('https://storage.googleapis.com/%s/%s', $bucket->name(), $objectName);
			return $publicUrl;
		} catch (Exception $e) {
			return '';
		}
	}
}

