<?php

namespace SugarCalendarBookings\Services\Admin;

use SugarCalendarBookings\Payments\PaymentsHelpers;
use SugarCalendarBookings\Plugin;
use SugarCalendarBookings\Services\CreateServiceDTO;
use SugarCalendarBookings\Services\ServiceDTO;
use SugarCalendarBookings\Services\ServiceModel;
use SugarCalendarBookings\Services\ServiceService;
use SugarCalendarBookings\Support\Ajax\AbstractController;
use SugarCalendarBookings\Support\Helpers\Time;

/**
 * Controller for Service admin actions.
 *
 * @since 1.0.0
 */
class ServiceController extends AbstractController {

	/**
	 * Handle service creation request.
	 *
	 * @since 1.0.0
	 */
	public function create() {

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'You are not allowed to create service.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		$form_service = Plugin::get( ServiceFormService::class );
		$data         = $this->get_input_data( $form_service->rules() );

		if ( empty( $data['locations'] ) && empty( $data['online_locations'] ) ) {
			wp_send_json_error( esc_html__( 'At least one location or online location is required.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		$dto     = new CreateServiceDTO( $data );
		$service = Plugin::get( ServiceService::class )->create( $dto );

		if ( ! $service ) {
			wp_send_json_error( esc_html__( 'Failed to create service.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		wp_send_json_success( $service->id );
	}

	/**
	 * Handle service update request.
	 *
	 * @since 1.0.0
	 */
	public function update() {

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'You are not allowed to update service.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		$form_service = Plugin::get( ServiceFormService::class );

		$rules = $form_service->rules(
			[
				'id' => 'required|id',
			]
		);

		$data = $this->get_input_data( $rules );

		if ( empty( $data['locations'] ) && empty( $data['online_locations'] ) ) {
			wp_send_json_error( esc_html__( 'At least one location or online location is required.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		$service = ServiceModel::get( $data['id'] );

		if ( ! $service ) {
			wp_send_json_error( esc_html__( 'Service not found.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		$dto     = new ServiceDTO( $data );
		$service = Plugin::get( ServiceService::class )->update( $service, $dto );

		if ( ! $service ) {
			wp_send_json_error( esc_html__( 'Failed to update service.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		wp_send_json_success( $service->id );
	}

	/**
	 * Handle service deletion request.
	 *
	 * @since 1.0.0
	 */
	public function delete() {

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'You are not allowed to delete service.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		$rules = [
			'id' => 'required|id',
		];

		$data    = $this->get_input_data( $rules );
		$service = ServiceModel::get( $data['id'] );

		if ( ! $service ) {
			wp_send_json_error( esc_html__( 'Service not found.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		$deleted = Plugin::get( ServiceService::class )->delete( $service );

		if ( ! $deleted ) {
			wp_send_json_error( esc_html__( 'Failed to delete service.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		wp_send_json_success( $service->id );
	}

	/**
	 * Get data for service creation form.
	 *
	 * @since 1.0.0
	 */
	public function get_create_form_data() {

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'You are not allowed to create service.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		$data = Plugin::get( ServiceFormService::class )->get_create_form_data();

		wp_send_json_success( $data );
	}

	/**
	 * Get data for service edit form.
	 *
	 * @since 1.0.0
	 */
	public function get_edit_form_data() {

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'You are not allowed to edit service.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		$rules = [
			'id' => 'required|id',
		];

		$data    = $this->get_input_data( $rules );
		$service = ServiceModel::get( $data['id'] );

		if ( ! $service ) {
			wp_send_json_error( esc_html__( 'Service not found.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		$data = Plugin::get( ServiceFormService::class )->get_edit_form_data( $service );

		wp_send_json_success( $data );
	}

	/**
	 * Return share-sidebar payload for a service.
	 *
	 * Assembles title, price, duration, feature image, and color for the
	 * Share sidebar header. Pro extends the payload via build_share_data().
	 *
	 * @since 1.5.0
	 *
	 * @return void
	 */
	public function get_share_data() {

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'You are not allowed to share service.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );

			return;
		}

		$rules = [
			'id' => 'required|id',
		];

		$data    = $this->get_input_data( $rules );
		$service = $this->get_share_service( (int) $data['id'] );

		if ( ! $service ) {
			wp_send_json_error( esc_html__( 'Service not found.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );

			return;
		}

		if ( $service->status !== 'enabled' ) {
			wp_send_json_error( esc_html__( 'Service is not enabled.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );

			return;
		}

		wp_send_json_success( $this->build_share_data( $service ) );
	}

	/**
	 * Fetch the service model used by the Share sidebar.
	 *
	 * Pro overrides this to return ProServiceModel so build_share_data() can
	 * read Pro-only meta keys (e.g. page_background) without an instanceof guard.
	 *
	 * @since 1.5.0
	 *
	 * @param int $id Service ID.
	 *
	 * @return ServiceModel|null
	 */
	protected function get_share_service( int $id ): ?ServiceModel {

		return ServiceModel::get( $id );
	}

	/**
	 * Build the share-sidebar payload for a service.
	 *
	 * Returns the always-available fields shown in the Share sidebar header.
	 * Pro overrides this to add `service_url` and `page_background`.
	 *
	 * @since 1.5.0
	 *
	 * @param ServiceModel $service Service model instance.
	 *
	 * @return array
	 */
	protected function build_share_data( ServiceModel $service ): array {

		$feature_image_id   = $service->feature_image_id;
		$feature_image_url  = null;
		$feature_image_name = null;

		if ( $feature_image_id ) {
			$feature_image      = wp_get_attachment_image_src( $feature_image_id, 'medium' );
			$feature_image_url  = is_array( $feature_image ) ? ( $feature_image[0] ?? null ) : null;
			$feature_image_name = is_array( $feature_image ) ? get_the_title( $feature_image_id ) : null;
		}

		return [
			'id'                 => $service->id,
			'title'              => $service->name,
			'formatted_price'    => html_entity_decode( PaymentsHelpers::format_currency( $service->price ) ),
			'formatted_duration' => Time::human_readable_duration( $service->duration ),
			'feature_image_url'  => $feature_image_url,
			'feature_image_name' => $feature_image_name,
			'color'              => $service->color,
		];
	}
}
