<?php
/**
 * Template for key renewal process.
 *
 * @package Postomatic
 * @subpackage Admin
 */

namespace Postomatic\Admin;

use Postomatic\Core\Activator;

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

// manual session reset.
if (
	( isset( $_GET['session'] ) && 'reset' === $_GET['session'] ) || ( isset( $_GET['session'] ) && ! isset( $_GET['try'] ) )
) {
	$transient_key = 'postomatic_tries_' . get_current_user_id();
	delete_transient( $transient_key ); // Delete the transient to reset tries.

	?>
	<script>
	setTimeout(function() {
		// A nonce is required by the key=refresh branch below, so it has to be
		// included here; without it the redirect landed on a page that quietly
		// did nothing.
		window.location.href = "<?php echo esc_url_raw( add_query_arg( array( 'page' => \Postomatic\Constants::PAGE_MAIN, 'key' => 'refresh', 'try' => 0, '_wpnonce' => wp_create_nonce( 'postomatic_admin_nonce' ) ), admin_url( 'admin.php' ) ) ); ?>";
	}, 1500);
	</script>
	<?php
}

// Delay page to receive data from api.
if ( isset( $_GET['key'] ) && 'refresh' === $_GET['key'] && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'postomatic_admin_nonce' ) ) {

	/*
	 * refresh_api_key() returns as soon as the service's callback has stored the
	 * new key, so in the normal case the handshake is already finished by the
	 * time this page renders and the redirect below only needs a moment's grace.
	 * Activator::activate() was used here before, which additionally re-ran the
	 * table migration and re-armed the activation redirect on every retry.
	 */
	$key_refreshed = Activator::refresh_api_key();

	/*
	 * Rebuild the current URL without the key/_wpnonce parameters.
	 *
	 * The previous version called wp_parse_url( $url, PHP_URL_QUERY, $params ),
	 * which takes only two arguments — the third was ignored, $query_params was
	 * always empty, and every other query parameter on the page (the page slug
	 * included) was dropped by the strtok() below. The page slug then had to be
	 * re-appended by hand further down, which is why the redirect could not
	 * return the user to the page they came from.
	 */
	$page_slug = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : \Postomatic\Constants::PAGE_MAIN;
	$query     = $_GET; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- nonce verified above.
	unset( $query['key'], $query['_wpnonce'], $query['session'] );
	$query['page'] = $page_slug;

	// Use WordPress transients instead of sessions.
	$transient_key = 'postomatic_tries_' . get_current_user_id();
	$tries         = (int) get_transient( $transient_key ) + 1;

	set_transient( $transient_key, $tries, 2 * MINUTE_IN_SECONDS );

	$query['try'] = $tries;
	$new_url      = add_query_arg( array_map( 'sanitize_text_field', array_map( 'strval', $query ) ), admin_url( 'admin.php' ) );

	/*
	 * The key is already in place, so there is nothing left to wait for: send
	 * the user straight back instead of showing the spinner. Only a failed
	 * handshake falls through to the retry screen below.
	 */
	if ( $key_refreshed ) {
		delete_transient( $transient_key );
		wp_safe_redirect( $new_url );
		exit();
	}

	// Three attempts rather than five: each one is now a real handshake with a
	// bounded wait, so five rounds only prolonged a failure the user cannot fix.
	if ( $tries > 3 ) {
		?>
		<div class="postomatic-error-message">
			<h3>API Key Renewal Error</h3>
			<p>We apologize, but there was an issue renewing your API key. Please try again later or contact our support
				team for assistance.</p>
			<p class="postomatic-support-link">
				<a href="admin.php?page=<?php echo esc_html( \Postomatic\Constants::PAGE_SUPPORT ); ?>" class="button button-primary">
					<span class="dashicons dashicons-admin-users"></span> Contact Support
				</a>
			</p>
		</div>
		<style>
			.postomatic-error-message {
				background: #fff;
				border-left: 4px solid #dc3232;
				box-shadow: 0 1px 1px rgba(0, 0, 0, .04);
				margin: 20px 0;
				padding: 12px 20px;
			}

			.postomatic-error-message h3 {
				margin: 0 0 10px;
				font-size: 16px;
				line-height: 1.4;
				color: #23282d;
			}

			.postomatic-error-message p {
				margin: 0 0 10px;
				color: #646970;
				font-size: 14px;
				line-height: 1.5;
			}

			.postomatic-support-link {
				margin-top: 15px !important;
			}

			.postomatic-support-link .button {
				display: inline-flex;
				align-items: center;
				gap: 5px;
			}
		</style>
		<?php
		exit();
	}
	?>


	<h2>Renewing Your <span class="postomatic-brand">Postomatic</span> API Key</h2>
	<p>Thank you for using <span class="postomatic-brand">Postomatic</span>. We're currently processing your key renewal
		request. This will only take a
		moment.</p>
	<div class="postomatic-loader"></div>
	<style>
		h2 {
			font-size: 28px;
			color: #23282d;
			font-weight: 600;
			margin-bottom: 1em;
			font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
		}

		p {
			font-size: 16px;
			color: #50575e;
			line-height: 1.5;
			margin-bottom: 2em;
		}

		.postomatic-brand {
			color: #0073aa;
			font-weight: 700;
			letter-spacing: 0.5px;
		}

		.postomatic-loader {
			border: 4px solid #f3f3f3;
			border-radius: 50%;
			border-top: 4px solid #0073aa;
			width: 40px;
			height: 40px;
			animation: spin 1s linear infinite;
		}

		@keyframes spin {
			0% {
				transform: rotate(0deg);
			}
			100% {
				transform: rotate(360deg);
			}
		}
	</style>
	<script>
		setTimeout(function() {
			// $new_url already carries the page slug, the try counter and every
			// other query parameter, so nothing is appended here. The previous
			// version concatenated "?page=…" onto a URL that had already lost
			// its own parameters.
			window.location.href = "<?php echo esc_url( $new_url ); ?>";
		}, 1500); // Short grace period; the handshake itself has already been waited for.
	</script>
	<?php

	exit();
}
