<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.WP.EnqueuedResourceParameters
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable WordPress.DB.PreparedSQLPlaceholders
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable PluginCheck.Security.DirectDB
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum

/**
 * GT BOGO Engine — Go Live Status Engine
 *
 * Evaluates the complete readiness of the plugin across every system:
 * license, rules, superpowers, email, store branding, PayPal, packs.
 * Powers the Go Live banner on the admin dashboard.
 *
 * @package GT_BOGO_Engine
 * @since   3.12.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class GT_BOGO_Go_Live {
 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound

	private static ?self $instance = null;

	public static function instance(): self {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action( 'wp_ajax_gtbogo_go_live', array( $this, 'ajax_go_live' ) );
		add_action( 'wp_ajax_gtbogo_dismiss_golive', array( $this, 'ajax_dismiss' ) );
		// Banner renders only on the dedicated Store Status page — not on every admin page
	}

	// ── Status check ──────────────────────────────────────────────────────────

	public function get_status(): array {
		$checks = array();

		// 1. License
		$license_status    = get_option( 'gtbogo_license_status', '' );
		$license_key       = get_option( 'gtbogo_license_key', '' );
		$checks['license'] = array(
			'label'        => 'PRO License',
			'pass'         => $license_status === 'active' && ! empty( $license_key ),
			'detail'       => $license_status === 'active' ? 'License active — ' . substr( $license_key, 0, 12 ) . '...' : 'No active license — enter your key in the License tab.',
			'action'       => admin_url( 'admin.php?page=gt-bogo-engine&tab=license' ),
			'action_label' => 'Activate License',
		);

		// 2. Store name
		$store_name           = get_bloginfo( 'name' );
		$generic              = in_array(
			strtolower( trim( $store_name ) ),
			array( 'wordpress', 'my wordpress blog', 'my blog', 'just another wordpress site', '' ),
			true
		);
		$checks['store_name'] = array(
			'label'        => 'Store Name',
			'pass'         => ! $generic,
			'detail'       => $generic ? 'Store name is still the WordPress default — set your real store name at Settings > General.' : 'Store name set: ' . esc_html( $store_name ),
			'action'       => admin_url( 'options-general.php' ),
			'action_label' => 'Set Store Name',
		);

		// 3. Store logo
		$site_icon            = get_option( 'site_icon' );
		$custom_logo          = get_option( 'gtbogo_email_logo_url', '' );
		$has_logo             = ! empty( $site_icon ) || ! empty( $custom_logo );
		$checks['store_logo'] = array(
			'label'        => 'Store Logo',
			'pass'         => $has_logo,
			'detail'       => $has_logo ? 'Store logo configured.' : 'No logo set — add a site icon at Appearance > Customize > Site Identity, or paste a URL in GT BOGO Engine > Settings.',
			'action'       => admin_url( 'admin.php?page=gt-bogo-engine&tab=settings' ),
			'action_label' => 'Set Logo',
		);

		// 4. WooCommerce email from address
		$from_email          = get_option( 'woocommerce_email_from_address', '' );
		$checks['woo_email'] = array(
			'label'        => 'WooCommerce Email',
			'pass'         => ! empty( $from_email ) && filter_var( $from_email, FILTER_VALIDATE_EMAIL ),
			'detail'       => ! empty( $from_email ) ? 'From address: ' . esc_html( $from_email ) : 'WooCommerce from email not set — go to WooCommerce > Settings > Emails.',
			'action'       => admin_url( 'admin.php?page=wc-settings&tab=email' ),
			'action_label' => 'Configure Email',
		);

		// 5. At least one active rule
		global $wpdb;
		$active_rules           = (int) $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
			"SELECT COUNT(*) FROM {$wpdb->prefix}gtbogo_rules WHERE status = 'active'"
		);
		$checks['active_rules'] = array(
			'label'        => 'Active Rules',
			'pass'         => $active_rules > 0,
			'detail'       => $active_rules > 0 ? $active_rules . ' active ' . ( $active_rules === 1 ? 'rule' : 'rules' ) . ' ready to fire.' : 'No active rules — import a Pro Pack or create a Free Rule.',
			'action'       => admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ),
			'action_label' => 'Import a Pack',
		);

		// 6. At least one superpower enabled
		$sp_settings           = get_option( 'gtbogo_superpower_settings', array() );
		$sp_enabled            = array_filter( $sp_settings, fn( $s ) => ! empty( $s['enabled'] ) );
		$checks['superpowers'] = array(
			'label'        => 'Superpowers',
			'pass'         => ! empty( $sp_enabled ),
			'detail'       => ! empty( $sp_enabled ) ? count( $sp_enabled ) . ' superpower' . ( count( $sp_enabled ) === 1 ? '' : 's' ) . ' active.' : 'No superpowers enabled — enable Cart Progress Bar and Product Badges to start.',
			'action'       => admin_url( 'admin.php?page=gt-bogo-engine&tab=superpowers' ),
			'action_label' => 'Enable Superpowers',
		);

		// 7. Customer emails configured
		$emails_on                 = (bool) get_option( 'gtbogo_customer_emails_enabled', false );
		$checks['customer_emails'] = array(
			'label'        => 'Customer Emails',
			'pass'         => $emails_on,
			'detail'       => $emails_on ? 'Customer emails enabled — customers will receive deal confirmations, tier upgrades, and rewards automatically.' : 'Customer emails are off — enable them in Settings to keep customers engaged automatically.',
			'action'       => admin_url( 'admin.php?page=gt-bogo-engine&tab=settings' ),
			'action_label' => 'Enable Emails',
		);

		// 8. Currency configured
		$currency           = get_woocommerce_currency();
		$checks['currency'] = array(
			'label'        => 'Currency',
			'pass'         => ! empty( $currency ),
			'detail'       => ! empty( $currency ) ? 'Currency: ' . esc_html( $currency ) . ' — deals will display in your store currency.' : 'WooCommerce currency not set.',
			'action'       => admin_url( 'admin.php?page=wc-settings&tab=general' ),
			'action_label' => 'Set Currency',
		);

		// 9. Permalink structure (required for WooCommerce)
		$permalink            = get_option( 'permalink_structure', '' );
		$checks['permalinks'] = array(
			'label'        => 'Permalink Structure',
			'pass'         => ! empty( $permalink ),
			'detail'       => ! empty( $permalink ) ? 'Permalinks configured.' : 'Permalink structure is plain — WooCommerce requires a non-plain structure. Go to Settings > Permalinks.',
			'action'       => admin_url( 'options-permalink.php' ),
			'action_label' => 'Fix Permalinks',
		);

		// 10. HTTPS
		$is_https        = is_ssl() || strpos( home_url(), 'https://' ) === 0;
		$checks['https'] = array(
			'label'        => 'HTTPS',
			'pass'         => $is_https,
			'detail'       => $is_https ? 'Store is running on HTTPS — PayPal and secure checkout are fully functional.' : 'Store is not on HTTPS — PayPal requires HTTPS. Contact your host to enable SSL.',
			'action'       => 'https://graphictshirts.shop/bogo/documentation',
			'action_label' => 'Learn More',
		);

		$passed = count( array_filter( $checks, fn( $c ) => $c['pass'] ) );
		$total  = count( $checks );
		$live   = get_option( 'gtbogo_is_live', false );

		return array(
			'checks'     => $checks,
			'passed'     => $passed,
			'total'      => $total,
			'percentage' => (int) round( ( $passed / $total ) * 100 ),
			'all_pass'   => $passed === $total,
			'is_live'    => (bool) $live,
			'dismissed'  => (bool) get_option( 'gtbogo_golive_dismissed', false ),
		);
	}

	// ── Go Live action ────────────────────────────────────────────────────────

	public function ajax_go_live(): void {
		check_ajax_referer( 'gtbogo_go_live_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die();
		}

		$status = $this->get_status();

		// Enable all systems
		update_option( 'gtbogo_is_live', true );
		update_option( 'gtbogo_live_date', current_time( 'mysql', true ) );

		// Enable customer emails if not already on
		$settings                            = get_option( 'gtbogo_settings', array() );
		$settings['customer_emails_enabled'] = '1';
		update_option( 'gtbogo_settings', $settings );

		// Clear any dismissal
		delete_option( 'gtbogo_golive_dismissed' );

		wp_send_json_success(
			array(
				'message'    => 'Your store is now live. All GT BOGO Engine systems are active.',
				'percentage' => $status['percentage'],
				'passed'     => $status['passed'],
				'total'      => $status['total'],
			)
		);
	}

	public function ajax_dismiss(): void {
		check_ajax_referer( 'gtbogo_go_live_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die();
		}
		update_option( 'gtbogo_golive_dismissed', true );
		wp_send_json_success();
	}

	// ── Admin banner ──────────────────────────────────────────────────────────

	public function render_status_page(): void {
		$screen = get_current_screen();
		if ( ! $screen || strpos( $screen->id, 'gt-bogo' ) === false ) {
			return;
		}
		if ( get_option( 'gtbogo_golive_dismissed', false ) && get_option( 'gtbogo_is_live', false ) ) {
			return;
		}

		$status = $this->get_status();
		$pct    = $status['percentage'];
		$passed = $status['passed'];
		$total  = $status['total'];
		$live   = $status['is_live'];
		$accent = '#E10000';
		$nonce  = wp_create_nonce( 'gtbogo_go_live_nonce' );

		// Color logic
		$has_conflicts = isset( $status['checks']['conflicts'] ) && ! $status['checks']['conflicts']['pass'];
		$bar_color     = $pct < 50 ? '#ef4444' : ( $has_conflicts ? '#f59e0b' : ( $pct < 100 ? '#f59e0b' : ( $live ? '#22c55e' : '#E10000' ) ) );
		$status_label  = $live && ! $has_conflicts ? 'LIVE' : ( $has_conflicts ? 'CONFLICTS' : ( $pct === 100 ? 'READY TO GO LIVE' : 'SETUP IN PROGRESS' ) );
		$status_color  = $live && ! $has_conflicts ? '#22c55e' : ( $has_conflicts ? '#f59e0b' : ( $pct === 100 ? '#22c55e' : '#f59e0b' ) );

		?>
		<div id="gtbogo-golive-banner" style="
			background:#070C1C;border:1px solid #0f1a30;border-radius:10px;
			margin:16px 20px 0 0;padding:0;overflow:hidden;
			font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;">

			<!-- Banner header -->
			<div style="display:flex;align-items:center;justify-content:space-between;padding:18px 24px;border-bottom:1px solid #0f1a30;gap:20px;flex-wrap:wrap;">
				<div style="display:flex;align-items:center;gap:16px;">
					<div style="width:44px;height:44px;border-radius:50%;background:<?php echo esc_html( $live ) ? 'rgba(34,197,94,.15)' : 'rgba(225,0,0,.1)'; ?>;border:1px solid <?php echo esc_html( $live ) ? '#22c55e' : '#E10000'; ?>;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
						<?php if ( $live ) : ?>
						<svg width="20" height="20" viewBox="0 0 20 20" fill="none"><circle cx="10" cy="10" r="3" fill="#22c55e"/><circle cx="10" cy="10" r="7" stroke="#22c55e" stroke-width="1.5" stroke-dasharray="2 2"/></svg>
						<?php else : ?>
						<svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M10 2L12.5 7.5H18L13.5 11L15.5 17L10 13.5L4.5 17L6.5 11L2 7.5H7.5L10 2Z" stroke="#E10000" stroke-width="1.5" fill="none"/></svg>
						<?php endif; ?>
					</div>
					<div>
						<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
							<p style="margin:0;font-size:15px;font-weight:700;color:#ffffff;">GT BOGO Engine Store Status</p>
							<!-- Traffic light indicator -->
							<div style="display:flex;align-items:center;gap:5px;background:#030608;border:1px solid #0f1a30;border-radius:999px;padding:4px 12px 4px 8px;">
								<!-- Red light -->
								<div style="width:10px;height:10px;border-radius:50%;background:<?php echo ( ! $live && $pct < 100 && ! $has_conflicts ) ? '#ef4444' : '#1a0808'; ?>;box-shadow:<?php echo ( ! $live && $pct < 100 && ! $has_conflicts ) ? '0 0 6px #ef4444' : 'none'; ?>;transition:all .3s;"></div>
								<!-- Yellow light -->
								<div style="width:10px;height:10px;border-radius:50%;background:<?php echo esc_html( $has_conflicts ) ? '#f59e0b' : '#1a1408'; ?>;box-shadow:<?php echo esc_html( $has_conflicts ) ? '0 0 8px #f59e0b' : 'none'; ?>;transition:all .3s;"></div>
								<!-- Green light -->
								<div style="width:10px;height:10px;border-radius:50%;background:<?php echo ( $live && ! $has_conflicts ) ? '#22c55e' : '#081a08'; ?>;box-shadow:<?php echo ( $live && ! $has_conflicts ) ? '0 0 8px #22c55e' : 'none'; ?>;transition:all .3s;"></div>
								<span style="font-size:10px;font-weight:800;letter-spacing:.1em;color:<?php echo esc_html( $status_color ); ?>;margin-left:4px;"><?php echo esc_html( $status_label ); ?></span>
							</div>
						</div>
						<p style="margin:4px 0 0;font-size:13px;color:#4a6a8a;"><?php echo esc_html( $passed ); ?> of <?php echo esc_html( $total ); ?> checks passing <?php echo esc_html( $live ) ? '— your store is live and all systems are active' : '— complete setup to go live'; ?></p>
					</div>
				</div>
				<div style="display:flex;align-items:center;gap:10px;flex-shrink:0;">
					<?php if ( ! $live && $status['all_pass'] && ! $has_conflicts ) : ?>
					<button id="gtbogo-golive-btn" onclick="gtbogoGoLive()" style="background:#E10000;color:#fff;border:none;border-radius:999px;padding:10px 28px;font-size:14px;font-weight:700;cursor:pointer;letter-spacing:.02em;">
						Go Live
					</button>
					<?php elseif ( $live ) : ?>
					<span style="color:#22c55e;font-size:13px;font-weight:700;">● Live since <?php echo esc_html( gmdate( 'M j, Y', strtotime( get_option( 'gtbogo_live_date', current_time( 'mysql', true ) ) ) ) ); ?></span>
					<?php endif; ?>
					<button onclick="gtbogoDismissGoLive()" style="background:transparent;color:#4a6a8a;border:none;font-size:18px;cursor:pointer;padding:4px 8px;line-height:1;" title="Dismiss">&times;</button>
				</div>
			</div>

			<!-- Progress bar -->
			<div style="padding:0 24px 0;background:#050a16;">
				<div style="height:4px;background:#0f1a30;border-radius:0;">
					<div style="height:4px;width:<?php echo esc_html( $pct ); ?>%;background:<?php echo esc_html( $bar_color ); ?>;border-radius:0;transition:width .4s ease;"></div>
				</div>
			</div>

			<!-- Checks grid -->
			<div id="gtbogo-golive-checks" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:0;background:#050a16;padding:16px 24px 20px;">
				<?php foreach ( $status['checks'] as $key => $check ) : ?>
				<div style="display:flex;align-items:flex-start;gap:10px;padding:10px 12px;border-radius:8px;<?php echo esc_html( $check['pass'] ) ? '' : 'background:rgba(239,68,68,.04);'; ?>">
					<div style="width:20px;height:20px;border-radius:50%;flex-shrink:0;margin-top:1px;display:flex;align-items:center;justify-content:center;background:<?php echo esc_html( $check['pass'] ) ? 'rgba(34,197,94,.15)' : 'rgba(239,68,68,.15)'; ?>;border:1px solid <?php echo esc_html( $check['pass'] ) ? '#22c55e' : '#ef4444'; ?>;">
						<?php if ( $check['pass'] ) : ?>
						<svg width="10" height="10" viewBox="0 0 10 10"><path d="M2 5L4 7L8 3" stroke="#22c55e" stroke-width="1.5" fill="none" stroke-linecap="round"/></svg>
						<?php else : ?>
						<svg width="10" height="10" viewBox="0 0 10 10"><path d="M3 3L7 7M7 3L3 7" stroke="#ef4444" stroke-width="1.5" stroke-linecap="round"/></svg>
						<?php endif; ?>
					</div>
					<div style="flex:1;min-width:0;">
						<p style="margin:0 0 2px;font-size:13px;font-weight:700;color:<?php echo esc_html( $check['pass'] ) ? '#c8d8e8' : '#ffffff'; ?>;"><?php echo esc_html( $check['label'] ); ?></p>
						<p style="margin:0;font-size:12px;color:<?php echo esc_html( $check['pass'] ) ? '#4a6a8a' : '#fca5a5'; ?>;line-height:1.5;"><?php echo esc_html( $check['detail'] ); ?></p>
						<?php if ( ! $check['pass'] ) : ?>
						<a href="<?php echo esc_url( $check['action'] ); ?>" style="display:inline-block;margin-top:6px;font-size:11px;font-weight:700;color:#E10000;text-decoration:none;letter-spacing:.04em;"><?php echo esc_html( $check['action_label'] ); ?> →</a>
						<?php endif; ?>
					</div>
				</div>
				<?php endforeach; ?>
			</div>

		</div>

		<?php if ( $has_conflicts ) : ?>
		<div style="display:flex;align-items:center;gap:16px;padding:14px 24px;background:#1a1000;border-top:1px solid #f59e0b44;">
			<div style="width:32px;height:32px;border-radius:50%;background:rgba(245,158,11,.15);border:1px solid #f59e0b;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
				<svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M8 2L14 13H2L8 2Z" stroke="#f59e0b" stroke-width="1.2" fill="none"/><path d="M8 6V9M8 11V11.5" stroke="#f59e0b" stroke-width="1.2" stroke-linecap="round"/></svg>
			</div>
			<div style="flex:1;">
				<p style="margin:0 0 2px;font-size:13px;font-weight:700;color:#f59e0b;">Rule conflicts detected — your deals may not fire as expected</p>
				<p style="margin:0;font-size:12px;color:#92400e;line-height:1.5;">Two or more active rules share the same priority. When rules collide, only one fires. Go to the Conflicts page to review affected packs and resolve priority clashes.</p>
			</div>
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=conflicts' ) ); ?>"
				style="flex-shrink:0;background:#f59e0b;color:#000;border:none;border-radius:999px;padding:8px 20px;font-size:13px;font-weight:700;cursor:pointer;text-decoration:none;white-space:nowrap;">
				View Conflicts
			</a>
		</div>
		<?php endif; ?>

		<script>
		function gtbogoGoLive() {
			var btn = document.getElementById('gtbogo-golive-btn');
			if (btn) { btn.textContent = 'Going Live...'; btn.disabled = true; }
			fetch(ajaxurl, {
				method: 'POST',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
				body: 'action=gtbogo_go_live&nonce=<?php echo esc_js( $nonce ); ?>'
			})
			.then(r => r.json())
			.then(data => {
				if (data.success) {
					var banner = document.getElementById('gtbogo-golive-banner');
					if (banner) {
						banner.style.borderColor = '#22c55e';
						banner.innerHTML = '<div style="padding:24px;display:flex;align-items:center;gap:16px;">'
							+ '<div style="width:48px;height:48px;border-radius:50%;background:rgba(34,197,94,.15);border:1px solid #22c55e;display:flex;align-items:center;justify-content:center;">'
							+ '<svg width="24" height="24" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="4" fill="#22c55e"/><circle cx="12" cy="12" r="9" stroke="#22c55e" stroke-width="1.5" stroke-dasharray="2 3"/></svg></div>'
							+ '<div><p style="margin:0 0 4px;font-size:17px;font-weight:700;color:#22c55e;">Your store is live.</p>'
							+ '<p style="margin:0;font-size:14px;color:#8ab0d0;">' + data.data.message + '</p></div></div>';
					}
				}
			});
		}
		function gtbogoDismissGoLive() {
			fetch(ajaxurl, {
				method: 'POST',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
				body: 'action=gtbogo_dismiss_golive&nonce=<?php echo esc_js( $nonce ); ?>'
			});
			var banner = document.getElementById('gtbogo-golive-banner');
			if (banner) banner.style.display = 'none';
		}
		</script>
		<?php
	}
}
