<?php
/**
 * Admin dashboard page template.
 *
 * @package    MaplePress
 * @subpackage MaplePress/includes
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

$options     = get_option( 'maplepress_settings' );
$has_api_key = ! empty( $options['api_key'] );
$is_verified = isset( $options['is_verified'] ) && $options['is_verified'];

// Refresh quota data if verified and API credentials are available
if ( $is_verified && ! empty( $options['api_url'] ) && ! empty( $options['api_key'] ) ) {
	require_once MAPLEPRESS_PLUGIN_DIR . 'includes/class-maplepress-api-client.php';
	$api_client = new MaplePress_API_Client( $options['api_url'], $options['api_key'] );
	$fresh_status = $api_client->verify_connection();

	// Update options with fresh quota data if API call succeeded
	if ( ! is_wp_error( $fresh_status ) ) {
		if ( isset( $fresh_status['search_requests_count'] ) ) {
			$options['search_requests_count'] = absint( $fresh_status['search_requests_count'] );
		}
		if ( isset( $fresh_status['storage_used_bytes'] ) ) {
			$options['storage_used_bytes'] = absint( $fresh_status['storage_used_bytes'] );
		}
		if ( isset( $fresh_status['monthly_pages_indexed'] ) ) {
			$options['monthly_pages_indexed'] = absint( $fresh_status['monthly_pages_indexed'] );
		}
		if ( isset( $fresh_status['total_pages_indexed'] ) ) {
			$options['total_pages_indexed'] = absint( $fresh_status['total_pages_indexed'] );
		}
	}
}
?>

<div class="wrap">
	<h1><?php esc_html_e( 'MaplePress Dashboard', 'maplepress' ); ?></h1>

	<?php
	// Display sync status messages
	if ( isset( $_GET['sync_status'] ) ) {
		if ( $_GET['sync_status'] === 'success' && isset( $_GET['synced_count'] ) ) {
			?>
			<div class="notice notice-success is-dismissible">
				<p>
					<?php
					printf(
						/* translators: %d: number of pages synced */
						esc_html__( '✓ Successfully synced %d pages to MaplePress!', 'maplepress' ),
						absint( $_GET['synced_count'] )
					);
					?>
				</p>
			</div>
			<?php
		} elseif ( $_GET['sync_status'] === 'error' && isset( $_GET['sync_message'] ) ) {
			?>
			<div class="notice notice-error is-dismissible">
				<p>
					<?php
					printf(
						/* translators: %s: error message */
						esc_html__( '✗ Sync failed: %s', 'maplepress' ),
						esc_html( urldecode( $_GET['sync_message'] ) )
					);
					?>
				</p>
			</div>
			<?php
		} elseif ( $_GET['sync_status'] === 'no_posts' ) {
			?>
			<div class="notice notice-warning is-dismissible">
				<p><?php esc_html_e( 'No published posts or pages found to sync.', 'maplepress' ); ?></p>
			</div>
			<?php
		}
	}
	?>

	<?php if ( ! $has_api_key ) : ?>
		<!-- No API key - prompt setup -->
		<div class="notice notice-warning" style="padding: 20px; margin: 20px 0;">
			<h2 style="margin-top: 0;"><?php esc_html_e( 'Welcome to MaplePress!', 'maplepress' ); ?></h2>
			<p><?php esc_html_e( 'You need to connect your site to MaplePress to use the cloud services.', 'maplepress' ); ?></p>
			<p>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=maplepress-settings' ) ); ?>" class="button button-primary button-large">
					<?php esc_html_e( 'Connect to MaplePress', 'maplepress' ); ?>
				</a>
			</p>
		</div>
	<?php elseif ( ! $is_verified ) : ?>
		<!-- API key connected but NOT verified - show verification required notice -->
		<div class="notice notice-error" style="padding: 20px; margin: 20px 0; border-left: 4px solid #dc3232;">
			<h2 style="margin-top: 0; color: #dc3232;">
				⚠️ <?php esc_html_e( 'Domain Verification Required', 'maplepress' ); ?>
			</h2>
			<p>
				<?php esc_html_e( 'Your API key is connected, but your domain needs to be verified before you can use MaplePress features.', 'maplepress' ); ?>
			</p>
			<p>
				<strong><?php esc_html_e( 'What you need to do:', 'maplepress' ); ?></strong>
			</p>
			<ol style="margin-left: 20px;">
				<li><?php esc_html_e( 'Go to Settings → MaplePress', 'maplepress' ); ?></li>
				<li><?php esc_html_e( 'Follow the DNS verification instructions', 'maplepress' ); ?></li>
				<li><?php esc_html_e( 'Add the DNS TXT record to your domain', 'maplepress' ); ?></li>
				<li><?php esc_html_e( 'Click "Verify Domain Now"', 'maplepress' ); ?></li>
			</ol>
			<p>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=maplepress-settings' ) ); ?>" class="button button-primary button-large">
					<?php esc_html_e( 'Complete Verification', 'maplepress' ); ?>
				</a>
			</p>

			<hr style="margin: 20px 0;">

			<p style="margin: 0;">
				<strong><?php esc_html_e( 'Features disabled until verification:', 'maplepress' ); ?></strong><br>
				<span style="color: #666;">
					<?php esc_html_e( 'Page syncing, search indexing, and all MaplePress cloud services are currently unavailable.', 'maplepress' ); ?>
				</span>
			</p>
		</div>

		<?php return; // Stop rendering dashboard content if not verified ?>

	<?php else : ?>
		<!-- Connected - show dashboard -->

		<!-- Connection Status -->
		<div class="notice notice-success" style="padding: 15px; margin: 20px 0; border-left-width: 4px;">
			<h2 style="margin: 0; color: #46b450;">
				✓ <?php esc_html_e( 'Connected to MaplePress', 'maplepress' ); ?>
			</h2>
			<p style="margin: 10px 0 0 0;">
				<strong><?php esc_html_e( 'Domain:', 'maplepress' ); ?></strong> <?php echo esc_html( $options['domain'] ?? 'N/A' ); ?>
				&nbsp;|&nbsp;
				<strong><?php esc_html_e( 'Billing:', 'maplepress' ); ?></strong> <?php esc_html_e( 'Usage-Based', 'maplepress' ); ?>
			</p>
		</div>

		<!-- Usage-Based Billing Notice -->
		<div class="notice notice-info" style="padding: 15px; margin: 20px 0;">
			<h3 style="margin: 0 0 10px 0;">ℹ️ <?php esc_html_e( 'Usage-Based Billing', 'maplepress' ); ?></h3>
			<p><?php esc_html_e( 'MaplePress now uses usage-based billing with no limits or quotas. You pay only for what you use:', 'maplepress' ); ?></p>
			<ul style="margin: 10px 0 10px 20px;">
				<li><?php esc_html_e( '✓ No search request limits', 'maplepress' ); ?></li>
				<li><?php esc_html_e( '✓ No page indexing limits', 'maplepress' ); ?></li>
				<li><?php esc_html_e( '✓ No storage limits', 'maplepress' ); ?></li>
				<li><?php esc_html_e( '✓ Generous rate limits for anti-abuse (10,000 requests/hour)', 'maplepress' ); ?></li>
			</ul>
			<p>
				<a href="https://getmaplepress.com/pricing" target="_blank" class="button">
					<?php esc_html_e( 'View Pricing Details', 'maplepress' ); ?>
				</a>
			</p>
		</div>

		<!-- Quick Stats -->
		<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin: 30px 0;">
			<!-- Monthly Searches -->
			<div class="postbox" style="padding: 20px;">
				<h3 style="margin: 0 0 10px 0;"><?php esc_html_e( 'Monthly Searches', 'maplepress' ); ?></h3>
				<p style="font-size: 32px; font-weight: bold; margin: 0; color: #2271b1;">
					<?php echo esc_html( number_format( $options['search_requests_count'] ?? 0 ) ); ?>
				</p>
				<p style="margin: 5px 0 0 0; color: #666;">
					<?php esc_html_e( 'this billing cycle', 'maplepress' ); ?>
				</p>
			</div>

			<!-- Monthly Pages Indexed -->
			<div class="postbox" style="padding: 20px;">
				<h3 style="margin: 0 0 10px 0;"><?php esc_html_e( 'Monthly Indexing', 'maplepress' ); ?></h3>
				<p style="font-size: 32px; font-weight: bold; margin: 0; color: #2271b1;">
					<?php echo esc_html( number_format( $options['monthly_pages_indexed'] ?? 0 ) ); ?>
				</p>
				<p style="margin: 5px 0 0 0; color: #666;">
					<?php esc_html_e( 'pages this cycle', 'maplepress' ); ?>
				</p>
			</div>

			<!-- Total Pages Indexed -->
			<div class="postbox" style="padding: 20px;">
				<h3 style="margin: 0 0 10px 0;"><?php esc_html_e( 'Total Pages', 'maplepress' ); ?></h3>
				<p style="font-size: 32px; font-weight: bold; margin: 0; color: #2271b1;">
					<?php echo esc_html( number_format( $options['total_pages_indexed'] ?? 0 ) ); ?>
				</p>
				<p style="margin: 5px 0 0 0; color: #666;">
					<?php esc_html_e( 'all-time indexed', 'maplepress' ); ?>
				</p>
			</div>

			<!-- Storage Used -->
			<div class="postbox" style="padding: 20px;">
				<h3 style="margin: 0 0 10px 0;"><?php esc_html_e( 'Storage Used', 'maplepress' ); ?></h3>
				<p style="font-size: 32px; font-weight: bold; margin: 0; color: #2271b1;">
					<?php
					$storage_mb = round( ( $options['storage_used_bytes'] ?? 0 ) / 1024 / 1024, 1 );
					echo esc_html( $storage_mb );
					?>
					<span style="font-size: 16px;">MB</span>
				</p>
				<p style="margin: 5px 0 0 0; color: #666;">
					<?php esc_html_e( 'cumulative usage', 'maplepress' ); ?>
				</p>
			</div>
		</div>

		<!-- Detailed Usage -->
		<h2><?php esc_html_e( 'Usage Details', 'maplepress' ); ?></h2>
		<table class="wp-list-table widefat fixed striped">
			<thead>
				<tr>
					<th style="width: 40%;"><?php esc_html_e( 'Resource', 'maplepress' ); ?></th>
					<th style="width: 30%;"><?php esc_html_e( 'Usage', 'maplepress' ); ?></th>
					<th style="width: 30%;"><?php esc_html_e( 'Period', 'maplepress' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td><strong><?php esc_html_e( 'Monthly Searches', 'maplepress' ); ?></strong></td>
					<td><?php echo esc_html( number_format( $options['search_requests_count'] ?? 0 ) ); ?> requests</td>
					<td><?php esc_html_e( 'Current billing cycle', 'maplepress' ); ?></td>
				</tr>
				<tr>
					<td><strong><?php esc_html_e( 'Monthly Indexing', 'maplepress' ); ?></strong></td>
					<td><?php echo esc_html( number_format( $options['monthly_pages_indexed'] ?? 0 ) ); ?> pages</td>
					<td><?php esc_html_e( 'Current billing cycle', 'maplepress' ); ?></td>
				</tr>
				<tr>
					<td><strong><?php esc_html_e( 'Total Pages Indexed', 'maplepress' ); ?></strong></td>
					<td><?php echo esc_html( number_format( $options['total_pages_indexed'] ?? 0 ) ); ?> pages</td>
					<td><?php esc_html_e( 'All-time cumulative', 'maplepress' ); ?></td>
				</tr>
				<tr>
					<td><strong><?php esc_html_e( 'Storage Used', 'maplepress' ); ?></strong></td>
					<td>
						<?php
						$used_mb = round( ( $options['storage_used_bytes'] ?? 0 ) / 1024 / 1024, 2 );
						echo esc_html( $used_mb ) . ' MB';
						?>
					</td>
					<td><?php esc_html_e( 'All-time cumulative', 'maplepress' ); ?></td>
				</tr>
			</tbody>
		</table>

		<!-- Quick Actions -->
		<h2 style="margin-top: 40px;"><?php esc_html_e( 'Quick Actions', 'maplepress' ); ?></h2>

		<div style="display: flex; gap: 10px; flex-wrap: wrap;">
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=maplepress-initial-sync' ) ); ?>" class="button button-primary button-large">
				<?php esc_html_e( 'Sync All Pages Now', 'maplepress' ); ?>
			</a>

			<a href="<?php echo esc_url( admin_url( 'admin.php?page=maplepress-settings' ) ); ?>" class="button button-large">
				<?php esc_html_e( 'Settings', 'maplepress' ); ?>
			</a>

			<a href="https://getmaplepress.com/dashboard" target="_blank" class="button button-large">
				<?php esc_html_e( '→ Open Cloud Dashboard', 'maplepress' ); ?>
			</a>
		</div>

		<!-- Advanced Tools -->
		<h2 style="margin-top: 40px;"><?php esc_html_e( 'Advanced', 'maplepress' ); ?></h2>
		<div class="postbox" style="padding: 20px; margin-bottom: 20px;">
			<h3 style="margin-top: 0;"><?php esc_html_e( 'Diagnostic Tools', 'maplepress' ); ?></h3>
			<p>
				<?php esc_html_e( 'Access advanced diagnostic and testing tools for your MaplePress integration.', 'maplepress' ); ?>
			</p>
			<div style="display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 30px;">
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=maplepress-speedtest' ) ); ?>" class="button button-large">
					<span class="dashicons dashicons-performance" style="vertical-align: middle;"></span>
					<?php esc_html_e( 'Search Speed Test', 'maplepress' ); ?>
				</a>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=maplepress-system-info' ) ); ?>" class="button button-large">
					<span class="dashicons dashicons-info" style="vertical-align: middle;"></span>
					<?php esc_html_e( 'System Info', 'maplepress' ); ?>
				</a>
			</div>

			<hr style="margin: 20px 0;">

			<h3 style="margin-top: 20px; color: #d63638;"><?php esc_html_e( 'Danger Zone', 'maplepress' ); ?></h3>
			<p>
				<?php esc_html_e( 'Permanently remove MaplePress plugin and all local data.', 'maplepress' ); ?>
			</p>
			<form method="post" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>" style="margin-top: 15px;">
				<input type="hidden" name="action" value="maplepress_reset_and_delete">
				<?php wp_nonce_field( 'maplepress_reset_and_delete' ); ?>
				<button type="submit"
						class="button button-large"
						style="color: #ffffff; background-color: #d63638; border-color: #d63638;"
						onmouseover="this.style.backgroundColor='#b32d2e';"
						onmouseout="this.style.backgroundColor='#d63638';"
						onclick="return confirm('<?php echo esc_js( __( '⚠️ WARNING: This action is PERMANENT and cannot be undone!\n\nThis will:\n✗ Delete all MaplePress settings from WordPress\n✗ Remove API keys and configuration\n✗ Clear verification status\n✗ Deactivate and DELETE the plugin\n\n⚠️ Your data in the MaplePress cloud will remain safe and can be accessed again if you reinstall.\n\nAre you absolutely sure you want to continue?', 'maplepress' ) ); ?>">
					<span class="dashicons dashicons-trash" style="vertical-align: middle;"></span>
					<?php esc_html_e( 'Reset & Delete Plugin', 'maplepress' ); ?>
				</button>
			</form>
			<p class="description" style="color: #d63638; margin-top: 10px;">
				<strong><?php esc_html_e( 'Warning:', 'maplepress' ); ?></strong>
				<?php esc_html_e( 'This will permanently delete the plugin and all local settings. Your cloud data remains safe.', 'maplepress' ); ?>
			</p>
		</div>

		<!-- Site Information -->
		<h2><?php esc_html_e( 'Site Information', 'maplepress' ); ?></h2>
		<table class="form-table">
			<tr>
				<th scope="row"><?php esc_html_e( 'Domain', 'maplepress' ); ?></th>
				<td><?php echo esc_html( $options['domain'] ?? 'N/A' ); ?></td>
			</tr>
			<tr>
				<th scope="row"><?php esc_html_e( 'Billing Model', 'maplepress' ); ?></th>
				<td><strong><?php esc_html_e( 'Usage-Based', 'maplepress' ); ?></strong></td>
			</tr>
			<tr>
				<th scope="row"><?php esc_html_e( 'Status', 'maplepress' ); ?></th>
				<td>
					<?php if ( $options['enabled'] ) : ?>
						<span style="color: #46b450; font-weight: bold;">● <?php esc_html_e( 'Active', 'maplepress' ); ?></span>
					<?php else : ?>
						<span style="color: #dc3232; font-weight: bold;">● <?php esc_html_e( 'Inactive', 'maplepress' ); ?></span>
					<?php endif; ?>
				</td>
			</tr>
		</table>

	<?php endif; ?>

	<!-- Footer -->
	<div style="margin-top: 40px; padding-top: 20px; border-top: 1px solid #dcdcde; text-align: center; color: #646970; font-size: 13px;">
		<p style="margin: 0;">
			<?php
			printf(
				/* translators: %s: link to source code */
				esc_html__( 'MaplePress is open-source software. %s', 'maplepress' ),
				'<a href="https://codeberg.org/mapleopentech/monorepo/src/branch/main/native/wordpress/maplepress-plugin" target="_blank" rel="noopener noreferrer" style="color: #2271b1; text-decoration: none;">' .
				esc_html__( 'View source code', 'maplepress' ) .
				' <span class="dashicons dashicons-external" style="font-size: 12px; vertical-align: text-top;"></span></a>'
			);
			?>
			&nbsp;|&nbsp;
			<a href="https://getmaplepress.com" target="_blank" rel="noopener noreferrer" style="color: #2271b1; text-decoration: none;">
				<?php esc_html_e( 'Documentation', 'maplepress' ); ?>
			</a>
			&nbsp;|&nbsp;
			<a href="https://codeberg.org/mapleopentech/monorepo/issues" target="_blank" rel="noopener noreferrer" style="color: #2271b1; text-decoration: none;">
				<?php esc_html_e( 'Report an issue', 'maplepress' ); ?>
			</a>
		</p>
	</div>
</div>
