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

/**
 * Admin / Tickets — view Paystack event-ticket purchases.
 */
#[\AllowDynamicProperties]
class Tickets extends Admin_Controller {

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

	public function index()
	{
		$tickets = $this->ticket_model->get_all();

		// Attach the event title to each ticket row for display.
		$events = array();
		foreach ($this->event_model->get_all() as $e)
		{
			$events[$e['id']] = $e['title'];
		}
		foreach ($tickets as &$t)
		{
			$t['event_title'] = $events[$t['event_id']] ?? '—';
		}
		unset($t);

		// Summary figures
		$paid = array_filter($tickets, function ($t) { return $t['payment_status'] === 'paid'; });
		$summary = array(
			'total'   => count($tickets),
			'paid'    => count($paid),
			'revenue' => $this->ticket_model->total_revenue(),
			'tickets_sold' => array_sum(array_column($paid, 'quantity')),
		);

		$this->render('tickets/index', array(
			'page_title' => 'Event Tickets',
			'tickets'    => $tickets,
			'summary'    => $summary,
		));
	}

	/** Verify a single ticket code (gate check helper). */
	public function verify()
	{
		$code = $this->input->get('code', TRUE);
		$ticket = $code ? $this->ticket_model->by_code($code) : NULL;

		$this->render('tickets/verify', array(
			'page_title' => 'Verify Ticket',
			'code'       => $code,
			'ticket'     => $ticket,
			'event'      => ($ticket ? $this->event_model->get($ticket['event_id']) : NULL),
		));
	}
}
