<?php
/**
 * Premium Components Tab Content for GGM Commerce Admin.
 *
 * @package GGM_Commerce
 */

defined( 'ABSPATH' ) || exit;

/**
 * Render the Premium Components settings tab.
 */
function ggm_commerce_render_premium_widgets_tab() {
	$license           = ggm_commerce_license();
	$status            = $license->get_status_summary();
	$activated_widgets = $license->get_activated_widgets();

	// Define available premium widgets (using Elementor icons).
	$premium_widgets = array(
		'product-comparison' => array(
			'name'        => 'Product Comparison',
			'description' => 'Compare multiple products side-by-side with customizable attributes.',
			'icon'        => 'eicon-exchange',
		),
		'quick-view'         => array(
			'name'        => 'Quick View',
			'description' => 'Modal popup for quick product preview without leaving the page.',
			'icon'        => 'eicon-preview-thin',
		),
		'wishlist'           => array(
			'name'        => 'Wishlist',
			'description' => 'Allow customers to save products to a wishlist for later.',
			'icon'        => 'eicon-heart-o',
		),
		'recently-viewed'    => array(
			'name'        => 'Recently Viewed',
			'description' => 'Display products the customer has recently viewed.',
			'icon'        => 'eicon-history',
		),
		'product-kits'       => array(
			'name'        => 'Product Kits & Builds',
			'description' => 'Create composite products from components. Kits can be broken down, Builds are permanent.',
			'icon'        => 'eicon-apps',
		),
		'custom-attributes'  => array(
			'name'        => 'Custom Attributes',
			'description' => 'Add custom attributes to products with groups for quick data entry.',
			'icon'        => 'eicon-tags',
		),
		'barcode'            => array(
			'name'        => 'Product Barcodes',
			'description' => 'Add barcodes (EAN, UPC, QR codes) to products with Elementor widget display.',
			'icon'        => 'eicon-barcode',
		),
		'b2b-tax-exemption'  => array(
			'name'        => 'B2B Tax Exemption',
			'description' => 'Allow business customers to register VAT/Tax ID and receive automatic tax exemption.',
			'icon'        => 'eicon-user-circle-o',
		),
		'stripe-gateway'     => array(
			'name'        => 'Stripe Payment Gateway',
			'description' => 'Accept cards, Apple Pay, Google Pay, and Link payments via Stripe.',
			'icon'        => 'eicon-stripe-button',
		),
		'paypal-gateway'     => array(
			'name'        => 'PayPal Payment Gateway',
			'description' => 'Accept PayPal, Pay Later, Venmo, and card payments via PayPal.',
			'icon'        => 'eicon-paypal-button',
		),
		'shipping'           => array(
			'name'        => 'Advanced Shipping',
			'description' => 'Shipping zones, weight-based rates, multiple methods, and carrier integration ready.',
			'icon'        => 'eicon-shape',
		),
		'product-variations' => array(
			'name'        => 'Product Variations',
			'description' => 'Add color, size, material variations with per-variation pricing, stock, and gallery images.',
			'icon'        => 'eicon-adjust',
		),
		'downloads'          => array(
			'name'        => 'Digital Downloads',
			'description' => 'Sell downloadable products with secure delivery, download limits, and license keys.',
			'icon'        => 'eicon-download-kit',
		),
		'product-reviews'    => array(
			'name'        => 'Product Reviews & Ratings',
			'description' => 'Customer reviews with star ratings, verified purchase badges, helpful votes, and rating summaries.',
			'icon'        => 'eicon-comments',
		),
		'google-merchant-feed' => array(
			'name'        => 'Google Merchant Feed',
			'description' => 'Generate product feeds for Google Merchant Center with automatic scheduling and multi-feed support.',
			'icon'        => 'eicon-cloud-upload',
		),
		'discount-vouchers'    => array(
			'name'        => 'Discounts & Vouchers',
			'description' => 'Discount codes, percentage/fixed discounts, and gift card vouchers with usage tracking.',
			'icon'        => 'eicon-price-table',
		),
		'subscription-billing' => array(
			'name'        => 'Subscription Billing',
			'description' => 'Recurring billing with flexible cycles, free trials, customer self-service, and automatic payment retries.',
			'icon'        => 'eicon-sync',
		),
		'checkout-fields'      => array(
			'name'        => 'Custom Checkout Fields',
			'description' => 'Add custom fields to checkout: text, select, radio, checkbox, date, and more. Group fields and place them at various checkout positions.',
			'icon'        => 'eicon-form-horizontal',
		),
		'product-carousel'     => array(
			'name'        => 'Product Carousel',
			'description' => 'Display products in a sliding carousel with peek effect, multiple layout modes, and fully configurable navigation.',
			'icon'        => 'eicon-slider-push',
		),
	);

	// Handle form submissions.
	// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified below.
	if ( isset( $_POST['ggm_premium_action'] ) ) {
		$nonce = isset( $_POST['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) : '';

		if ( wp_verify_nonce( $nonce, 'ggm_premium_widgets' ) ) {
			$action = sanitize_text_field( wp_unslash( $_POST['ggm_premium_action'] ) );

			if ( 'save_license' === $action ) {
				$license_key = isset( $_POST['license_key'] ) ? sanitize_text_field( wp_unslash( $_POST['license_key'] ) ) : '';
				$result      = $license->save_license( $license_key );
				$status      = $license->get_status_summary();

				if ( ! empty( $result['success'] ) ) {
					echo '<div class="notice notice-success"><p>License validated and activated successfully!</p></div>';
				} else {
					$error_msg = isset( $result['message'] ) ? $result['message'] : 'License validation failed.';
					echo '<div class="notice notice-error"><p>' . esc_html( $error_msg ) . '</p></div>';
				}
			} elseif ( 'deactivate_license' === $action ) {
				$license->deactivate_license();
				update_option( GGM_Commerce_License::OPTION_LICENSE, array() );
				update_option( GGM_Commerce_License::OPTION_ACTIVATED_WIDGETS, array() );
				$status            = $license->get_status_summary();
				$activated_widgets = array();
				echo '<div class="notice notice-success"><p>License deactivated.</p></div>';
			} elseif ( 'activate_widget' === $action ) {
				$widget_slug = isset( $_POST['widget_slug'] ) ? sanitize_text_field( wp_unslash( $_POST['widget_slug'] ) ) : '';
				$result      = $license->activate_widget( $widget_slug );
				$activated_widgets = $license->get_activated_widgets();
				$status = $license->get_status_summary();

				if ( ! empty( $result['success'] ) ) {
					echo '<div class="notice notice-success"><p>Widget activated!</p></div>';
				} else {
					$error_msg = isset( $result['message'] ) ? $result['message'] : 'Failed to activate widget.';
					echo '<div class="notice notice-error"><p>' . esc_html( $error_msg ) . '</p></div>';
				}
			} elseif ( 'deactivate_widget' === $action ) {
				$widget_slug = isset( $_POST['widget_slug'] ) ? sanitize_text_field( wp_unslash( $_POST['widget_slug'] ) ) : '';
				$license->deactivate_widget( $widget_slug );
				$activated_widgets = $license->get_activated_widgets();
				$status = $license->get_status_summary();
				echo '<div class="notice notice-success"><p>Widget deactivated.</p></div>';
			}
		}
	}
	?>

	<div class="ggmc-premium-tab-content">
		<!-- Combined License Section -->
		<div class="ggmc-license-section">
			<h2>Premium Components</h2>
			<p>Unlock powerful additional widgets for your store by activating your license.</p>

			<span class="ggmc-license-status-badge <?php echo $status['is_valid'] ? 'active' : 'inactive'; ?>">
				<?php if ( $status['is_valid'] ) : ?>
					License Active - <?php echo esc_html( ucfirst( $status['plan_tier'] ) ); ?> Plan
				<?php else : ?>
					No Active License
				<?php endif; ?>
			</span>

			<?php if ( $status['is_valid'] ) : ?>
				<div class="ggmc-license-details">
					<p><strong>Status:</strong> Active</p>
					<p><strong>Plan:</strong> <?php echo esc_html( ucfirst( $status['plan_tier'] ) ); ?></p>
					<?php if ( $status['expires_at'] ) : ?>
						<p><strong>Expires:</strong> <?php echo esc_html( gmdate( 'F j, Y', strtotime( $status['expires_at'] ) ) ); ?></p>
					<?php endif; ?>
				</div>

				<form method="post">
					<?php wp_nonce_field( 'ggm_premium_widgets' ); ?>
					<input type="hidden" name="ggm_premium_action" value="deactivate_license">
					<button type="submit" class="button" onclick="return confirm('Are you sure you want to deactivate this license?');">Deactivate License</button>
				</form>
			<?php else : ?>
				<form method="post">
					<?php wp_nonce_field( 'ggm_premium_widgets' ); ?>
					<input type="hidden" name="ggm_premium_action" value="save_license">

					<div class="form-row">
						<label for="license_key">License Key</label>
						<input type="text" id="license_key" name="license_key" value="<?php echo esc_attr( $license->get_license_key() ); ?>" placeholder="GGMC-XXXX-XXXX-XXXX-XXXX" required>
						<p class="description">Enter the license key from your purchase confirmation email.</p>
					</div>

					<button type="submit" class="button button-primary">Activate License</button>
				</form>
				<p class="description" style="margin-top: 15px;">
					Don't have a license? <a href="https://wpgoose.com" target="_blank">Purchase one at wpgoose.com</a>
				</p>
			<?php endif; ?>
		</div>

	<?php if ( $status['is_valid'] ) : ?>
		<?php
		$limit     = $status['widgets']['limit'];
		$activated = $status['widgets']['activated'];
		?>
		<!-- Widget Slots Info -->
		<div class="ggmc-widget-slots">
			<div class="slots-info">
				<strong>Widget Slots:</strong>
				<span class="slots-count">
					<?php
					if ( 0 === $limit ) {
						echo esc_html( $activated ) . ' activated (Unlimited available)';
					} else {
						echo esc_html( $activated ) . ' of ' . esc_html( $limit ) . ' used';
					}
					?>
				</span>
			</div>
			<?php if ( $limit > 0 && $activated >= $limit ) : ?>
				<span style="color: #dc3545;">All slots used - deactivate a widget to activate another</span>
			<?php endif; ?>
		</div>

		<!-- Available Widgets -->
		<h3>Available Premium Components</h3>
		<div class="ggmc-widget-grid">
			<?php
			foreach ( $premium_widgets as $slug => $widget ) :
				$is_activated = in_array( $slug, $activated_widgets, true );
				$can_activate = 0 === $limit || $activated < $limit;
				?>
				<div class="ggmc-widget-card <?php echo $is_activated ? 'activated' : ''; ?>">
					<h3>
						<i class="<?php echo esc_attr( $widget['icon'] ); ?>"></i>
						<?php echo esc_html( $widget['name'] ); ?>
					</h3>
					<p><?php echo esc_html( $widget['description'] ); ?></p>

					<form method="post">
						<?php wp_nonce_field( 'ggm_premium_widgets' ); ?>
						<input type="hidden" name="widget_slug" value="<?php echo esc_attr( $slug ); ?>">

						<?php if ( $is_activated ) : ?>
							<input type="hidden" name="ggm_premium_action" value="deactivate_widget">
							<button type="submit" class="button">Deactivate</button>
						<?php elseif ( $can_activate ) : ?>
							<input type="hidden" name="ggm_premium_action" value="activate_widget">
							<button type="submit" class="button button-primary">Activate</button>
						<?php else : ?>
							<button type="button" class="button" disabled>No Slots Available</button>
						<?php endif; ?>
					</form>
				</div>
			<?php endforeach; ?>
		</div>

	<?php else : ?>
		<div class="card">
			<h3>Premium Components Available</h3>
			<p>Activate your license to unlock these powerful widgets:</p>
			<ul style="list-style: disc; margin-left: 20px;">
				<?php foreach ( $premium_widgets as $widget ) : ?>
					<li><strong><?php echo esc_html( $widget['name'] ); ?></strong> - <?php echo esc_html( $widget['description'] ); ?></li>
				<?php endforeach; ?>
			</ul>
			<p><a href="https://wpgoose.com" target="_blank" class="button button-primary">Get Premium License</a></p>
		</div>
	<?php endif; ?>
	</div><!-- .ggmc-premium-tab-content -->
	<?php
}
