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

/**
 * Webinars CRUD (Firestore: Webinars, images in Firebase Storage).
 */
class Aoust_webinars extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->helper(array('url', 'form'));
		$this->load->library('session');
		$this->load->database();

		// Guard: require login session used by header/sidebar.
		if (!isset($this->session->userdata['session_data'])) {
			redirect(base_url('login'));
			return;
		}
	}

	public function index()
	{
		$data['page_title'] = 'AOUST — Webinars';
		$rows = $this->common->readdatafromcollectionwhereclause('Webinars');
		$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['webinars'] = $list;

		$this->template->template_render('admin/webinars/index', $data);
	}

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

	public function store()
	{
		$payload = $this->_read_payload_from_post();

		$payload['timeStamp'] = round(microtime(true) * 1000);
		$payload['createdAt'] = date('c');

		// Images
		$titleSlug = $this->_slug($payload['title']);
		$docId = 'web_' . uniqid();
		$payload['image'] = $this->_maybe_upload('image', 'webinars/' . $docId . '/' . $titleSlug . '-cover');
		$payload['speakerImage'] = $this->_maybe_upload('speakerImage', 'webinars/' . $docId . '/' . $titleSlug . '-speaker');

		// Required-ish: keep empty strings instead of null
		$payload = $this->_normalize_webinar($payload);

		$ok = $this->common->adddatamodel('Webinars', $docId, $payload);
		if ($ok) {
			$this->session->set_flashdata('successmessage', 'Webinar created.');
			redirect(base_url('aoust_webinars'));
			return;
		}

		$this->session->set_flashdata('warningmessage', 'Failed to create webinar.');
		redirect(base_url('aoust_webinars/create'));
	}

	public function edit($id = '')
	{
		$id = trim((string) $id);
		if ($id === '') {
			redirect(base_url('aoust_webinars'));
			return;
		}

		$row = $this->common->readdatadocument('Webinars', $id);
		if (empty($row) || !is_array($row)) {
			$this->session->set_flashdata('warningmessage', 'Webinar not found.');
			redirect(base_url('aoust_webinars'));
			return;
		}

		$row['id'] = $id;
		$data['page_title'] = 'AOUST — Edit Webinar';
		$data['mode'] = 'edit';
		$data['webinar'] = array_merge($this->_empty_webinar(), $row);
		$this->template->template_render('admin/webinars/form', $data);
	}

	public function update($id = '')
	{
		$id = trim((string) $id);
		if ($id === '') {
			redirect(base_url('aoust_webinars'));
			return;
		}

		$existing = $this->common->readdatadocument('Webinars', $id);
		if (empty($existing) || !is_array($existing)) {
			$this->session->set_flashdata('warningmessage', 'Webinar not found.');
			redirect(base_url('aoust_webinars'));
			return;
		}

		$payload = $this->_read_payload_from_post();
		$payload['updatedAt'] = date('c');

		$titleSlug = $this->_slug($payload['title']);
		$newCover = $this->_maybe_upload('image', 'webinars/' . $id . '/' . $titleSlug . '-cover');
		$newSpeaker = $this->_maybe_upload('speakerImage', 'webinars/' . $id . '/' . $titleSlug . '-speaker');

		if ($newCover !== '') $payload['image'] = $newCover;
		else $payload['image'] = isset($existing['image']) ? (string) $existing['image'] : '';

		if ($newSpeaker !== '') $payload['speakerImage'] = $newSpeaker;
		else $payload['speakerImage'] = isset($existing['speakerImage']) ? (string) $existing['speakerImage'] : '';

		$payload = $this->_normalize_webinar($payload);

		$ok = $this->common->updatedatamodel('Webinars', $id, $payload);
		if ($ok) {
			$this->session->set_flashdata('successmessage', 'Webinar updated.');
			redirect(base_url('aoust_webinars'));
			return;
		}

		$this->session->set_flashdata('warningmessage', 'Failed to update webinar.');
		redirect(base_url('aoust_webinars/edit/' . rawurlencode($id)));
	}

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

	public function toggle($id = '')
	{
		$id = trim((string) $id);
		if ($id === '') {
			redirect(base_url('aoust_webinars'));
			return;
		}
		$row = $this->common->readdatadocument('Webinars', $id);
		if (empty($row) || !is_array($row)) {
			redirect(base_url('aoust_webinars'));
			return;
		}
		$active = isset($row['isActive']) ? (bool) $row['isActive'] : false;
		$this->common->updatedatamodel('Webinars', $id, array(
			'isActive' => !$active,
			'updatedAt' => date('c'),
		));
		redirect(base_url('aoust_webinars'));
	}

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

		$isActiveRaw = $this->input->post('isActive');
		$isActive = ($isActiveRaw === '1' || $isActiveRaw === 'true' || $isActiveRaw === 'on');
		$datatime=$this->input->post('date').' '.$this->input->post('time');
		$datatimems=strtotime($datatime)*1000;

		return array(
			'title' => (string) $this->input->post('title'),
			'date' => (string) $this->input->post('date'),
			'time' => (string) $this->input->post('time'),
			'startTime' => $datatimems,
			'endTime' => $datatimems + (int) $this->input->post('duration') * 60 * 1000,
			'language' => (string) $this->input->post('language'),
			'duration' => (string) $this->input->post('duration'),
			'description' => (string) $this->input->post('description'),
			'speakerName' => (string) $this->input->post('speakerName'),
			'speakerPosition' => (string) $this->input->post('speakerPosition'),
			'isActive' => $isActive,
			'userId' => $userId,
			'noOfParticipant' => 0,
		);
	}

	private function _empty_webinar()
	{
		return array(
			'id' => '',
			'title' => '',
			'image' => '',
			'date' => '',
			'time' => '',
			'language' => '',
			'duration' => '',
			'description' => '',
			'speakerName' => '',
			'speakerPosition' => '',
			'speakerImage' => '',
			'isActive' => false,
			'userId' => '',
			'noOfParticipant' => 0,
		);
	}

	private function _normalize_webinar($payload)
	{
		$base = $this->_empty_webinar();
		foreach ($base as $k => $_) {
			if (!array_key_exists($k, $payload)) continue;
			if (is_string($base[$k])) {
				$payload[$k] = trim((string) $payload[$k]);
			}
		}
		return $payload;
	}

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

	private function _maybe_upload($field, $pathPrefix)
	{
		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 = 'jpg';
		$objectName = $pathPrefix . '-' . date('YmdHis') . '.' . $ext;

		try {
			$firebase = $this->firebase->init();
			$storage = $firebase->createStorage();
			$bucket = $storage->getBucket();
			$object = $bucket->upload(
				fopen($tmp, 'r'),
				array(
					'name' => $objectName,
					'predefinedAcl' => 'publicRead',
				)
			);
			// Prefer public URL if ACL allowed; otherwise fall back to signed URL.
			$publicUrl = sprintf('https://storage.googleapis.com/%s/%s', $bucket->name(), $objectName);
			return $publicUrl;
		} catch (Exception $e) {
			try {
				$firebase = $this->firebase->init();
				$storage = $firebase->createStorage();
				$bucket = $storage->getBucket();
				$bucket->upload(fopen($tmp, 'r'), array('name' => $objectName));
				$publicUrl = sprintf('https://storage.googleapis.com/%s/%s', $bucket->name(), $objectName);
				return $publicUrl;
			} catch (Exception $e2) {
				return '';
			}
		}
	}
}

