<?php

use RadiusTheme\RadiusBooking\Helpers\SettingsHelper;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}
/**
 * Display the login form.
 *
 * @param array $args {
 *     Optional. Array of arguments for customizing the form.
 *
 * @type string $message Message to display above the form. Default empty.
 * @type string $redirect_to URL to redirect after login. Default current page.
 * @type bool $hidden Whether the form should be hidden initially. Default false.
 * }
 * @return void
 * @since 1.0.0
 */
function radius_booking_login_form( $args = array() ) {
	$defaults = array(
		'message'             => '',
		'redirect_to'         => radius_booking_get_current_url(),
		'hidden'              => false,
		'registration_enable' => true
	);
	$args = wp_parse_args( $args, $defaults );

	// Extract variables for template.
	$message             = $args['message'];
	$redirect_to         = $args['redirect_to'];
	$hidden              = $args['hidden'];
	$registration_enable = $args['registration_enable'];

	rtrb_get_template( 'global/form-login.php', compact( 'message', 'redirect_to', 'hidden','registration_enable' ) );
}

/**
 * Display the signup form.
 *
 * @param array $args {
 *     Optional. Array of arguments for customizing the form.
 *
 * @type string $message Message to display above the form. Default empty.
 * @type string $redirect_to URL to redirect after signup. Default current page.
 * @type bool $hidden Whether the form should be hidden initially. Default false.
 * }
 * @return void
 * @since 1.0.0
 */
function radius_booking_signup_form( $args = array() ) {
	$defaults = array(
		'message'     => '',
		'redirect_to' => radius_booking_get_current_url(),
		'hidden'      => false,
	);

	$args = wp_parse_args( $args, $defaults );

	// Extract variables for template.
	$message     = $args['message'];
	$redirect_to = $args['redirect_to'];
	$hidden      = $args['hidden'];

	rtrb_get_template( 'global/form-signup.php', compact( 'message', 'redirect_to', 'hidden' ) );
}

/**
 * Track whether at least one Classified Listing booking button was rendered
 * on the current request, so the shared modal shell only prints when needed.
 *
 * @param bool|null $set Pass true to mark the modal as needed.
 *
 * @return bool Whether the shared booking modal should be rendered.
 * @since 1.0.0
 */
function rtrb_cl_booking_modal_needed( $set = null ) {
	static $needed = false;

	if ( true === $set ) {
		$needed = true;
	}

	return $needed;
}

/**
 * Build the Classified Listing "Book Now" button markup.
 *
 * Drop this anywhere a listing is available — single listing templates, the
 * archive loop, widgets, shortcodes. Clicking the rendered button opens the
 * shared booking modal pre-loaded with that listing's service/employee.
 *
 * Returns an empty string when Classified Listing is inactive or the listing
 * is not bookable, so it is safe to call unconditionally inside a loop.
 *
 * @param array $args {
 *     Optional. Arguments for the button.
 *
 *     @type int    $listing_id    Listing post ID. Default current post in the loop.
 *     @type int    $service_id    Override the auto-resolved service ID. Default 0 (auto).
 *     @type mixed  $employee_id   Override the auto-resolved employee ID. Default '' (auto).
 *     @type string $text          Button label. Default the listing's configured text.
 *     @type string $class         Extra CSS classes for the <button>. Default ''.
 *     @type string $wrapper_class Extra CSS classes for the wrapper <div>. Default ''.
 *     @type string $style         Inline style for the <button>. Pass '' to drop the
 *                                  default styling (e.g. when theming via $class).
 *     @type bool   $echo          Whether to echo the markup. Default false.
 * }
 *
 * @return string Button HTML, or '' when the listing is not bookable.
 * @since 1.0.0
 */
function rtrb_cl_get_booking_button( $args = array() ) {
	if ( ! function_exists( 'rtcl' ) ) {
		return '';
	}
    $settings    = SettingsHelper::get_setting( 'integrations' );
    $cl_settings = $settings['classifiedListing'] ?? array();

    if ( empty( $cl_settings['enabled'] ) ) {
        return '';
    }

	$default_style = '';
//	$default_style = 'width:100%;padding:12px 24px;background-color:#0040ff;color:#fff;border:none;border-radius:6px;font-size:16px;font-weight:600;cursor:pointer;';

	$defaults = array(
		'listing_id'    => get_the_ID(),
		'service_id'    => 0,
		'employee_id'   => '',
		'flow'          => '',
		'text'          => '',
		'class'         => '',
		'wrapper_class' => '',
		'style'         => $default_style,
		'echo'          => false,
	);

	$args = wp_parse_args( $args, $defaults );
	/**
	 * Filter the resolved button arguments before rendering.
	 *
	 * @param array $args Button arguments.
	 */
	$args = apply_filters( 'rtrb_cl_booking_button_args', $args );

	$listing_id = (int) $args['listing_id'];
	if ( ! $listing_id ) {
		return '';
	}

	$data = \RadiusTheme\RadiusBooking\Integrations\ClassifiedListing\ListingFrontendHooks::resolveBookingData( $listing_id );
	if ( ! $data ) {
		return '';
	}

	// Lazily pull in the React booking bundle + modal controller so the button
	// works even on custom pages/loops that the automatic asset detection in
	// LoadAssets::enqueue_site_assets() does not cover. Idempotent, and since
	// these are footer scripts a late enqueue (during the loop) still prints.
	if ( function_exists( 'radius_booking' ) && isset( radius_booking()->assets ) ) {
		radius_booking()->assets->enqueue_site_bundle();
	}

	// Use the resolved data's service_id when the caller did not override it.
	// resolveBookingData() may return an empty string for service_id in staff
	// mode when the staff offers multiple services — empty means "no
	// pre-selection" so the service chooser stays visible.
	if ( $args['service_id'] ) {
		$service_id = (int) $args['service_id'];
	} elseif ( array_key_exists( 'service_id', $data ) ) {
		$service_id = $data['service_id'];
	} else {
		$service_id = (int) $data['service']->id;
	}
	$employee_id = ( '' !== $args['employee_id'] ) ? $args['employee_id'] : $data['employee_id'];
	$text        = ( '' !== $args['text'] ) ? $args['text'] : $data['button_text'];
	$flow        = ( '' !== $args['flow'] ) ? $args['flow'] : ( $data['flow'] ?? 'service_first' );

	$btn_class  = trim( 'rtrb-cl-book-now btn btn-primary ' . $args['class'] );
	$wrap_class = trim( 'rtrb-cl-book-now-wrapper ' . $args['wrapper_class'] );

	ob_start();
	?>
	<div class="<?php echo esc_attr( $wrap_class ); ?>" style="margin-top:15px;margin-bottom:15px;">
		<button type="button" class="<?php echo esc_attr( $btn_class ); ?>"
			data-listing-id="<?php echo esc_attr( $listing_id ); ?>"
			data-service-id="<?php echo esc_attr( $service_id ); ?>"
			data-employee-id="<?php echo esc_attr( $employee_id ); ?>"
			data-flow="<?php echo esc_attr( $flow ); ?>"
			<?php if ( '' !== $args['style'] ) : ?>style="<?php echo esc_attr( $args['style'] ); ?>"<?php endif; ?>>
			<?php echo esc_html( $text ); ?>
		</button>
	</div>
	<?php
	$html = ob_get_clean();

	/**
	 * Filter the final button HTML.
	 *
	 * @param string $html Button markup.
	 * @param array  $args Resolved button arguments.
	 * @param array  $data Resolved booking data (service, employee_id, etc.).
	 */
	$html = apply_filters( 'rtrb_cl_booking_button_html', $html, $args, $data );

	// Flag the shared modal shell to render in wp_footer.
	rtrb_cl_booking_modal_needed( true );

	if ( $args['echo'] ) {
		echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- built/escaped above.
	}

	return $html;
}

/**
 * Echo the Classified Listing "Book Now" button.
 *
 * Convenience wrapper around {@see rtrb_cl_get_booking_button()}.
 *
 * @param array $args See rtrb_cl_get_booking_button() for accepted arguments.
 *
 * @return void
 * @since 1.0.0
 */
function rtrb_cl_booking_button( $args = array() ) {
	$args['echo'] = true;
	rtrb_cl_get_booking_button( $args );
}

/**
 * Get the current page URL.
 *
 * @return string Current page URL.
 * @since 1.0.0
 */
function radius_booking_get_current_url() {
	global $wp;

	return home_url( add_query_arg( array(), $wp->request ) );
}


/**
 * Check if marketing consent checkbox should be displayed.
 *
 * @return bool True if marketing consent is enabled, false otherwise.
 * @since 1.0.0
 */
function radius_booking_is_marketing_consent_enabled() {
	return (bool) get_option( 'radius_booking_show_marketing_consent', false );
}

/**
 * Get the terms and conditions page URL.
 *
 * @return string Terms page URL or empty string if not set.
 * @since 1.0.0
 */
function radius_booking_get_terms_page_url() {
	$terms_page_id = get_option( 'radius_booking_terms_page_id', 0 );

	if ( ! $terms_page_id ) {
		return '';
	}

	return get_permalink( $terms_page_id );
}