<?php
/**
 * MeetingTypeService
 *
 * Handles CRUD orchestration for meeting types including
 * availability and date override synchronization.
 *
 * @package RadiusTheme\RadiusBooking\Services
 * @since   1.2.0
 */

namespace RadiusTheme\RadiusBooking\Services;

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

use RadiusTheme\RadiusBooking\Models\MeetingType;
use RadiusTheme\RadiusBooking\Repositories\MeetingTypeRepository;

/**
 * Class MeetingTypeService
 */
class MeetingTypeService {

	/**
	 * @var MeetingTypeRepository
	 */
	private MeetingTypeRepository $repo;

	/**
	 * MeetingTypeService constructor.
	 *
	 * @param MeetingTypeRepository $repo Meeting type repository.
	 */
	public function __construct( MeetingTypeRepository $repo ) {
		$this->repo = $repo;
	}

	/**
	 * Create a meeting type with availability and date overrides.
	 *
	 * @param array $data Meeting type data including optional 'availability' and 'date_overrides'.
	 *
	 * @return MeetingType The newly created meeting type.
	 */
	public function createMeetingType( array $data ): MeetingType {
		$availability  = $data['availability'] ?? array();
		$date_overrides = $data['date_overrides'] ?? array();
		unset( $data['availability'], $data['date_overrides'] );

		$meeting_type = $this->repo->create( $data );

		if ( ! empty( $availability ) ) {
			$this->repo->syncAvailability( $meeting_type->id, $availability );
		}

		if ( ! empty( $date_overrides ) ) {
			$this->repo->syncDateOverrides( $meeting_type->id, $date_overrides );
		}

		return $meeting_type;
	}

	/**
	 * Update a meeting type with availability and date overrides.
	 *
	 * @param int   $id   Meeting type ID.
	 * @param array $data Updated data.
	 *
	 * @return bool Whether the update succeeded.
	 */
	public function updateMeetingType( int $id, array $data ): bool {
		$availability   = $data['availability'] ?? null;
		$date_overrides = $data['date_overrides'] ?? null;
		unset( $data['availability'], $data['date_overrides'] );

		$result = $this->repo->update( $id, $data );

		if ( null !== $availability ) {
			$this->repo->syncAvailability( $id, $availability );
		}

		if ( null !== $date_overrides ) {
			$this->repo->syncDateOverrides( $id, $date_overrides );
		}

		return $result;
	}

	/**
	 * Get a meeting type by slug for the public booking page.
	 *
	 * @param string $slug The meeting type slug.
	 *
	 * @return array|null Meeting type data with availability, or null if not found.
	 */
	public function getPublicMeetingType( string $slug ): ?array {
		$meeting_type = $this->repo->findBySlug( $slug );

		if ( ! $meeting_type ) {
			return null;
		}

		$availability   = $this->repo->getAvailability( $meeting_type->id );
		$date_overrides = $this->repo->getDateOverrides( $meeting_type->id );

		return array(
			'meeting_type'   => $meeting_type,
			'availability'   => $availability,
			'date_overrides' => $date_overrides,
		);
	}
}
