<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/** Constants (safe defaults) */
if ( ! defined('EXECVITR_CHECKOUT_URL') ) {
	define( 'EXECVITR_CHECKOUT_URL', 'https://licenses.gksoft.dev/checkout.php' );
}
if ( ! defined('EXECVITR_LICENSE_CHECK_URL') ) {
	define( 'EXECVITR_LICENSE_CHECK_URL', 'https://licenses.gksoft.dev/check-license-vip.php' );
}

/** Menü */
add_action( 'admin_menu', function() {
	add_submenu_page(
		'execvitr-settings',
		esc_html__( 'License', 'executive-vip-transfer-service' ),
		esc_html__( 'License', 'executive-vip-transfer-service' ),
		'manage_options',
		'execvitr-license',
		'execvitr_license_page_html'
	);
}, 20 );

/** CSS sadece lisans sayfasında yüklenecek */
add_action('admin_enqueue_scripts', function($hook) {
	if ( strpos($hook, 'execvitr-license') !== false ) {
		wp_enqueue_style(
			'execvitr-license-css',
			plugins_url('assets/css/admin-style.css', dirname(__FILE__)),
			[],
			'1.0.0'
		);
	}
});

function execvitr_license_page_html() {
	if ( ! current_user_can( 'manage_options' ) ) return;

	// --- Verify license realtime ---
	if ( class_exists( 'EXECVITR_License' ) && method_exists( 'EXECVITR_License', 'verify' ) ) {
		EXECVITR_License::verify();
	}

	$isPro   = function_exists('execvitr_is_pro_active') && execvitr_is_pro_active();
	$domain  = strtolower(preg_replace('/^www\./i','', (string) wp_parse_url(home_url(), PHP_URL_HOST)));
	$status  = get_option(EXECVITR_OPT_LICENSE_STATUS, 'invalid');
	$last    = (int) get_option(EXECVITR_OPT_LICENSE_LASTCHECK, 0);
	$meta    = json_decode((string) get_option(EXECVITR_OPT_LICENSE_META, ''), true);
	$json    = is_array($meta['json'] ?? null) ? $meta['json'] : [];

	$email   = esc_html($json['email'] ?? '');
	$expires = esc_html($json['expires'] ?? '—');

	$current_user = wp_get_current_user();
	$admin_email  = get_option('admin_email', '');
	$userEmail    = is_email($current_user->user_email) ? $current_user->user_email : (is_email($admin_email) ? $admin_email : '');
	$return_url   = admin_url('admin.php?page=execvitr-license');
	$buy_url = add_query_arg([
		'product' => 'vip_transfer',
		'email'   => $userEmail,
		'domain'  => $domain,
		'return'  => rawurlencode($return_url),
	], EXECVITR_CHECKOUT_URL);

	$badgeText  = $isPro ? 'PRO' : 'FREE';
	$badgeColor = $isPro ? 'linear-gradient(135deg,#00b36b,#00e6a1)' : 'linear-gradient(135deg,#d63638,#ff5f5f)';

	echo '<div class="execvitr-license-wrap">';
	echo '<div class="execvitr-status-badge" style="background:' . esc_attr( $badgeColor ) . ';">' . esc_html( $badgeText ) . '</div>';
	echo '<div class="execvitr-license-header">';
	echo '<h1>'.($isPro ? 'License Information' : 'Upgrade to Pro').'</h1>';
	echo '</div>';

	// =============================================
	// 🆓 FREE USER → Upsell Section
	// =============================================
	if ( ! $isPro ) {
	echo '
	<div class="execvitr-pricing">
	<h2 class="pricing-title">Upgrade to Pro</h2>
	<p class="pricing-subtitle">Unlock advanced features — only $59/year.</p>
		<div class="pricing-grid">
			<div class="plan lite">
				<h3>Lite <span class="tag">Free</span></h3>
				<ul>
					<li>WooCommerce-ready booking flow</li>
					<li>Distance-based pricing</li>
					<li>Google Places Autocomplete</li>
				</ul>
			</div>

			<div class="plan pro">
				<h3>Pro <span class="badge">Popular</span></h3>
				<div class="price-block">
					<div class="price-main">$59 <span class="per">/ year</span></div>
					<div class="price-sub">Billed annually — $4.92 / month</div>
				</div>
				<a class="buy-pro" href="'.esc_url($buy_url).'" target="_blank" rel="noopener">
					Buy Pro — $59
				</a>
				<ul>
					<li>Vehicle management (brand, capacity, image)</li>
					<li>Pickup date & pickup time options</li>
					<li>Vehicle-based pricing option</li>
					<li>Priority support</li>
				</ul>
			</div>
		</div>

		<div class="execvitr-trust">
			<div>Payments are securely processed by Stripe.</div>
			<div class="icons">
				<span class="pill">SSL Secured</span>
				<span class="pill">PCI-DSS Compliant</span>
				<span class="pill">Trusted worldwide</span>
			</div>
		</div>
	</div>

	<!-- 📨 License verification by email -->
	<div class="execvitr-verify-box">
		<h3>Already purchased Pro?</h3>
		<p>Enter the email address you used at checkout to activate your license for this site.</p>
		<form id="execvitr-verify-form">
			<input type="email" id="execvitr-email" placeholder="your@email.com" required>
			<button type="submit" class="button button-primary">Verify License</button>
		</form>
		<div id="execvitr-verify-result" style="margin-top:10px;font-weight:500;"></div>
	</div>

	<script>
	document.addEventListener("DOMContentLoaded", function() {
		const form = document.getElementById("execvitr-verify-form");
		const res = document.getElementById("execvitr-verify-result");
		const btn = form.querySelector("button");

		form.addEventListener("submit", async (e) => {
			e.preventDefault();
			res.style.color = "#444";
			res.textContent = "Checking...";
			btn.disabled = true;
			btn.textContent = "Verifying...";

			const email = document.getElementById("execvitr-email").value.trim();
			const domain = window.location.hostname.replace(/^www\\./, "");

			try {
				const r = await fetch("https://licenses.gksoft.dev/verify-email.php?email=" + encodeURIComponent(email) + "&domain=" + encodeURIComponent(domain));
				const j = await r.json();

				if (j.status === "success") {
					res.style.color = "#00b36b";
					res.textContent = j.message + " ✓";
					btn.textContent = "Verified!";
					setTimeout(() => {
						location.reload();
					}, 1000);
				} else {
					res.style.color = "#d63638";
					res.textContent = j.message || "Verification failed.";
					btn.textContent = "Verify License";
					btn.disabled = false;
				}
			} catch (err) {
				res.style.color = "#d63638";
				res.textContent = "Request failed. Please try again.";
				btn.textContent = "Verify License";
				btn.disabled = false;
			}
		});
	});
	</script>
	';
}


	// =============================================
	// 💎 PRO USER → License Info Section
	// =============================================
	else {
		echo '<table class="execvitr-license-table">
			<tr><th>Domain</th><td><code>'. esc_html($domain) .'</code></td></tr>
			<tr><th>Status</th><td>'. esc_html( ucfirst( $status ) ) .'</td></tr>
			<tr><th>Email</th><td>'. esc_html( $email ?: '—' ) .'</td></tr>
			<tr><th>Expires</th><td>'. esc_html( $expires ?: '—' ) .'</td></tr>
			<tr><th>Last Check</th><td>'.($last ? esc_html(gmdate('Y-m-d H:i:s', $last)).' UTC' : '—').'</td></tr>
		</table>

		<div class="execvitr-license-actions">
			<form method="post" style="display:inline;">
				'; wp_nonce_field('execvitr_license_nonce'); echo '
				<button type="submit" class="button button-primary" name="execvitr_license_action" value="verify">Force Refresh</button>
			</form>
		</div>

		<div class="execvitr-meta">Last sync: '.($last ? esc_html(gmdate('H:i:s', $last)).' UTC' : 'never').'</div>';
	}

	echo '</div>'; // wrap
}

