<?php

/**
 * Payment
 */

namespace RadiusTheme\RadiusBooking\Resources;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}
use RadiusTheme\RadiusBooking\Abstracts\BaseResource;
use RadiusTheme\RadiusBooking\Helpers\SettingsHelper;
use RadiusTheme\RadiusBooking\Models\CustomerBooking;
use RadiusTheme\RadiusBooking\Models\Payment;

/**
 * Api/Resources/PaymentResource.php
 * Payment resource transformer
 *
 * @package RadiusTheme\RadiusBooking\Resources
 */
class PaymentResource extends BaseResource {

	/**
	 * Transform a Payment model into an API-friendly array.
	 *
	 * @param object $payment The Payment model instance.
	 *
	 * @return array Transformed data.
	 */
	public function transform( $payment ): array {
		return array(
			'id'               => $payment->id,
			'booking_id'       => $payment->booking_id,
			'appointment_data' => $this->getBookingData( $payment->id, $payment->booking_id ),
			'currency'         => array(
				'currency_symbol' => get_rtrb_currency_symbol(),
				'currency'        => get_rtrb_currency(),
			),
			'business_settings' => SettingsHelper::get_setting( 'business' ) ?? array(),
			'admin_email'       => get_option( 'admin_email' ),
			'site_url'          => get_site_url(),
		);
	}

	/**
	 * Retrieve booking data associated with a payment and booking ID.
	 *
	 * @param int $paymentId The ID of the payment.
	 * @param int $bookingId The ID of the booking.
	 *
	 * @return array|null Transformed booking data or null if the booking ID is not provided.
	 */
	public function getBookingData( $paymentId, $bookingId ) {
		if ( ! $bookingId ) {
			return null;
		}
		$payment = Payment::find( $paymentId );
		if ( ! $payment ) {
			return null;
		}
		$booking = $payment->booking()->get();
		if ( ! $booking ) {
			return null;
		}
		$booking->customer_info = maybe_unserialize( $booking->customer_info );
		$customerBooking        = CustomerBooking::find( $booking->id );
		if ( ! $customerBooking ) {
			return null;
		}
		$appointment = $customerBooking->appointments()->get();
		if ( ! $appointment ) {
			return null;
		}
		return ( new AppointmentResource() )->transform( $appointment );
	}
}
