<?php
/**
 * RadiusBooking API Route Registrar
 *
 * This class is responsible for registering API routes dynamically with the WordPress REST API.
 * It supports CRUD operations and allows for middleware to be applied globally or per route.
 *
 * @package RadiusTheme\RadiusBooking\Core\Api\Routes
 */

namespace RadiusTheme\RadiusBooking\Hooks;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}
use DateTime;
use DateTimeZone;
use RadiusTheme\RadiusBooking\Integrations\GoogleCalendarMeetIntegration;
use RadiusTheme\RadiusBooking\Models\AppointmentIntegration;

/**
 * Class Common
 *
 * @package RadiusTheme\PluginName\Hooks
 *
 * @since 1.0.0
 */
class Common {


	/**
	 * Constructor method initializes the class by registering roles
	 * and adding an action to hide notices on the booking page.
	 *
	 * @return void
	 */
	public function __construct() {
		$this->register_role();
		add_action( 'admin_head', array( $this, 'hide_notice_booking_page' ), 1 );
		add_filter( 'display_post_states', array( $this, 'add_booking_page_states' ), 10, 2 );
		add_filter( 'body_class', [ $this, 'add_booking_page_class' ] );
		add_filter( 'rtrb_my_booking_item_data', array( $this, 'inject_meeting_link' ) );
	}

	/**
	 * Inject meeting link (Zoom / Google Meet) into each booking item
	 * for the employee and customer panels.
	 *
	 * @param object $item Appointment/booking data object.
	 *
	 * @return object
	 */
	public function inject_meeting_link( $item ) {
		$appointment_id = $item->appointment_id ?? ( $item->id ?? null );
		if ( empty( $appointment_id ) ) {
			return $item;
		}

		$integration = AppointmentIntegration::where( 'appointment_id', $appointment_id )
			->whereNotNull( 'join_url' )
			->first();

		if ( $integration ) {
			$item->meeting_link = array(
				'provider'  => $integration->provider ?? 'zoom',
				'join_url'  => $integration->join_url ?? $integration->meeting_url ?? '',
				'start_url' => $integration->start_url ?? '',
				'status'    => $integration->status ?? 'created',
			);
		}

		return $item;
	}

	/**
	 * Registers custom user roles: 'Radius Booking Employee' and 'Radius Booking Customer'.
	 * If the roles do not exist, they are added with specific capabilities.
	 *
	 * @return void
	 */
	public function register_role() {

		// Employee
		$role = get_role( 'radius_booking_employee' );
		if ( ! $role ) {
			$role = add_role(
				'radius_booking_employee',
				__( 'Radius Booking Employee', 'radius-booking' ),
				array(
					'read'         => true,
					'upload_files' => true,
				)
			);
		}

		// Ensure capabilities are correct even if role already created.
		if ( $role ) {
			if ( ! $role->has_cap( 'upload_files' ) ) {
				$role->add_cap( 'upload_files' );
			}
			// Remove explicit false caps that break multi-role users (e.g. admin + employee).
			foreach ( array( 'edit_posts', 'delete_posts' ) as $cap ) {
				if ( isset( $role->capabilities[ $cap ] ) && ! $role->capabilities[ $cap ] ) {
					$role->remove_cap( $cap );
				}
			}
		}

		// Customer
		$role = get_role( 'radius_booking_customer' );
		if ( ! $role ) {
			$role = add_role(
				'radius_booking_customer',
				__( 'Radius Booking Customer', 'radius-booking' ),
				array(
					'read'         => true,
					'upload_files' => true,
				)
			);
		}

		// Ensure capabilities are correct even if role already created.
		if ( $role ) {
			if ( ! $role->has_cap( 'upload_files' ) ) {
				$role->add_cap( 'upload_files' );
			}
			// Remove explicit false caps that break multi-role users (e.g. admin + customer).
			foreach ( array( 'edit_posts', 'delete_posts' ) as $cap ) {
				if ( isset( $role->capabilities[ $cap ] ) && ! $role->capabilities[ $cap ] ) {
					$role->remove_cap( $cap );
				}
			}
		}
	}


	/**
	 * Hides all admin notices on the Radius Booking page.
	 *
	 * @return void
	 */
	public function hide_notice_booking_page() {
		global $current_screen;
		if ( 'toplevel_page_radius-booking' === $current_screen->base ) {
			remove_all_actions( 'admin_notices' );
		}
	}

	/**
	 * Add "Radius Booking" post state labels to plugin-assigned pages.
	 *
	 * @param array    $post_states Existing post states.
	 * @param \WP_Post $post        The current post object.
	 *
	 * @return array
	 */
	public function add_booking_page_states( $post_states, $post ) {
		$settings = \RadiusTheme\RadiusBooking\Helpers\SettingsHelper::get_setting( 'pages' );

		$page_labels = array(
			'bookingFormPage' => __( 'Radius Booking Form', 'radius-booking' ),
			'myBookingPage'   => __( 'Radius My Booking', 'radius-booking' ),
		);

		foreach ( $page_labels as $key => $label ) {
			if ( ! empty( $settings[ $key ] ) && (int) $settings[ $key ] === $post->ID ) {
				$post_states[ 'radius_booking_' . $key ] = $label;
			}
		}

		return $post_states;
	}

	/**
	 * Add Booking page class for myaccount
	 * @param $classes
	 *
	 * @return mixed
	 */
	public function add_booking_page_class($classes) {
		if (is_singular()) {
			global $post;

			if (has_shortcode($post->post_content, 'rtrb_my_booking')) {
				$classes[] = 'rtrb-account';
			}
		}

		return $classes;
	}
}
