<?php
/**
 * Radius Booking - Single Layout "Booking Form" element.
 *
 * Renders the "Book Now" button and booking form modal
 * when placed in a Classified Listing Single Layout.
 *
 * @package RadiusTheme\RadiusBooking\Templates
 *
 * @var string                              $fieldUuid
 * @var \Rtcl\Services\FormBuilder\FBField  $field
 */

use RadiusTheme\RadiusBooking\Helpers\SettingsHelper;
use RadiusTheme\RadiusBooking\Models\EmployeeService;
use RadiusTheme\RadiusBooking\Models\Service;

defined( 'ABSPATH' ) || exit;

if ( ! class_exists( '\Rtcl\Services\FormBuilder\FBField' ) || ! is_a( $field, \Rtcl\Services\FormBuilder\FBField::class ) ) {
	return;
}

global $listing;
if ( ! is_a( $listing, '\Rtcl\Models\Listing' ) ) {
	return;
}

$listing_id = $listing->get_id();

// Only render on published listings with booking enabled.
if ( 'publish' !== get_post_status( $listing_id ) ) {
	return;
}
if ( ! get_post_meta( $listing_id, '_rtrb_booking_enabled', true ) ) {
	return;
}

$service = Service::where( 'listing_id', $listing_id )->first();
if ( ! $service || 'visible' !== $service->status ) {
	return;
}

$employee_service = EmployeeService::where( 'service_id', $service->id )->first();
$employee_id      = $employee_service ? $employee_service->user_id : '';

$settings    = SettingsHelper::get_setting( 'integrations' );
$cl_settings = $settings['classifiedListing'] ?? array();
$button_text = ! empty( $field->getField()['text'] ) ? $field->getField()['text'] : ( $cl_settings['bookNowButtonText'] ?? __( 'Book Now', 'radius-booking' ) );
?>

<div class="rtrb-cl-book-now-wrapper" style="margin-top: 15px; margin-bottom: 15px;">
	<button type="button" class="rtrb-cl-book-now btn btn-primary"
		data-listing-id="<?php echo esc_attr( $listing_id ); ?>"
		data-service-id="<?php echo esc_attr( $service->id ); ?>"
		style="width: 100%; padding: 12px 24px; background-color: #0040ff; color: #fff; border: none; border-radius: 6px; font-size: 16px; font-weight: 600; cursor: pointer;">
		<?php echo esc_html( $button_text ); ?>
	</button>
</div>

<?php
/**
 * Mark that the button was rendered via Single Layout so the hook-based
 * fallback in ListingFrontendHooks can skip its own rendering.
 */
if ( ! defined( 'RTRB_SL_BOOKING_RENDERED' ) ) {
	define( 'RTRB_SL_BOOKING_RENDERED', true );
}
