<?php
/**
 * Livada SEO — Licence Settings View
 *
 * @package Livada_SEO
 */

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

$has_class  = class_exists( 'Livada_SEO_License' );
$key        = $has_class ? Livada_SEO_License::get_key() : '';
$status     = $has_class ? Livada_SEO_License::get_status() : [];
$is_valid   = ! empty( $status['valid'] );
$masked_key = '' !== $key ? substr( $key, 0, 8 ) . str_repeat( '•', max( 0, strlen( $key ) - 12 ) ) . substr( $key, -4 ) : '';

$plan       = (string) ( $status['plan']       ?? '' );
$email      = (string) ( $status['email']      ?? '' );
$expires_at = (string) ( $status['expires_at'] ?? '' );
$message    = (string) ( $status['message']    ?? '' );
$checked_at = isset( $status['checked_at'] ) ? (int) $status['checked_at'] : 0;
?>
<div class="wrap livada-seo-wrap has-ls-hero">
<?php include LIVADA_SEO_PATH . 'includes/admin/views/_partials/header.php'; ?>
	<h1><?php esc_html_e( 'Licence', 'livada-seo' ); ?></h1>

	<?php if ( isset( $_GET['updated'] ) ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Settings saved.', 'livada-seo' ); ?></p></div>
	<?php endif; ?>

	<div class="livada-seo-card" style="max-width:640px;margin-top:20px;">

		<!-- Status banner -->
		<div style="padding:16px 20px;border-radius:4px;margin-bottom:24px;background:<?php echo $is_valid ? '#edfaed' : '#fdf0f0'; ?>;border-left:4px solid <?php echo $is_valid ? '#46b450' : '#dc3232'; ?>;">
			<?php if ( $is_valid ) : ?>
				<strong style="color:#46b450;">&#10003; <?php esc_html_e( 'Licence active', 'livada-seo' ); ?></strong>
				<?php if ( '' !== $plan ) : ?>
					&nbsp;—&nbsp;<span style="text-transform:uppercase;font-size:11px;font-weight:600;"><?php echo esc_html( $plan ); ?></span>
				<?php endif; ?>
				<?php if ( '' !== $email ) : ?>
					<div style="margin-top:4px;color:#555;font-size:12px;"><?php echo esc_html( $email ); ?></div>
				<?php endif; ?>
				<?php if ( '' !== $expires_at && 'never' !== $expires_at ) : ?>
					<div style="margin-top:4px;color:#555;font-size:12px;">
						<?php esc_html_e( 'Expires:', 'livada-seo' ); ?> <?php echo esc_html( $expires_at ); ?>
					</div>
				<?php endif; ?>
			<?php else : ?>
				<strong style="color:#dc3232;">&#10007; <?php esc_html_e( 'No active licence', 'livada-seo' ); ?></strong>
				<?php if ( '' !== $key && 'no_key' !== $message ) : ?>
					<div style="margin-top:4px;color:#555;font-size:12px;">
						<?php
						$msg_map = [
							'invalid_license'  => __( 'Licence key not recognised.', 'livada-seo' ),
							'expired'          => __( 'Licence has expired.', 'livada-seo' ),
							'max_activations'  => __( 'Maximum number of sites reached for this licence.', 'livada-seo' ),
							'site_mismatch'    => __( 'This key is registered to another domain.', 'livada-seo' ),
							'connection_error' => __( 'Could not reach the licence server. Check again later.', 'livada-seo' ),
						];
						echo esc_html( $msg_map[ $message ] ?? $message );
						?>
					</div>
				<?php endif; ?>
				<div style="margin-top:8px;color:#555;font-size:12px;">
					<?php esc_html_e( 'Auto-updates are disabled without a valid licence.', 'livada-seo' ); ?>
				</div>
			<?php endif; ?>

			<?php if ( $checked_at > 0 ) : ?>
				<div style="margin-top:6px;color:#999;font-size:11px;">
					<?php
					printf(
						/* translators: %s: human-readable time ago */
						esc_html__( 'Last checked: %s ago', 'livada-seo' ),
						esc_html( human_time_diff( $checked_at ) )
					);
					?>
				</div>
			<?php endif; ?>
		</div>

		<?php if ( $is_valid ) : ?>
			<!-- Activated: show masked key + deactivate button -->
			<table class="form-table" role="presentation">
				<tr>
					<th scope="row"><?php esc_html_e( 'Licence key', 'livada-seo' ); ?></th>
					<td>
						<code><?php echo esc_html( $masked_key ); ?></code>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'This site', 'livada-seo' ); ?></th>
					<td><code><?php echo esc_html( home_url( '/' ) ); ?></code></td>
				</tr>
			</table>

			<p>
				<button type="button" id="livada-license-check" class="button">
					<?php esc_html_e( 'Check again', 'livada-seo' ); ?>
				</button>
				&nbsp;
				<button type="button" id="livada-license-deactivate" class="button button-link-delete" style="margin-left:8px;">
					<?php esc_html_e( 'Deactivate on this site', 'livada-seo' ); ?>
				</button>
			</p>

		<?php else : ?>
			<!-- Not activated: show input form -->
			<table class="form-table" role="presentation">
				<tr>
					<th scope="row"><label for="livada-license-key-input"><?php esc_html_e( 'Licence key', 'livada-seo' ); ?></label></th>
					<td>
						<input
							type="text"
							id="livada-license-key-input"
							class="regular-text"
							placeholder="LIVADA-XXXX-XXXX-XXXX-XXXX"
							autocomplete="off"
							spellcheck="false"
						/>
						<p class="description">
							<?php esc_html_e( 'Enter the licence key you received by e-mail after purchase.', 'livada-seo' ); ?>
						</p>
					</td>
				</tr>
			</table>

			<p>
				<button type="button" id="livada-license-activate" class="button button-primary">
					<?php esc_html_e( 'Activate licence', 'livada-seo' ); ?>
				</button>
			</p>
		<?php endif; ?>

		<div id="livada-license-msg" style="margin-top:12px;display:none;"></div>

	</div><!-- .livada-seo-card -->
</div><!-- .wrap -->

<script>
document.addEventListener('DOMContentLoaded', function () {
	if (typeof livadaSEO === 'undefined') {
		console.warn('livadaSEO not loaded');
		return;
	}
	var nonce  = livadaSEO.nonce || '';
	var ajax   = livadaSEO.ajaxUrl || (typeof ajaxurl !== 'undefined' ? ajaxurl : '/wp-admin/admin-ajax.php');
	var msgBox = document.getElementById('livada-license-msg');

	function showMsg(text, ok) {
		if (!msgBox) return;
		msgBox.style.display = 'block';
		msgBox.style.padding = '10px 14px';
		msgBox.style.borderLeft = '4px solid ' + (ok ? '#46b450' : '#dc3232');
		msgBox.style.background = ok ? '#edfaed' : '#fdf0f0';
		msgBox.textContent = text;
	}

	function post(action, extra, cb) {
		var data = Object.assign({ action: action, nonce: nonce }, extra);
		var body = new URLSearchParams(data).toString();
		fetch(ajax, {
			method: 'POST',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			body: body
		})
		.then(function(r){ return r.json(); })
		.then(cb)
		.catch(function(){ showMsg('Network error.', false); });
	}

	var activateBtn    = document.getElementById('livada-license-activate');
	var deactivateBtn  = document.getElementById('livada-license-deactivate');
	var checkBtn       = document.getElementById('livada-license-check');
	var keyInput       = document.getElementById('livada-license-key-input');

	if (activateBtn) {
		activateBtn.addEventListener('click', function () {
			var key = keyInput ? keyInput.value.trim() : '';
			if (!key) { showMsg('<?php echo esc_js( __( 'Please enter a licence key.', 'livada-seo' ) ); ?>', false); return; }
			activateBtn.disabled = true;
			activateBtn.textContent = '<?php echo esc_js( __( 'Activating…', 'livada-seo' ) ); ?>';
			post('livada_seo_activate_license', { license_key: key }, function (res) {
				if (res.success) {
					location.reload();
				} else {
					activateBtn.disabled = false;
					activateBtn.textContent = '<?php echo esc_js( __( 'Activate licence', 'livada-seo' ) ); ?>';
					showMsg(res.data && res.data.message ? res.data.message : '<?php echo esc_js( __( 'Activation failed.', 'livada-seo' ) ); ?>', false);
				}
			});
		});
	}

	if (deactivateBtn) {
		deactivateBtn.addEventListener('click', function () {
			if (!confirm('<?php echo esc_js( __( 'Deactivate the licence on this site?', 'livada-seo' ) ); ?>')) return;
			deactivateBtn.disabled = true;
			post('livada_seo_deactivate_license', {}, function () { location.reload(); });
		});
	}

	if (checkBtn) {
		checkBtn.addEventListener('click', function () {
			checkBtn.disabled = true;
			checkBtn.textContent = '<?php echo esc_js( __( 'Checking…', 'livada-seo' ) ); ?>';
			post('livada_seo_check_license', {}, function (res) {
				checkBtn.disabled = false;
				checkBtn.textContent = '<?php echo esc_js( __( 'Check again', 'livada-seo' ) ); ?>';
				if (res.success) {
					showMsg('<?php echo esc_js( __( 'Licence is valid.', 'livada-seo' ) ); ?>', true);
				} else {
					showMsg(res.data && res.data.message ? res.data.message : '<?php echo esc_js( __( 'Licence invalid or expired.', 'livada-seo' ) ); ?>', false);
				}
			});
		});
	}
});
</script>
