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

// Exit if accessed directly.
if (!defined("ABSPATH")) {
    exit();
} ?>

<div class="wrap">
	<h1><?php echo esc_html(get_admin_page_title()); ?></h1>

	<?php
 $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
 // Fetch fresh data on every page load without persisting to avoid triggering hooks
 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
     // Note: We only update the in-memory $options array, not the database
     // This ensures fresh display without triggering validation hooks
     if (!is_wp_error($fresh_status)) {
         // Update quota fields in options for display only
         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"],
             );
         }
         // Do NOT call update_option() here - it could trigger validation/sync hooks
     }
 }
 ?>

	<?php if (!$has_api_key): ?>
		<!-- First-time setup instructions -->
		<div class="notice notice-info" style="padding: 15px; margin: 20px 0;">
			<h2 style="margin-top: 0;"><?php esc_html_e(
       "🚀 Welcome to MaplePress!",
       "maplepress",
   ); ?></h2>
			<p><?php esc_html_e(
       "MaplePress provides cloud services for your WordPress site - starting with advanced search, with more features coming soon (uploads, metrics, analytics, etc.).",
       "maplepress",
   ); ?></p>
			<p><strong><?php esc_html_e(
       '✨ When you save settings with "Enable MaplePress search" checked, all your existing pages will automatically sync!',
       "maplepress",
   ); ?></strong></p>
			<p><?php esc_html_e("To get started, follow these steps:", "maplepress"); ?></p>
			<ol style="margin-left: 20px;">
				<li>
					<strong><?php esc_html_e(
         "Create a MaplePress account:",
         "maplepress",
     ); ?></strong><br>
					<a href="https://getmaplepress.com/register" target="_blank" class="button button-primary" style="margin-top: 5px;">
						<?php esc_html_e("Sign Up at MaplePress.io", "maplepress"); ?>
					</a>
					<?php esc_html_e("or", "maplepress"); ?>
					<a href="https://getmaplepress.com/login" target="_blank" class="button" style="margin-top: 5px;">
						<?php esc_html_e("Login to Existing Account", "maplepress"); ?>
					</a>
				</li>
				<li style="margin-top: 10px;">
					<strong><?php esc_html_e(
         "Create a site in your dashboard",
         "maplepress",
     ); ?></strong><br>
					<span style="color: #666;"><?php esc_html_e(
         "After logging in, create a new site for this WordPress installation.",
         "maplepress",
     ); ?></span>
				</li>
				<li style="margin-top: 10px;">
					<strong><?php esc_html_e(
         "Copy your API URL and API key",
         "maplepress",
     ); ?></strong><br>
					<span style="color: #666;">
						<?php esc_html_e(
          "Your API URL is https://getmaplepress.ca (or your custom backend URL). Your API key will be displayed once - make sure to copy both!",
          "maplepress",
      ); ?>
					</span>
				</li>
				<li style="margin-top: 10px;">
					<strong><?php esc_html_e(
         "Paste your API URL and API key below and save",
         "maplepress",
     ); ?></strong>
				</li>
			</ol>
		</div>
	<?php endif; ?>

	<?php settings_errors("maplepress_settings"); ?>

	<?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 }
 } ?>

	<form method="post" action="options.php">
		<?php
  settings_fields("maplepress_settings_group");
  do_settings_sections("maplepress");
  submit_button(__("Save Settings & Verify Connection", "maplepress"));
  ?>
	</form>

	<?php if ($is_verified): ?>
		<!-- Connection status - show site details -->
		<hr>
		<h2><?php esc_html_e("✓ Connected to MaplePress", "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("Plan", "maplepress"); ?></th>
				<td><strong><?php echo esc_html(
        ucfirst($options["plan_tier"] ?? "free"),
    ); ?></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 (Enable above to activate)",
          "maplepress",
      ); ?></span>
					<?php endif; ?>
				</td>
			</tr>
		</table>

		<?php if (
      isset($options["storage_quota_bytes"]) ||
      isset($options["search_quota_monthly"]) ||
      isset($options["indexing_quota_pages"])
  ): ?>
			<h3><?php esc_html_e("Usage & Quotas", "maplepress"); ?></h3>
			<table class="form-table">
				<?php if (isset($options["storage_quota_bytes"])): ?>
					<tr>
						<th scope="row"><?php esc_html_e("Storage", "maplepress"); ?></th>
						<td>
							<?php
       $used = isset($options["storage_used_bytes"])
           ? $options["storage_used_bytes"]
           : 0;
       $quota = $options["storage_quota_bytes"];
       $used_mb = round($used / 1024 / 1024, 2);
       $quota_mb = round($quota / 1024 / 1024, 2);
       $percent = $quota > 0 ? round(($used / $quota) * 100, 1) : 0;
       ?>
							<strong><?php echo esc_html($used_mb); ?> MB</strong> / <?php echo esc_html(
     $quota_mb,
 ); ?> MB
							<span style="color: <?php echo $percent > 80
           ? "#dc3232"
           : "#46b450"; ?>;">(<?php echo esc_html($percent); ?>% used)</span>
						</td>
					</tr>
				<?php endif; ?>
				<?php if (isset($options["search_quota_monthly"])): ?>
					<tr>
						<th scope="row"><?php esc_html_e("Monthly Searches", "maplepress"); ?></th>
						<td>
							<?php
       $used = isset($options["search_requests_count"])
           ? $options["search_requests_count"]
           : 0;
       $quota = $options["search_quota_monthly"];
       $percent = $quota > 0 ? round(($used / $quota) * 100, 1) : 0;
       ?>
							<strong><?php echo esc_html(
           number_format($used),
       ); ?></strong> / <?php echo esc_html(number_format($quota)); ?>
							<span style="color: <?php echo $percent > 80
           ? "#dc3232"
           : "#46b450"; ?>;">(<?php echo esc_html($percent); ?>% used)</span>
						</td>
					</tr>
				<?php endif; ?>
				<?php if (isset($options["indexing_quota_pages"])): ?>
					<tr>
						<th scope="row"><?php esc_html_e("Monthly Indexing", "maplepress"); ?></th>
						<td>
							<?php
       $used = isset($options["monthly_pages_indexed"])
           ? $options["monthly_pages_indexed"]
           : 0;
       $quota = $options["indexing_quota_pages"];
       $percent = $quota > 0 ? round(($used / $quota) * 100, 1) : 0;
       ?>
							<strong><?php echo esc_html(
           number_format($used),
       ); ?></strong> / <?php echo esc_html(number_format($quota)); ?> pages
							<span style="color: <?php echo $percent > 80
           ? "#dc3232"
           : "#46b450"; ?>;">(<?php echo esc_html(
    $percent,
); ?>% used this month)</span>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e("Total Pages Indexed", "maplepress"); ?></th>
						<td>
							<?php $total = isset($options["total_pages_indexed"])
           ? $options["total_pages_indexed"]
           : 0; ?>
							<strong><?php echo esc_html(number_format($total)); ?></strong> pages (all-time)
						</td>
					</tr>
				<?php endif; ?>
			</table>
		<?php endif; ?>

		<hr>
		<h2><?php esc_html_e("Sync Pages", "maplepress"); ?></h2>
		<p><?php esc_html_e(
      "Sync all your published posts and pages to MaplePress. New posts and pages are automatically synced when published.",
      "maplepress",
  ); ?></p>
		<form method="post" action="<?php echo esc_url(admin_url("admin.php")); ?>">
			<input type="hidden" name="action" value="maplepress_bulk_sync">
			<?php wp_nonce_field("maplepress_bulk_sync"); ?>
			<p>
				<button type="submit" class="button button-primary">
					<?php esc_html_e("Sync All Pages Now", "maplepress"); ?>
				</button>
			</p>
		</form>

		<p>
			<a href="https://getmaplepress.com/dashboard" target="_blank" class="button">
				<?php esc_html_e("→ Open MaplePress Dashboard", "maplepress"); ?>
			</a>
		</p>
	<?php endif; ?>

	<hr>

	<h2><?php esc_html_e("About MaplePress", "maplepress"); ?></h2>
	<p>
		<?php printf(
      /* translators: %s: MaplePress website URL */
      esc_html__(
          "MaplePress is a cloud services platform for WordPress that offloads computationally intensive tasks to dedicated infrastructure. Currently featuring advanced search capabilities, with more services coming soon including uploads, metrics, and analytics. Visit %s to learn more.",
          "maplepress",
      ),
      '<a href="https://mapleopentech.io" target="_blank">https://mapleopentech.io</a>',
  ); ?>
	</p>
</div>
