<?php
/**
 * AppointmentIntegration Service
 */
namespace RadiusTheme\RadiusBooking\Services;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}
use RadiusTheme\RadiusBooking\Repositories\AppointmentIntegrationRepository;

/**
 * Services/AppointmentIntegrationService.php
 * Business logic layer for AppointmentIntegration.
 */
class AppointmentIntegrationService {

	/**
	 * AppointmentIntegration Repository
	 *
	 * @var AppointmentIntegrationRepository $integrationRepo
	 */
	private AppointmentIntegrationRepository $integrationRepo;

	/**
	 * Constructor method for initializing repositories.
	 *
	 * @param AppointmentIntegrationRepository $appointmentIntegrationRepo Repository for managing appointment integrations.
	 */
	public function __construct( AppointmentIntegrationRepository $appointmentIntegrationRepo ) {
		$this->integrationRepo = $appointmentIntegrationRepo;
	}

	/**
	 * Stores or updates an appointment's integration data based on its existence.
	 *
	 * @param int|string $appointmentId The unique identifier of the appointment.
	 * @param string $provider The name of the external provider.
	 * @param array $data The data to be stored or updated, containing fields such as external event ID, calendar ID, URLs, meta details, and status.
	 *
	 * @return mixed The result of the create or update operation performed by the repository.
	 */
	public function storeOrUpdate( $appointmentId, $provider, array $data ) {
		$existing = $this->integrationRepo->findByAppointmentAndProvider( $appointmentId, $provider );
		$payload  = array(
			'appointment_id'       => $appointmentId,
			'provider'             => $provider,
			'external_event_id'    => $data['external_event_id'] ?? null,
			'external_calendar_id' => $data['external_calendar_id'] ?? null,
			'meeting_url'          => $data['meeting_url'] ?? null,
			'join_url'             => $data['join_url'] ?? null,
			'start_url'            => $data['start_url'] ?? null,
			'meta'                 => $data['meta'] ?? array(),
			'status'               => $data['status'] ?? 'created',
		);

		if ( $existing ) {
			return $this->integrationRepo->update( $existing->id, $payload );
		}
		return $this->integrationRepo->create( $payload );
	}

	/**
	 * Retrieves data associated with a specific appointment.
	 *
	 * @param int|string $appointmentId The ID of the appointment to retrieve data for.
	 *
	 * @return mixed The data retrieved for the specific appointment.
	 */
	public function getByAppointment( $appointmentId ) {
		return $this->integrationRepo->getByAppointment( $appointmentId );
	}

	/**
	 * Deletes an entry associated with a given appointment ID.
	 *
	 * @param mixed $appointmentId The ID of the appointment to delete.
	 *
	 * @return mixed The result of the delete operation.
	 */
	public function deleteByAppointment( $appointmentId ) {
		return $this->integrationRepo->deleteByAppointment( $appointmentId );
	}
	// Add business logic methods here...
}
