<?php
/**
 * Event helper functions.
 *
 * @package Awesomemotive\Rewardswp\Helpers
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Helpers;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Awesomemotive\Rewardswp\Database\Tables\EventsTable;
use Awesomemotive\Rewardswp\Models\Event;
use Awesomemotive\Rewardswp\Services\EventsService;
use Exception;
use WP_Error;

/**
 * Create a new event.
 *
 * @param array $args The arguments for creating the event (e.g., 'member_id', 'type', 'context', etc.).
 *
 * @return Event|WP_Error The created event object or a WP_Error on failure.
 */
function create_event( array $args ) {
	$args = wp_parse_args(
		$args,
		[
			'member_id'    => 0,
			'type'         => 'visit',
			'context'      => null,
			'ip_address'   => '',
			'referrer_url' => '',
			'landing_url'  => '',
			'created_at'   => get_current_time(),
		]
	);

	try {
		// Create a new event object.
		$event = am_rewardswp()->get_container()->make( Event::class );

		// Populate the object.
		$event->hydrate( $args );

		// Attempt to create the event.
		$event->create();

		return $event;
	} catch ( Exception $e ) {
		return new WP_Error( 'general_error', $e->getMessage() );
	}
}

/**
 * Return a event by its id.
 *
 * @since 1.0.0
 *
 * @param int $event_id The event ID.
 *
 * @return Event|null
 */
function get_event( int $event_id ): ?Event {
	try {
		$event = am_rewardswp()->get_container()->make( Event::class );

		$event->load( $event_id );

		return $event;
	} catch ( Exception $e ) {
		return null;
	}
}

/**
 * Retrieve events based on the given parameters and pagination options.
 *
 * @since 1.0.0
 *
 * @param array $query_args An associative array of conditions to filter events.
 *                          See {@see EventsTable::get_columns()} for available parameters.
 * @param int   $per_page   Optional. The number of items per page for pagination. Default to 10.
 * @param int   $page       Optional. The page number for pagination. Default to 1.
 *
 * @return Event[] Array of events.
 */
function get_events( array $query_args = [], int $per_page = 10, int $page = 1 ): array {
	try {
		$events_service = am_rewardswp()->get_container()->make( EventsService::class );
		return $events_service->get_events( $query_args, $per_page, $page );
	} catch ( Exception $e ) {
		return [];
	}
}
