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

/**
 * Activity CRUD (Firestore collection: Activities)
 * Fields: title, image, description, documentUrl
 * Uploads: image + document to Firebase Storage; stores URL in Firestore.
 */
class Aoust_activity 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 — Activity';
		$rows = $this->common->readdatafromcollectionwhereclause('Activities');
		$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['activities'] = $list;
		$this->template->template_render('admin/activity/index', $data);
	}

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

	public function store()
	{
		$payload = $this->_read_payload_from_post();
		if ($payload['title'] === '') {
			$this->session->set_flashdata('warningmessage', 'Title is required.');
			redirect(base_url('aoust_activity/create'));
			return;
		}

		$docId = 'act_' . 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', 'activity/' . $docId . '/' . $titleSlug . '-image');
		$payload['documentUrl'] = $this->_maybe_upload('document', 'activity/' . $docId . '/' . $titleSlug . '-document');

		$ok = $this->common->adddatamodel('Activities', $docId, $payload);
		if ($ok) {
			$this->session->set_flashdata('successmessage', 'Activity created.');
			redirect(base_url('aoust_activity'));
			return;
		}
		$this->session->set_flashdata('warningmessage', 'Failed to create activity.');
		redirect(base_url('aoust_activity/create'));
	}

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

		$row = $this->common->readdatadocument('Activities', $id);
		if (empty($row) || !is_array($row)) {
			$this->session->set_flashdata('warningmessage', 'Activity not found.');
			redirect(base_url('aoust_activity'));
			return;
		}
		$row['id'] = $id;

		$data['page_title'] = 'AOUST — Edit Activity';
		$data['mode'] = 'edit';
		$data['activity'] = array_merge($this->_empty_activity(), $row);
		$this->template->template_render('admin/activity/form', $data);
	}

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

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

		$payload = $this->_read_payload_from_post();
		if ($payload['title'] === '') {
			$this->session->set_flashdata('warningmessage', 'Title is required.');
			redirect(base_url('aoust_activity/edit/' . rawurlencode($id)));
			return;
		}

		$payload['updatedAt'] = date('c');

		$titleSlug = $this->_slug($payload['title']);
		$newImage = $this->_maybe_upload('image', 'activity/' . $id . '/' . $titleSlug . '-image');
		$newDoc = $this->_maybe_upload('document', 'activity/' . $id . '/' . $titleSlug . '-document');

		$payload['image'] = ($newImage !== '') ? $newImage : (isset($existing['image']) ? (string) $existing['image'] : '');
		$payload['documentUrl'] = ($newDoc !== '') ? $newDoc : (isset($existing['documentUrl']) ? (string) $existing['documentUrl'] : '');

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

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

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

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

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

		return array(
			'title' => trim((string) $this->input->post('title')),
			'description' => trim((string) $this->input->post('description')),
			'userId' => $userIdPost !== '' ? $userIdPost : $userId,
			// URLs filled by upload step
			'image' => '',
			'documentUrl' => '',
		);
	}

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

	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 = 'bin';
		$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',
				)
			);
			return sprintf('https://storage.googleapis.com/%s/%s', $bucket->name(), $objectName);
		} catch (Exception $e) {
			return '';
		}
	}
}

