<?php

namespace SugarCalendarBookings\Admin\Settings;

use SugarCalendarBookings\Support\Helpers\UI;
use SugarCalendarBookings\Plugin;
use SugarCalendarBookings\Options;
use SugarCalendarBookings\Notifications\Emails\EmailDefaults;
use SugarCalendarBookings\Notifications\Emails\EmailService;
use SugarCalendarBookings\Support\Admin\AbstractPage;
use SugarCalendarBookings\Support\Admin\Notices;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Email Edit page.
 *
 * @since 1.0.0
 */
class EmailEditPage extends AbstractPage {

	/**
	 * Current email type being edited.
	 *
	 * @since 1.0.0
	 *
	 * @var string|null
	 */
	private $email_type;

	/**
	 * Email configuration data.
	 *
	 * @since 1.0.0
	 *
	 * @var array
	 */
	private $email_data;

	/**
	 * Page title.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public static function get_title() {

		return esc_html__( 'Edit Email', 'sugar-calendar-bookings-scheduling-appointments-lite' );
	}

	/**
	 * Page slug.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public static function get_slug() {

		return 'settings';
	}

	/**
	 * View slug.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public static function get_view_slug() {

		return 'edit-email';
	}

	/**
	 * Menu slug for navigation highlighting.
	 *
	 * Returns 'emails' to highlight the Emails tab when editing an email.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public static function get_menu_slug() {

		return 'emails';
	}

	/**
	 * Hooks.
	 *
	 * @since 1.0.0
	 */
	public function hooks() {

		add_action( 'admin_init', [ $this, 'init' ], 0 );
		add_action( 'current_screen', [ $this, 'load_email_data' ], 5 );
		add_filter( 'screen_options_show_screen', '__return_false' );
	}

	/**
	 * Initialize page properties.
	 *
	 * @since 1.0.0
	 *
	 * @return void
	 */
	public function init() {

		// phpcs:disable WordPress.Security.NonceVerification.Recommended
		if ( ! isset( $_GET['email_type'] ) ) {
			wp_die( esc_html__( 'Invalid email type.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		$email_type          = sanitize_key( $_GET['email_type'] );
		$email_notifications = Plugin::get( EmailService::class )->get_email_notifications();

		if ( ! isset( $email_notifications[ $email_type ] ) ) {
			wp_die( esc_html__( 'Unrecognised email type.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		$this->email_type = $email_type;
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
	}

	/**
	 * Load email data.
	 *
	 * @since 1.0.0
	 */
	public function load_email_data() {

		$options = Plugin::get( Options::class );

		// Get defaults first.
		$defaults           = EmailDefaults::to_array();
		$default_email_data = $defaults[ $this->email_type ] ?? [];
		$saved_email_data   = $options->get( "emails.{$this->email_type}", [] );
		$this->email_data   = array_merge( $default_email_data, $saved_email_data );
	}

	/**
	 * Display subheader actions left.
	 *
	 * @since 1.0.0
	 */
	public function display_subheader_actions_left() {

		UI::button(
			[
				'text'  => esc_html__( 'Back to Emails', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				'class' => 'sugar-calendar-bookings-back-to',
				'size'  => 'sm',
				'link'  => EmailsSettingsTab::get_url(),
			]
		);
	}

	/**
	 * Get email type title.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	private function get_email_title() {

		$email_notifications = Plugin::get( EmailService::class )->get_email_notifications();

		return $email_notifications[ $this->email_type ]['label'] ?? esc_html__( 'Email Settings', 'sugar-calendar-bookings-scheduling-appointments-lite' );
	}

	/**
	 * Display page content.
	 *
	 * @since 1.0.0
	 * @since 1.4.0 Added reset-to-default button and confirmation modal.
	 */
	public function display_content() {

		$this->display_subheader_actions_left();

		if ( empty( $this->email_type ) || empty( $this->email_data ) ) {
			echo '<p>' . esc_html__( 'Invalid email type.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) . '</p>';

			return;
		}

		ob_start();

		UI::heading(
			[
				'title' => $this->get_email_title(),
			]
		);

		// Status Toggle.
		UI::toggle_control(
			[
				'id'    => "emails_{$this->email_type}_enabled",
				'name'  => [ 'emails', $this->email_type, 'enabled' ],
				'value' => $this->email_data['enabled'] ?? true,
				'label' => esc_html__( 'Status', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			]
		);

		// Email Subject.
		UI::text_input(
			[
				'id'          => "emails_{$this->email_type}_subject",
				'name'        => [ 'emails', $this->email_type, 'subject' ],
				'value'       => $this->email_data['subject'] ?? '',
				'label'       => esc_html__( 'Email Subject', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				'description' => esc_html__( 'The subject line for this email notification.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				'required'    => true,
			]
		);

		// Email Message.
		UI::wysiwyg_editor(
			[
				'id'            => "emails_{$this->email_type}_content",
				'name'          => [ 'emails', $this->email_type, 'content' ],
				'value'         => $this->email_data['content'] ?? '',
				'label'         => esc_html__( 'Email Message', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				'rows'          => 15,
				'media_buttons' => true,
				'teeny'         => false,
				'quicktags'     => true,
				'smart_tags'    => Plugin::get( EmailService::class )->get_email_smart_tags(),
			]
		);

		UI::form_wrapper( ob_get_clean() );

		// Reset to Default button — JS will relocate into the form's submit area.
		?>
		<div id="sugar-calendar-bookings-reset-email-defaults-wrap" style="display:none;">
			<?php
			UI::button(
				[
					'id'     => 'sugar-calendar-bookings-reset-email-btn',
					'text'   => esc_html__( 'Reset to Default', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					'type'   => 'danger',
					'submit' => false,
				]
			);
			?>
		</div>
		<?php

		UI::confirmation_modal();
	}

	/**
	 * Get post data processing rules.
	 *
	 * @since 1.0.0
	 *
	 * @return array
	 */
	public function get_post_data_processing_rules() {

		return [
			"emails.{$this->email_type}.enabled" => 'required|form_boolean',
			"emails.{$this->email_type}.subject" => 'required|string|max:255',
			"emails.{$this->email_type}.content" => 'required|html',
		];
	}

	/**
	 * Handle POST requests.
	 *
	 * @since 1.0.0
	 *
	 * @param array $post_data Post data.
	 */
	public function handle_post( $post_data = [] ) {

		Plugin::get( Options::class )->update( $post_data );

		Plugin::get( Notices::class )->success( __( 'Settings successfully saved.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
	}

	/**
	 * Get page-specific script data.
	 *
	 * @since 1.4.0
	 *
	 * @return array
	 */
	public function get_script_data() {

		return [
			'email_type' => $this->email_type,
		];
	}
}
