<?php
/**
 * Template for user agreement signing.
 *
 * This file handles the agreement form display and submission processing.
 *
 * @package  Postomatic
 * @category Admin
 * @since    1.0.0
 * @license  https://www.gnu.org/licenses/gpl-2.0.html GPL-2.0-or-later
 * @link     https://example.com/postomatic
 */

namespace Postomatic\Admin;

use Postomatic\Constants;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Check if nonce exists and is valid.
if ( isset( $_GET['key'] ) && 'agreement' === $_GET['key']
						&& isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'postomatic_agreement_access' )
) {
	// Create nonce for form submission.
	$nonce = wp_create_nonce( 'postomatic_agreement_nonce' );

	// Check if REQUEST_URI is set and properly unslash before sanitizing.
	$current_url = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_url( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
	$parsed_url  = wp_parse_url( $current_url, PHP_URL_QUERY );
	parse_str( $parsed_url, $query_params );
	unset( $query_params['key'], $query_params['_wpnonce'] );

	$new_url = strtok( $current_url, '?' ) .
	( count( $query_params ) ? '?' .
	http_build_query( $query_params ) : '' );
	?>
<!DOCTYPE html>
<html>
<head>
	<style>
		.agreement-container {
			max-width: 800px;
			margin: 2rem auto;
			padding: 2rem;
			background: white;
			box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
			border-radius: 8px;
			font-family: 'Segoe UI', Arial, sans-serif;
			color: #2d3748;
		}

		.agreement-header {
			text-align: center;
			padding-bottom: 1.5rem;
			border-bottom: 2px solid #e2e8f0;
			margin-bottom: 1.5rem;
		}

		.agreement-header h1 {
			color: #2d3748;
			font-size: 2.25rem;
			margin-bottom: 1rem;
		}

		.agreement-iframe {
			width: 100%;
			height: 400px;
			border: 1px solid #e2e8f0;
			border-radius: 4px;
			margin: 1rem 0;
			background: #f8fafc;
		}

		.agreement-footer {
			margin-top: 2rem;
			padding-top: 2rem;
			border-top: 2px solid #e2e8f0;
		}

		.checkbox-container {
			display: flex;
			align-items: center;
			margin: 2rem 0;
			padding: 1rem;
			background: #f7fafc;
			border-radius: 6px;
		}

		.checkbox-container input[type="checkbox"] {
			width: 20px;
			height: 20px;
			margin-right: 1rem;
			cursor: pointer;
		}

		.checkbox-container label {
			font-size: 1rem;
			color: #4a5568;
			cursor: pointer;
		}

		.agreement-button {
			display: block;
			width: 200px;
			margin: 2rem auto;
			padding: 1rem 2rem;
			background: #4299e1;
			color: white;
			text-align: center;
			text-decoration: none;
			border-radius: 6px;
			font-weight: 600;
			transition: background 0.3s ease;
			cursor: pointer;
			opacity: 0.5;
			pointer-events: none;
		}

		.active {
			opacity: 1;
			pointer-events: auto;
		}

		.active:hover {
			background: #3182ce;
		}

		.last-updated {
			text-align: center;
			color: #718096;
			font-size: 0.875rem;
			margin-top: 2rem;
		}

		button#agree_btn {
			background-color: #2979FF; /* Modern blue */
			color: #FFFFFF; /* White text */
			font-size: 16px;
			font-family: Roboto, Arial, sans-serif; /* Modern font */
			padding: 16px 40px; /* Increased padding */
			border: none; /* Removed default border */
			border-radius: 6px; /* rounded corners*/
			box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* Subtle shadow */
			cursor: pointer;
			transition: background-color 0.3s, box-shadow 0.3s;
		}

		.agreement-footer.ai-style-change-2 {
			display: flex;
			justify-content: center; /* Center the button */
		}
	</style>
	<?php
	// Enqueue Vue.js using Admin_Assets class.
	$admin_assets = new Admin_Assets();
	$admin_assets->enqueue_vue_js();
	?>
</head>
<body>
	<div id="app">
		<div class="agreement-container">
			<div class="agreement-header">
				<h1>Plugin User Agreement</h1>
				<p>Please read this agreement carefully before proceeding</p>
			</div>

			<div class="loading-spinner" id="loading-spinner" v-if="iframeLoading"></div>
			<iframe
				id="agreement-iframe"
				class="agreement-iframe"
				:src="apiBaseUrlFront + '/pages/postomatic/agreement'"
				v-show="!iframeLoading"
				@load="iframeLoaded"
			></iframe>

			<div class="agreement-footer">
				<div class="checkbox-container">
					<input type="checkbox" id="agree-checkbox" v-model="agreed">
					<label for="agree-checkbox">
						I have read and agree to the terms
						and conditions outlined in this agreement</label>
				</div>

				<button
					id="agree_btn"
					class="agreement-button"
					:class="{ active: agreed && !isSubmitting}"
					:disabled="!agreed"
					@click="submitAgreement"
				>I Agree</button>
			</div>
		</div>
	</div>

	<script>
		const { createApp } = Vue;

		createApp({
			data() {
				return {
					agreed: false,
					iframeLoading: true,
					apiBaseUrlFront: '<?php echo esc_url( Constants::API_BASE_URL_FRONT ); ?>',
					newUrl: '<?php echo esc_url( $new_url ); ?>',
					wpUser: '<?php echo esc_js( wp_get_current_user()->user_login ); ?>',
					nonce: '<?php echo esc_js( $nonce ); ?>',
					ajaxUrl: '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>',
					adminNonce: '<?php echo esc_js( wp_create_nonce( 'postomatic_admin_nonce' ) ); ?>',
					isSubmitting: false  // Add this new property
				};
			},
			methods: {
				iframeLoaded() {
					this.iframeLoading = false;
				},
				async submitAgreement() {
					if (this.agreed && !this.isSubmitting) {
						this.isSubmitting = true;  // Disable the button

						try {
							await this.fetchCreditData();
						} catch (error) {
							console.error('Agreement submission error:', error);
						} finally {
							// If the request fails, re-enable the button
							this.isSubmitting = false;
						}
					}
				},
				async fetchCreditData() {
					// Routed through admin-ajax so the API service key stays on
					// the server. This used to PUT to the remote endpoint
					// directly, which required printing the key into this page.
					const body = new URLSearchParams();
					body.append('action', 'postomatic_sign_agreement');
					body.append('nonce', this.adminNonce);

					try {
						const response = await fetch(
							this.ajaxUrl,
							{
								method: 'POST',
								credentials: 'same-origin',
								headers: {
									'Content-Type': 'application/x-www-form-urlencoded'
								},
								body: body
							}
						);

						if (!response.ok) throw new Error('Failed to update agreement');

						const result = await response.json();

						if (!result.success) {
							throw new Error((result.data && result.data.message) || 'Failed to update agreement');
						}

						// wp_send_json_success() nests the remote payload under
						// `data`, so the remote body's own `status` flag lives
						// one level deeper than it did before.
						if (!result.data || result.data.status) {
							window.location.href = this.newUrl;
						}
					} catch (error) {
						console.error('Agreement update error:', error);
					}
				}
			}
		}).mount('#app');
	</script>
</body>
</html>

	<?php
	die();
}
