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

/**
 * Admin / Events — manage events, view RSVPs.
 */
#[\AllowDynamicProperties]
class Events_admin extends Admin_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model(array('event_model', 'ticket_model'));
	}

	public function index()
	{
		$this->render('events/index', array(
			'page_title'  => 'Events',
			'events'      => $this->event_model->get_all(),
			'event_types' => $this->config->item('event_types'),
		));
	}

	public function create()
	{
		$this->render('events/form', array(
			'page_title'  => 'Add Event',
			'event'       => $this->_blank(),
			'event_types' => $this->config->item('event_types'),
			'mode'        => 'create',
		));
	}

	public function edit($id)
	{
		$event = $this->event_model->get($id);
		if ( ! $event) show_404();
		$this->render('events/form', array(
			'page_title'  => 'Edit Event',
			'event'       => $event,
			'event_types' => $this->config->item('event_types'),
			'mode'        => 'edit',
		));
	}

	/** View RSVPs and ticket purchases for an event. */
	public function attendees($id)
	{
		$event = $this->event_model->get($id);
		if ( ! $event) show_404();
		$this->render('events/attendees', array(
			'page_title' => 'Attendees — '.$event['title'],
			'event'      => $event,
			'rsvps'      => $this->event_model->rsvps($id),
			'tickets'    => $this->ticket_model->for_event($id, FALSE),
		));
	}

	public function save()
	{
		$id = (int) $this->input->post('id');

		$this->load->library('form_validation');
		$this->form_validation->set_rules('title', 'Title', 'required|trim');
		$this->form_validation->set_rules('event_date', 'Event Date', 'required');

		if ($this->form_validation->run() === FALSE)
		{
			$this->session->set_flashdata('error', strip_tags(validation_errors()));
			redirect($id ? 'admin/events/edit/'.$id : 'admin/events/create');
		}

		$data = array(
			'title'        => $this->input->post('title', TRUE),
			'slug'         => $this->input->post('slug', TRUE) ?: url_title($this->input->post('title', TRUE), '-', TRUE),
			'event_type'   => $this->input->post('event_type', TRUE),
			'excerpt'      => $this->input->post('excerpt', TRUE),
			'description'  => $this->input->post('description', TRUE),
			'location'     => $this->input->post('location', TRUE),
			'event_date'   => $this->input->post('event_date', TRUE),
			'event_time'   => $this->input->post('event_time', TRUE),
			'allow_rsvp'   => $this->input->post('allow_rsvp') ? 1 : 0,
			'is_paid'      => $this->input->post('is_paid') ? 1 : 0,
			'ticket_price' => (float) $this->input->post('ticket_price'),
			'capacity'     => (int) $this->input->post('capacity'),
			'is_featured'  => $this->input->post('is_featured') ? 1 : 0,
			'is_active'    => $this->input->post('is_active') ? 1 : 0,
			'meta_title'   => $this->input->post('meta_title', TRUE),
			'meta_desc'    => $this->input->post('meta_desc', TRUE),
		);

		// Handle gallery (multi-upload, merged with existing)
		$new_gallery = $this->uploader->files('gallery', 'events');
		$existing = $id ? decode_json($this->event_model->get($id)['gallery']) : array();
		$keep = (array) $this->input->post('keep_gallery');
		$existing = array_values(array_intersect($existing, $keep));
		$data['gallery'] = json_encode(array_merge($existing, $new_gallery));

		// Handle cover image upload - convert array to string if needed
		$cover = NULL;
		if (isset($_FILES['cover_image']) && !empty($_FILES['cover_image']['name'])) {
			// If it's an array with one file, convert to standard structure
			if (is_array($_FILES['cover_image']['name'])) {
				if (count($_FILES['cover_image']['name']) === 1 && !empty($_FILES['cover_image']['name'][0])) {
					$_FILES['cover_image'] = array(
						'name'     => $_FILES['cover_image']['name'][0],
						'type'     => $_FILES['cover_image']['type'][0],
						'tmp_name' => $_FILES['cover_image']['tmp_name'][0],
						'error'    => $_FILES['cover_image']['error'][0],
						'size'     => $_FILES['cover_image']['size'][0],
					);
				}
			}
			$cover = $this->upload('cover_image', 'events');
		}
		if ($cover) $data['cover_image'] = $cover;

		if ($id)
		{
			// FIXED: Use event_model (not events_model)
			$this->event_model->update($id, $data);
			$this->log('Updated event', $data['title']);
			$msg = 'Event updated.';
		}
		else
		{
			// FIXED: Use event_model (not events_model)
			$this->event_model->insert($data);
			$this->log('Created event', $data['title']);
			$msg = 'Event created.';
		}

		$this->session->set_flashdata('success', $msg);
		redirect('admin/events');
	}
	
	public function delete($id)
	{
		$e = $this->event_model->get($id);
		if ($e)
		{
			// Delete cover image if exists
			if (!empty($e['cover_image'])) {
				$this->uploader->remove($e['cover_image']);
			}
			$this->event_model->delete($id);
			$this->log('Deleted event', $e['title']);
			$this->session->set_flashdata('success', 'Event deleted.');
		}
		redirect('admin/events');
	}

	public function toggle($id)
	{
		$e = $this->event_model->get($id);
		if ($e) $this->event_model->update($id, array('is_active' => $e['is_active'] ? 0 : 1));
		redirect('admin/events');
	}

	private function _blank()
	{
		return array(
			'id' => 0, 
			'title' => '', 
			'slug' => '', 
			'event_type' => '', 
			'cover_image' => '',
			'excerpt' => '', 
			'description' => '', 
			'event_date' => '', 
			'event_time' => '',
			'location' => '', 
			'gallery' => '[]', 
			'allow_rsvp' => 1, 
			'is_paid' => 0,
			'ticket_price' => 0, 
			'capacity' => 0, 
			'is_featured' => 0, 
			'is_active' => 1,
			'meta_title' => '', 
			'meta_desc' => '',
		);
	}
}