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

/**
 * Ticket_model — Paystack event ticket purchases.
 */
#[\AllowDynamicProperties]
class Ticket_model extends MY_Model {

	protected $table = 'event_tickets';
	protected $order_by = 'created_at DESC';

	/** Fetch a ticket by its Paystack reference. */
	public function by_reference($reference)
	{
		return $this->get_by(array('reference' => $reference));
	}

	/** Fetch a ticket by its unique ticket code. */
	public function by_code($code)
	{
		return $this->get_by(array('ticket_code' => $code));
	}

	/** Mark a ticket paid and assign a ticket code. */
	public function mark_paid($id, $code)
	{
		return $this->update($id, array(
			'payment_status' => 'paid',
			'ticket_code'    => $code,
		));
	}

	/** Paid tickets for an event (admin). */
	public function for_event($event_id, $paid_only = TRUE)
	{
		$this->db->where('event_id', $event_id);
		if ($paid_only) $this->db->where('payment_status', 'paid');
		return $this->db->order_by('created_at DESC')
			->get($this->table)->result_array();
	}

	/** Total revenue from paid tickets. */
	public function total_revenue()
	{
		$row = $this->db->select_sum('amount')
			->where('payment_status', 'paid')
			->get($this->table)->row_array();
		return $row['amount'] ?: 0;
	}
}
