<?php
/**
 * Integrations settings page.
 *
 * @package FoodOrd
 */

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

/**
 * Class Foodord_Integrations
 */
class Foodord_Integrations
{
	/**
	 * Initialize hooks.
	 */
	public function init()
	{
		add_action('admin_init', array($this, 'register_settings'));
		add_action('admin_post_foodord_save_integrations', array($this, 'handle_save'));
	}

	/**
	 * Register integration settings.
	 */
	public function register_settings()
	{
		register_setting(
			'foodord_integration_settings',
			'foodord_google_client_id',
			array(
				'type' => 'string',
				'sanitize_callback' => 'sanitize_text_field',
				'default' => '',
			)
		);

		register_setting(
			'foodord_integration_settings',
			'foodord_google_client_secret',
			array(
				'type' => 'string',
				'sanitize_callback' => 'sanitize_text_field',
				'default' => '',
			)
		);
	}

	/**
	 * Render the Integrations page.
	 */
	public static function render_page()
	{
		if (!current_user_can('manage_options')) {
			wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'foodord'));
		}

		$client_id = get_option('foodord_google_client_id', '');
		$client_secret = get_option('foodord_google_client_secret', '');
		$callback_url = home_url('/?foodord_auth=google');
		$success_flag = filter_input(INPUT_GET, 'success', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

		?>
		<div class="wrap foodord-settings-wrap">
			<h1 class="foodord-integrations__title"><?php echo esc_html__('Integrations', 'foodord'); ?></h1>

			<?php if ('1' === $success_flag): ?>
				<div class="notice notice-success is-dismissible">
					<p class="foodord-integrations__notice-text">
						<?php echo esc_html__('Settings saved successfully.', 'foodord'); ?>
					</p>
				</div>
			<?php endif; ?>

			<p class="foodord-integrations__intro">
				<?php echo esc_html__('Enable customers to sign in with their Google account by configuring Google OAuth credentials.', 'foodord'); ?>
			</p>
			<?php
			if (function_exists('foodord_admin_render_horizontal_menu')) {
				foodord_admin_render_horizontal_menu();
			}
			?>

			<div class="card foodord-integrations-card">
				<h2 class="title"><?php echo esc_html__('Google Login Configuration', 'foodord'); ?></h2>

				<div class="foodord-google-config-box">
					<h3 class="foodord-google-config-title">
						<?php echo esc_html__('How to get your Google API Keys:', 'foodord'); ?>
					</h3>
					<ol class="foodord-google-steps">
						<li>
							<?php
							$console_anchor = sprintf(
								'<a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s</a>',
								esc_url('https://console.cloud.google.com/'),
								esc_html__('Google Cloud Console', 'foodord')
							);
							echo wp_kses(
								sprintf(
									/* translators: %s: Google Cloud Console anchor tag. */
									__('Go to the %s.', 'foodord'),
									$console_anchor
								),
								array(
									'a' => array(
										'href' => array(),
										'target' => array(),
										'rel' => array(),
									),
								)
							);
							?>
						</li>
						<li><?php echo esc_html__('Create a new project or select an existing one.', 'foodord'); ?></li>
						<li><?php echo esc_html__('Navigate to "APIs & Services" > "Credentials".', 'foodord'); ?></li>
						<li><?php echo esc_html__('Click "Create Credentials" and select "OAuth client ID".', 'foodord'); ?>
						</li>
						<li><?php echo esc_html__('Select "Web application" as the application type.', 'foodord'); ?></li>
						<li><?php echo esc_html__('In the "Authorized redirect URIs" field, paste the URL shown below.', 'foodord'); ?>
						</li>
						<li><?php echo esc_html__('Click "Create" and copy your Client ID and Client Secret.', 'foodord'); ?>
						</li>
					</ol>
				</div>

				<form class="foodord-integrations__form" method="post"
					action="<?php echo esc_url(admin_url('admin-post.php')); ?>" autocomplete="off">
					<input class="foodord-integrations__hidden-input" type="hidden" name="action"
						value="foodord_save_integrations" />
					<?php wp_nonce_field('foodord_integrations_nonce', 'foodord_integrations_nonce'); ?>

					<div class="foodord-integrations__honeypot">
						<input class="foodord-integrations__honeypot-input" type="text" name="foodord_fake_user" tabindex="-1"
							aria-hidden="true" />
						<input class="foodord-integrations__honeypot-input" type="password" name="foodord_fake_pass"
							tabindex="-1" aria-hidden="true" />
					</div>

					<table class="form-table">
						<tr>
							<th scope="row">
								<label class="foodord-integrations__label"
									for="foodord_google_client_id"><?php echo esc_html__('Client ID', 'foodord'); ?></label>
							</th>
							<td>
								<input type="text" name="foodord_google_client_id" id="foodord_google_client_id"
									value="<?php echo esc_attr($client_id); ?>" class="regular-text"
									placeholder="<?php echo esc_attr__('Example: 123456789-abc.apps.googleusercontent.com', 'foodord'); ?>"
									autocomplete="off" />
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label class="foodord-integrations__label"
									for="foodord_google_client_secret"><?php echo esc_html__('Client Secret', 'foodord'); ?></label>
							</th>
							<td>
								<input type="password" name="foodord_google_client_secret" id="foodord_google_client_secret"
									value="<?php echo esc_attr($client_secret); ?>" class="regular-text"
									autocomplete="new-password" />
							</td>
						</tr>
						<tr>
							<th scope="row">
								<span
									class="foodord-integrations__label-text"><?php echo esc_html__('Authorized Redirect URI', 'foodord'); ?></span>
							</th>
							<td>
								<code><?php echo esc_html($callback_url); ?></code>
								<p class="description">
									<?php echo esc_html__('Copy this URL and paste it into the "Authorized redirect URIs" field in your Google Cloud Console.', 'foodord'); ?>
								</p>
							</td>
						</tr>
					</table>

					<p class="submit">
						<button type="submit"
							class="button button-primary"><?php echo esc_html__('Save Changes', 'foodord'); ?></button>
					</p>
				</form>
			</div>
		</div>
		<?php
	}

	/**
	 * Handle form save.
	 */
	public function handle_save()
	{
		if (!current_user_can('manage_options')) {
			wp_die(esc_html__('Insufficient permissions', 'foodord'));
		}

		check_admin_referer('foodord_integrations_nonce', 'foodord_integrations_nonce');

		if (isset($_POST['foodord_google_client_id'])) {
			update_option('foodord_google_client_id', sanitize_text_field(wp_unslash($_POST['foodord_google_client_id'])));
		}

		if (isset($_POST['foodord_google_client_secret'])) {
			update_option('foodord_google_client_secret', sanitize_text_field(wp_unslash($_POST['foodord_google_client_secret'])));
		}

		$page_slug = function_exists('foodord_get_settings_page_slug') ? foodord_get_settings_page_slug('integrations') : 'foodord-integrations';
		wp_safe_redirect(add_query_arg('success', 1, admin_url('admin.php?page=' . $page_slug)));
		exit;
	}
}
