<?php
/**
 * EventResource
 *
 * Transforms Event model data into API response format.
 *
 * @package RadiusTheme\RadiusBooking\Resources
 * @since   1.2.0
 */

namespace RadiusTheme\RadiusBooking\Resources;

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

use RadiusTheme\RadiusBooking\Abstracts\BaseResource;
use RadiusTheme\RadiusBooking\Helpers\SettingsHelper;
use RadiusTheme\RadiusBooking\Models\EventSession;
use RadiusTheme\RadiusBooking\Repositories\EventTicketTypeRepository;

/**
 * Class EventResource
 */
class EventResource extends BaseResource {

	/**
	 * Transform an event into an API-friendly array.
	 *
	 * @param mixed $event The event model or object.
	 *
	 * @return array
	 */
	public function transform( $event ): array {
		$ticket_repo  = new EventTicketTypeRepository();
		$ticket_types = $ticket_repo->getByEvent( $event->id );
		$sessions     = EventSession::where( 'event_id', $event->id )
			->orderBy( 'sort_order', 'ASC' )
			->get();

		return array(
			'id'                    => $event->id,
			'organizer_id'          => $event->organizer_id,
			'organizer_name'        => $this->getOrganizerName( $event->organizer_id ),
			'organizer_image'       => $this->getOrganizerImage( $event->organizer_id ),
			'name'                  => $event->name,
			'slug'                  => $event->slug,
			'description'           => $event->description,
			'short_description'     => $event->short_description,
			'event_type'            => $event->event_type,
			'start_date'            => $event->start_date,
			'end_date'              => $event->end_date,
			'start_time'            => $event->start_time,
			'end_time'              => $event->end_time,
			'timezone'              => $event->timezone,
			'location_type'         => $event->location_type,
			'location_value'        => $event->location_value,
			'category_id'           => $event->category_id,
			'capacity'              => $event->capacity,
			'registered_count'      => $event->registered_count,
			'waitlist_enabled'      => $event->waitlist_enabled,
			'waitlist_capacity'     => $event->waitlist_capacity,
			'status'                => $event->status,
			'registration_deadline' => $event->registration_deadline,
			'settings'              => $event->settings,
			'picture_full_path'     => $event->picture_full_path,
			'picture_thumb_path'    => $event->picture_thumb_path,
			'is_featured'           => $event->is_featured,
			'ticket_types'          => $this->formatTicketTypes( $ticket_types ),
			'sessions'              => $this->formatSessions( $sessions ),
			'shareable_url'         => $this->getShareableUrl( $event ),
			'created_at'            => $event->created_at ?? null,
			'updated_at'            => $event->updated_at ?? null,
		);
	}

	/**
	 * Get the organizer display name.
	 *
	 * @param int|null $organizer_id WordPress user ID.
	 *
	 * @return string|null
	 */
	private function getOrganizerName( $organizer_id ): ?string {
		if ( ! $organizer_id ) {
			return null;
		}

		// Try staff profile first_name + last_name first.
		$repo = \RadiusTheme\RadiusBooking\Core\Container\Container::resolve(
			\RadiusTheme\RadiusBooking\Repositories\UserProfileRepository::class
		);
		if ( $repo->exists( $organizer_id ) ) {
			$profile    = $repo->find( $organizer_id );
			$first_name = $profile->first_name ?? '';
			$last_name  = $profile->last_name ?? '';
			$full_name  = trim( $first_name . ' ' . $last_name );
			if ( ! empty( $full_name ) ) {
				return $full_name;
			}
		}

		// Fallback to WordPress display_name.
		$user = get_userdata( $organizer_id );
		return $user ? $user->display_name : null;
	}

	/**
	 * Get the organizer profile image URL.
	 *
	 * @param int|null $organizer_id WordPress user ID.
	 *
	 * @return string
	 */
	private function getOrganizerImage( $organizer_id ): string {
		if ( ! $organizer_id ) {
			return '';
		}
		$repo = \RadiusTheme\RadiusBooking\Core\Container\Container::resolve(
			\RadiusTheme\RadiusBooking\Repositories\UserProfileRepository::class
		);
		if ( $repo->exists( $organizer_id ) ) {
			$profile = $repo->find( $organizer_id );
			return $profile->getImageUrl() ?: '';
		}
		return '';
	}

	/**
	 * Format ticket type data for the API response.
	 *
	 * @param array $ticket_types Raw ticket type records.
	 *
	 * @return array
	 */
	private function formatTicketTypes( array $ticket_types ): array {
		return array_map(
			function ( $ticket ) {
				return array(
					'id'              => $ticket->id ?? ( $ticket['id'] ?? null ),
					'name'            => $ticket->name ?? ( $ticket['name'] ?? null ),
					'description'     => $ticket->description ?? ( $ticket['description'] ?? null ),
					'ticket_type'     => $ticket->ticket_type ?? ( $ticket['ticket_type'] ?? null ),
					'price'           => $ticket->price ?? ( $ticket['price'] ?? 0 ),
					'capacity'        => $ticket->capacity ?? ( $ticket['capacity'] ?? 0 ),
					'quantity_sold'   => $ticket->quantity_sold ?? ( $ticket['quantity_sold'] ?? 0 ),
					'sale_start_date' => $ticket->sale_start_date ?? ( $ticket['sale_start_date'] ?? null ),
					'sale_end_date'   => $ticket->sale_end_date ?? ( $ticket['sale_end_date'] ?? null ),
					'min_per_order'   => $ticket->min_per_order ?? ( $ticket['min_per_order'] ?? 1 ),
					'max_per_order'   => $ticket->max_per_order ?? ( $ticket['max_per_order'] ?? 10 ),
					'is_active'       => $ticket->is_active ?? ( $ticket['is_active'] ?? true ),
					'sort_order'      => $ticket->sort_order ?? ( $ticket['sort_order'] ?? 0 ),
				);
			},
			$ticket_types
		);
	}

	/**
	 * Format session data for the API response.
	 *
	 * @param array $sessions Raw session records.
	 *
	 * @return array
	 */
	/**
	 * Generate the public shareable registration URL.
	 *
	 * @param mixed $event The event model.
	 *
	 * @return string
	 */
	private function getShareableUrl( $event ): string {
		$pages   = SettingsHelper::get_setting( 'pages' );
		$page_id = $pages['eventRegistrationPage'] ?? 0;

		if ( $page_id ) {
			return add_query_arg( 'event', $event->slug, get_permalink( $page_id ) );
		}

		return site_url( '/event/' . $event->slug );
	}

	private function formatSessions( array $sessions ): array {
		return array_map(
			function ( $session ) {
				return array(
					'id'                => $session->id ?? ( $session['id'] ?? null ),
					'name'              => $session->name ?? ( $session['name'] ?? null ),
					'description'       => $session->description ?? ( $session['description'] ?? null ),
					'session_date'      => $session->session_date ?? ( $session['session_date'] ?? null ),
					'start_time'        => $session->start_time ?? ( $session['start_time'] ?? null ),
					'end_time'          => $session->end_time ?? ( $session['end_time'] ?? null ),
					'speaker'           => $session->speaker ?? ( $session['speaker'] ?? null ),
					'capacity'          => $session->capacity ?? ( $session['capacity'] ?? 0 ),
					'location_override' => $session->location_override ?? ( $session['location_override'] ?? null ),
					'sort_order'        => $session->sort_order ?? ( $session['sort_order'] ?? 0 ),
				);
			},
			$sessions
		);
	}
}
