<?php

namespace SugarCalendarBookings\Admin\Settings;

use SugarCalendarBookings\Integrations\ExternalBusyTimes\ExternalBusyTimeModel;
use SugarCalendarBookings\Integrations\IntegrationRegistry;
use SugarCalendarBookings\Integrations\OAuthRelay\OAuthConnectionModel;
use SugarCalendarBookings\Integrations\OAuthRelay\OAuthRelayClient;
use SugarCalendarBookings\Options;
use SugarCalendarBookings\Plugin;
use SugarCalendarBookings\Support\Admin\AbstractTabPage;
use SugarCalendarBookings\Support\Admin\Notices;
use SugarCalendarBookings\Support\Helpers\UI;

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

/**
 * Misc Settings tab.
 *
 * @since 1.4.0
 */
class MiscSettingsTab extends AbstractTabPage {

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

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

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

		return 'settings';
	}

	/**
	 * Page view slug.
	 *
	 * @since 1.4.0
	 *
	 * @return string
	 */
	public static function get_view_slug() {

		return 'misc';
	}

	/**
	 * Priority in menu position.
	 *
	 * @since 1.4.0
	 *
	 * @return int
	 */
	public static function get_priority() {

		return 60;
	}

	/**
	 * Display page content.
	 *
	 * @since 1.4.0
	 */
	public function display_content() {

		ob_start();

		UI::heading(
			[
				'title' => esc_html__( 'Miscellaneous', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			]
		);

		foreach ( $this->get_controls() as $control ) {
			UI::toggle_control( $control );
		}

		UI::form_wrapper( ob_get_clean() );

		UI::confirmation_modal();
	}

	/**
	 * Get toggle controls for the Misc settings tab.
	 *
	 * @since 1.4.0
	 *
	 * @return array
	 */
	protected function get_controls(): array {

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

		return [
			'disable_integrations'     => [
				'id'          => 'misc_disable_integrations',
				'name'        => [ 'misc', 'disable_integrations' ],
				'value'       => $options->get( 'misc.disable_integrations' ),
				'label'       => esc_html__( 'Disable Integrations', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				'description' => esc_html__( 'Disconnect and disable all external integrations and usage tracking for Sugar Calendar Bookings.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			],
			'hide_announcements'       => [
				'id'          => 'misc_hide_announcements',
				'name'        => [ 'misc', 'hide_announcements' ],
				'value'       => $options->get( 'misc.hide_announcements' ),
				'label'       => esc_html__( 'Hide Announcements', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				'description' => esc_html__( 'Hide plugin announcements and update details.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			],
			'delete_data_on_uninstall' => [
				'id'                  => 'misc_delete_data_on_uninstall',
				'name'                => [ 'misc', 'delete_data_on_uninstall' ],
				'value'               => $options->get( 'misc.delete_data_on_uninstall' ),
				'label'               => esc_html__( 'Uninstall Cleanup', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				'description'         => esc_html__( 'Remove ALL Sugar Calendar Bookings data upon plugin deletion.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				'description_warning' => esc_html__( 'All appointments and settings will be unrecoverable.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			],
		];
	}

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

		return [
			'misc.disable_integrations'     => 'form_boolean',
			'misc.hide_announcements'       => 'form_boolean',
			'misc.delete_data_on_uninstall' => 'form_boolean',
		];
	}

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

		$options      = Plugin::get( Options::class );
		$was_disabled = (bool) $options->get( 'misc.disable_integrations' );
		$now_disabled = ! empty( $post_data['misc']['disable_integrations'] );

		$options->update( $post_data );

		// If integrations just got disabled, clean up all connections.
		if ( ! $was_disabled && $now_disabled ) {
			$this->cleanup_integrations( $options );
		}

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

	/**
	 * Remove all integration connections and related data.
	 *
	 * @since 1.4.0
	 *
	 * @param Options $options Options instance.
	 */
	private function cleanup_integrations( Options $options ): void {

		$relay       = Plugin::get( OAuthRelayClient::class );
		$connections = OAuthConnectionModel::query()->get();

		foreach ( $connections as $connection ) {

			// Unregister webhook from the Product API relay.
			$relay->unregister_webhook( $connection->provider, $connection->account_id );

			// Delete associated external busy times.
			ExternalBusyTimeModel::query()
				->where( 'oauth_connection_id', '=', $connection->id, '%d' )
				->delete();

			$connection->delete();
		}

		// Reset all per-provider enabled flags.
		$registry = Plugin::get( IntegrationRegistry::class );
		$disabled = [];

		foreach ( $registry->get_all() as $integration ) {
			$disabled[ $integration->get_slug() ] = [ 'enabled' => false ];
		}

		$options->update( [ 'integrations' => $disabled ] );
	}
}
