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

class Courses extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->helper(['url', 'form']);
		$this->load->library(['session', 'template']);
		$this->load->library('firebase');
		$this->load->model('common');
	}

	private function uuidV4()
	{
		$data = random_bytes(16);
		// Set version to 0100
		$data[6] = chr((ord($data[6]) & 0x0f) | 0x40);
		// Set bits 6-7 to 10
		$data[8] = chr((ord($data[8]) & 0x3f) | 0x80);
		$hex = bin2hex($data);
		return sprintf(
			'%s-%s-%s-%s-%s',
			substr($hex, 0, 8),
			substr($hex, 8, 4),
			substr($hex, 12, 4),
			substr($hex, 16, 4),
			substr($hex, 20, 12)
		);
	}

	private function normalizeCourseInput($input)
	{
		$duration = isset($input['duration']) ? (int)$input['duration'] : 0;
		$price = isset($input['price']) ? trim((string)$input['price']) : '';

		return [
			'category' => isset($input['category']) ? trim((string)$input['category']) : '',
			'title' => isset($input['title']) ? trim((string)$input['title']) : '',
			'description' => isset($input['description']) ? trim((string)$input['description']) : '',
			'duration' => $duration,
			'price' => $price,
			'thumbnail' => isset($input['thumbnail']) ? trim((string)$input['thumbnail']) : '',
			'userId' => 'nafFVeLpqtTu2SFqv4SJAZS9BEi2',
		];
	}

	private function uploadThumbnailIfPresent($courseId, $existingUrl = '')
	{
		if (empty($_FILES['thumbnail_file']) || empty($_FILES['thumbnail_file']['tmp_name'])) {
			return $existingUrl;
		}

		$tmp = $_FILES['thumbnail_file']['tmp_name'];
		$original = isset($_FILES['thumbnail_file']['name']) ? (string)$_FILES['thumbnail_file']['name'] : '';
		$ext = strtolower(pathinfo($original, PATHINFO_EXTENSION));
		if (!in_array($ext, ['jpg', 'jpeg', 'png', 'webp', 'gif'], true)) {
			$ext = 'jpg';
		}

		$objectName = 'coursePlan/' . $courseId . '.' . $ext;

		$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$bucket = $storage->getBucket();

		$bucket->upload(
			file_get_contents($tmp),
			[
				'name' => $objectName,
				'predefinedAcl' => 'publicRead',
			]
		);

		// Public URL style used across this codebase
		$bucketName = $bucket->name();
		return 'https://storage.googleapis.com/' . $bucketName . '/' . $objectName;
	}

	public function index()
	{
		$data['courses'] = $this->common->readdatafromcollectionbetween('courses');
		$this->template->template_render('courses_crud/index', $data);
	}

	public function create()
	{
		$data['course'] = null;
		$data['mode'] = 'create';
		$data['currentUserId'] = $this->session->userdata('session_data')['userId'] ?? '';
		$this->template->template_render('courses_crud/form', $data);
	}

	public function store()
	{
		$post = $this->input->post();
		$courseId = $this->uuidV4();
		$data = $this->normalizeCourseInput($post);

		$data['courseID'] = $courseId;
		$data['userId'] =  'nafFVeLpqtTu2SFqv4SJAZS9BEi2';
		$data['thumbnail'] = $this->uploadThumbnailIfPresent($courseId, $data['thumbnail']);
		$response = $this->common->adddatamodel('courses', $courseId, $data);
		$baby=array();
		$baby['courseId'] = $courseId;
		$baby['chatType'] = "many";
		$baby['lastMessage']=null;
		$baby['ownerId'] =  'nafFVeLpqtTu2SFqv4SJAZS9BEi2';
		$baby['participants'] = array();
		$baby['participants']['nafFVeLpqtTu2SFqv4SJAZS9BEi2'] = true;
		$response = $this->common->adddatamodel('Chats', $courseId, $baby);


		if ($response) {
			$this->session->set_flashdata('successmessage', 'Course created successfully');
			redirect(base_url('courses'));
			return;
		}

		$this->session->set_flashdata('warningmessage', 'Failed to create course');
		redirect(base_url('courses/create'));
	}

	public function show($courseId)
	{
		$data['courseId'] = $courseId;
		$data['course'] = $this->common->readdatadocument('courses', $courseId);
		if (!$data['course']) {
			$this->session->set_flashdata('warningmessage', 'Course not found');
			redirect(base_url('courses'));
			return;
		}
		$this->template->template_render('courses_crud/show', $data);
	}

	public function edit($courseId)
	{
		$data['courseId'] = $courseId;
		$data['course'] = $this->common->readdatadocument('courses', $courseId);
		if (!$data['course']) {
			$this->session->set_flashdata('warningmessage', 'Course not found');
			redirect(base_url('courses'));
			return;
		}
		$data['mode'] = 'edit';
		$data['currentUserId'] = $this->session->userdata('session_data')['userId'] ?? '';
		$this->template->template_render('courses_crud/form', $data);
	}

	public function update($courseId)
	{
		$post = $this->input->post();
		$data = $this->normalizeCourseInput($post);

		// Ensure these stay consistent
		$data['courseID'] = $courseId;
		$data['thumbnail'] = $this->uploadThumbnailIfPresent($courseId, $data['thumbnail']);

		$response = $this->common->updatedatamodel('courses', $courseId, $data);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Course updated successfully');
			redirect(base_url('courses/edit/' . $courseId));
			return;
		}

		$this->session->set_flashdata('warningmessage', 'Failed to update course');
		redirect(base_url('courses/edit/' . $courseId));
	}

	public function delete($courseId)
	{
		$response = $this->common->deletedatamodel('courses', $courseId);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Course deleted successfully');
		} else {
			$this->session->set_flashdata('warningmessage', 'Failed to delete course');
		}
		redirect(base_url('courses'));
	}
}

