<?php
/**
 * Stripe / Subscriptions Admin Page
 *
 * @package MindWebConcierge
 */

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


add_action( 'admin_init', 'mindweco_stripe_init_settings' );

function mindweco_stripe_init_settings() {
	$prod_id = mindweco_get_product_id();

	if ( ! $prod_id ) {
		return;
	}

	$current = get_option( 'mindweco_stripe_product_id' );
	if ( $current !== $prod_id ) {
		update_option( 'mindweco_stripe_product_id', $prod_id );
	}
}

add_action( 'admin_enqueue_scripts', 'mindweco_stripe_enqueue_scripts' );

function mindweco_stripe_enqueue_scripts( $hook ) {
	if ( 'mind-web_page_mind-web-subscriptions' !== $hook ) {
		return;
	}

	$plugin_url = plugin_dir_url( __DIR__ );
	$ver        = defined( 'MIND_WEB_VERSION' ) ? MIND_WEB_VERSION : '1.2.9';

	$app_guid        = get_option( 'mindweco_plugin_guid' );
	$stripe_base_url = mindweco_get_stripe_base_url();
	$trial_option    = maybe_unserialize( get_option( 'mindweco_trial_response', array() ) );

	if ( ! is_array( $trial_option ) ) {
		$trial_option = array();
	}

	$subscription = isset( $trial_option['subscription'] ) ? $trial_option['subscription'] : $trial_option;
	$end_date     = isset( $subscription['currentPeriodEnd'] )
		? gmdate( 'Y-m-d H:i:s', strtotime( $subscription['currentPeriodEnd'] ) )
		: '';
	$type         = isset( $subscription['type'] )   ? sanitize_text_field( $subscription['type'] )   : '';
	$status       = isset( $subscription['status'] ) ? sanitize_text_field( $subscription['status'] ) : '';

	$product_id = mindweco_get_product_id();
	$user       = wp_get_current_user();
	$user_email = sanitize_email( $user->user_email );

	$site_icon_url = get_site_icon_url();
	$plugin_url_a  = plugin_dir_url( dirname( __FILE__ ) );
	$img_url       = $plugin_url_a . 'assets/img/logo_notespace_smart.png';
	global $wpdb;

	$items_count    = 0;
	$products_count = 0;

	$items_table        = $wpdb->prefix . 'mindweco_indexed_items';
	$items_table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $items_table ) );
	if ( $items_table_exists === $items_table ) {
		$items_count = (int) $wpdb->get_var(
			$wpdb->prepare( "SELECT COUNT(*) FROM `{$items_table}` WHERE status = %s", 'indexed' )
		);
	}

	$products_table        = $wpdb->prefix . 'mindweco_indexed_products';
	$products_table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $products_table ) );
	if ( $products_table_exists === $products_table ) {
		$products_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM `{$products_table}`" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	}
	if ( empty( $site_icon_url ) ) {
		$site_icon_url = $img_url;
	}

	wp_enqueue_style(
		'mindweco-stripe-style',
		$plugin_url . 'assets/css/mindweco_subscription.css',
		array(),
		$ver
	);

	wp_enqueue_style(
        'mindweco-pagination-style',
        $plugin_url . 'assets/css/mindweco-pagination.css',
        array(),
        $ver
    );

	wp_enqueue_script(
		'mindweco-modal',
		$plugin_url . 'assets/js/components/Modal.js',
		array( 'jquery' ),
		$ver,
		true
	);

	wp_enqueue_script(
		'mindweco-toast',
		$plugin_url . 'assets/js/components/Toast.js',
		array( 'jquery' ),
		$ver,
		true
	);

	wp_enqueue_script(
		'mindweco-pagination',
		$plugin_url . 'assets/js/components/Pagination.js',
		array( 'jquery' ),
		$ver,
		true
	);

	$js_base = $plugin_url . 'assets/js/mindweco/';

	wp_enqueue_script(
		'mindweco-helpers',
		$js_base . 'utils/mindweco_helpers.js',
		array( 'jquery' ),
		$ver,
		true
	);

	wp_enqueue_script(
		'mindweco-greetings',
		$js_base . 'utils/mindweco_greetings.js',
		array( 'jquery' ),
		$ver,
		true
	);

	wp_enqueue_script(
		'mindweco-theme',
		$js_base . 'modules/mindweco_theme.js',
		array( 'jquery' ),
		$ver,
		true
	);

	wp_enqueue_script(
		'mindweco-citations',
		$js_base . 'modules/mindweco_citations.js',
		array( 'jquery', 'mindweco-helpers' ),
		$ver,
		true
	);

	wp_enqueue_script(
		'mindweco-messages',
		$js_base . 'modules/mindweco_messages.js',
		array( 'jquery', 'mindweco-helpers', 'mindweco-greetings', 'mindweco-citations' ),
		$ver,
		true
	);

	wp_enqueue_script(
		'mindweco-history',
		$js_base . 'modules/mindweco_history.js',
		array( 'jquery', 'mindweco-helpers', 'mindweco-messages' ),
		$ver,
		true
	);

	wp_enqueue_script(
		'mindweco-subscriptions',
		$js_base . 'modules/mindweco_subscriptions.js',
		array( 'jquery', 'mindweco-helpers', 'mindweco-modal', 'mindweco-toast', 'mindweco-pagination' ),
		$ver,
		true
	);

	wp_enqueue_script(
		'mindweco-logs',
		$js_base . 'modules/mindweco_logs.js',
		array( 'jquery', 'mindweco-helpers' ),
		$ver,
		true
	);

	wp_enqueue_script(
		'mindweco-ui',
		$js_base . 'modules/mindweco_ui.js',
		array( 'jquery', 'mindweco-theme', 'mindweco-messages', 'mindweco-history' ),
		$ver,
		true
	);

	wp_enqueue_script(
		'mindweco-main',
		$plugin_url . 'assets/js/mindweco-main.js',
		array(
			'jquery',
			'mindweco-helpers',
			'mindweco-greetings',
			'mindweco-theme',
			'mindweco-citations',
			'mindweco-messages',
			'mindweco-history',
			'mindweco-subscriptions',
			'mindweco-logs',
			'mindweco-ui',
		),
		$ver,
		true
	);

	wp_localize_script(
		'mindweco-main',
		'mindwecoData',
		array(
			'ajaxurl'               => admin_url( 'admin-ajax.php' ),
			'nonce'                 => wp_create_nonce( 'mindweco_trial_nonce' ),
			'trialEndDate'          => $end_date,
			'trial_status'          => $status,
			'trial_type'            => $type,
			'user_email'            => $user_email,
			'title'                 => esc_url( get_option( 'siteurl' ) ),
			'should_show_initially' => true,
			'has_items'             => ( $items_count > 0 ),
			'has_products'          => ( $products_count > 0 ),
			'calendly_url'          => get_option( 'mindweco_calendly_url', '' ),
			'show_calendly' 		=> (int) get_option('mindweco_show_calendly', 0),
		)
	);
	$show_cal = (int) get_option('mindweco_show_calendly', 0);
	
	wp_localize_script(
		'mindweco-main',
		'mindwecoFrontend',
		array(
			'ajax_url'       => admin_url( 'admin-ajax.php' ),
			'nonce'          => wp_create_nonce( 'mindweco_frontend_nonce' ),
			'post_id'        => get_the_ID(),
			'initialHistory' => array(),
			'bot_avatar'     => esc_url( $site_icon_url ),
			'user_avatar'    => esc_url( get_avatar_url( get_current_user_id(), array( 'size' => 64 ) ) ),
			'summary'        => get_option( 'mindweco_summary', '' ),
			'language'       => sanitize_text_field( explode( '_', get_locale() )[0] ),
		)
	);
}

function mindweco_render_stripe_settings() {

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'mind-web-concierge' ) );
	}

	if (
		isset( $_SERVER['REQUEST_METHOD'] ) &&
		'POST' === sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) )
	) {
		check_admin_referer( 'mindweco_stripe_settings_nonce' );
	}

	$product_id      = mindweco_get_product_id();
	$stripe_base_url = mindweco_get_stripe_base_url();
	$trial_option    = maybe_unserialize( get_option( 'mindweco_trial_response', array() ) );

	if ( ! is_array( $trial_option ) ) {
		$trial_option = array();
	}

	$type      = isset( $trial_option['type'] )   ? sanitize_text_field( $trial_option['type'] )   : '';
	$status    = isset( $trial_option['status'] ) ? sanitize_text_field( $trial_option['status'] ) : '';
	$guid      = get_option( 'mindweco_plugin_guid', '' );
	$site_url  = get_option( 'siteurl' );

	?>
	<div id="mindweco-stripe-settings-wrapper">
		<div class="wrap mindweco-stripe-settings" style="padding:0 20px 40px 20px;">

			<div class="mindweco-card-subscriptions">
				<h4 style="margin:0;color:#fff;font-size:25px;font-weight:600;">
					<i class="bi bi-sliders" aria-hidden="true"></i>
					<?php esc_html_e( 'Subscriptions Overview', 'mind-web-concierge' ); ?>
				</h4>
			</div>

			<h2 class="nav-tab-wrapper mindweco-nav-tabs">
				<a href="#settings" class="nav-tab nav-tab-active mindweco-nav-tab" data-tab="settings">
					<i class="bi bi-sliders" aria-hidden="true"></i>
					<?php esc_html_e( 'General', 'mind-web-concierge' ); ?>
				</a>
				<a href="#subscriptions" class="nav-tab mindweco-nav-tab" data-tab="subscriptions" id="subscription-tab">
					<i class="bi bi-credit-card-2-front" aria-hidden="true"></i>
					<?php esc_html_e( 'Subscriptions Overview', 'mind-web-concierge' ); ?>
				</a>
				<a href="#logs" class="nav-tab mindweco-nav-tab" data-tab="logs" id="logs-tab">
					<i class="bi bi-clock-history" aria-hidden="true"></i>
					<?php esc_html_e( 'Subscriptions History', 'mind-web-concierge' ); ?>
				</a>
			</h2>

			<div id="tab-settings" class="tab-content" style="display:block;">
				<div class="mindweco-card">
					<form method="post">
						<?php wp_nonce_field( 'mindweco_stripe_settings_nonce' ); ?>
						<table class="form-table">
							<tr>
								<td colspan="2">
									<div class="subscription-info-block">
										<h1 class="custom-heading fw-semibold">
											<i class="bi bi-sliders" aria-hidden="true" style="margin-right:6px;"></i>
											<?php esc_html_e( 'Plugin Identifier and Site Address', 'mind-web-concierge' ); ?>
										</h1>
										<p class="text-secondary mt-2 fw-bold m-0 paragraph-info">
											<?php esc_html_e( 'Shows the unique plugin GUID and the site URL for this Mind Web.', 'mind-web-concierge' ); ?>
										</p>
										<p class="text-warning fw-bold">
											<?php esc_html_e( '⚠️ Free Trial Period', 'mind-web-concierge' ); ?><br>
												<?php
													printf(
														wp_kses_post(
															__( 'Your free trial period for the Mind Web Concierge service expires in 7 days. After expiry, the plugin will continue to work using the free-tier service. Upgrade to %s for higher-quality AI responses and advanced features.', 'mind-web-concierge' )
														),
														'<a class="smartmind-link" href="' . esc_url( 'https://smartmind.it' ) . '" target="_blank" rel="noopener noreferrer">SmartMind</a>'
													);
												?>										
										</p>
									</div>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="mindweco-guid">
										<i class="bi bi-key" aria-hidden="true"></i>
										<?php esc_html_e( 'Plugin GUID:', 'mind-web-concierge' ); ?>
									</label>
								</th>
								<td>
									<input
										type="text"
										id="mindweco-guid"
										value="<?php echo esc_attr( $guid ); ?>"
										readonly
										class="regular-text"
									/>
									<p class="description">
										<?php esc_html_e( 'Your plugin identifier GUID.', 'mind-web-concierge' ); ?>
									</p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="site-url">
										<i class="bi bi-globe" aria-hidden="true"></i>
										<?php esc_html_e( 'Site URL:', 'mind-web-concierge' ); ?>
									</label>
								</th>
								<td>
									<input
										type="text"
										id="site-url"
										value="<?php echo esc_attr( $site_url ); ?>"
										readonly
										class="regular-text"
									/>
									<p class="description">
										<?php esc_html_e( 'Your site URL.', 'mind-web-concierge' ); ?>
									</p>
								</td>
							</tr>
						</table>
					</form>
				</div>
			</div>

			<div id="tab-subscriptions" class="tab-content" style="display:none;">
				<div class="mindweco-card">
					<div class="subscription-info-block">
						<h1 class="custom-heading fw-semibold">
							<i class="bi bi-credit-card-2-front" aria-hidden="true" style="margin-right:6px;"></i>
							<?php esc_html_e( 'Subscription Overview', 'mind-web-concierge' ); ?>
						</h1>
						<p class="text-secondary fw-bold m-0 paragraph-info">
							<?php esc_html_e( 'Summary of your current subscription period and status.', 'mind-web-concierge' ); ?>
						</p>
					</div>

					<div class="subscription-header-wrapper">
						<div id="btn-buy-wrapper"></div>
						<button type="button" id="refresh-plugin" class="btn-buy-trial" >
							<i class="bi bi-arrow-clockwise" aria-hidden="true"></i>
							<span><?php esc_html_e( 'Refresh Subscription Status', 'mind-web-concierge' ); ?></span>
						</button>
					</div>

					<div id="mindweco-subscription-result" style="margin-top:10px;color:#d63638;"></div>
					<div id="subscription-cards-container" class="subscription-cards-grid"></div>
				</div>
			</div>

			<div id="tab-logs" class="tab-content" style="display:none;">
				<div class="mindweco-card">
					<div class="subscription-info-block">
						<h1 class="custom-heading fw-semibold">
							<i class="bi bi-clock-history" aria-hidden="true" style="margin-right:6px;"></i>
							<?php esc_html_e( 'Subscription History', 'mind-web-concierge' ); ?>
						</h1>
						<p class="text-secondary fw-bold m-0 paragraph-info">
							<?php esc_html_e( 'Keep track of your subscription history and quickly review all important updates and messages.', 'mind-web-concierge' ); ?>
						</p>
					</div>
					<div id="logs-cards-container" class="logs-cards-grid"></div>
				</div>
			</div>

			<div class="modal fade" id="subscriptionActionModal" tabindex="-1" aria-labelledby="subscriptionActionModalTitle" aria-hidden="true">
				<div class="modal-dialog modal-dialog-centered">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title" id="subscriptionActionModalTitle"></h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<?php esc_attr_e( 'Close', 'mind-web-concierge' ); ?>"></button>
						</div>
						<div class="modal-body" id="subscriptionActionModalBody"></div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
								<?php esc_html_e( 'Close', 'mind-web-concierge' ); ?>
							</button>
							<button type="button" id="subscriptionActionModalConfirm" class="btn"></button>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<?php
}