<?php

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

/**
 * Render the dashboard page
 */
function content_craft_ai_render_dashboard_page()
{
  // Check authentication status
  $token = get_option('content_craft_ai_token');
  if (empty($token)) {
    // Redirect to auth page if not authenticated
    wp_redirect(admin_url('admin.php?page=content-craft-ai'));
    exit;
  }

  // Get auth status - we'll rely on the global auth check for redirects
  $user = content_craft_ai_check_auth();

  // Check if authenticated - don't redirect here, just exit
  if (!$user) {
    // This is a fallback - the auth-check.php should handle this redirect already
    // Just return without rendering anything
    return;
  }

  // User is authenticated, show dashboard
  // Ensure the script is enqueued
  wp_enqueue_script('content-craft-ai-admin');

  // Add data as JSON in window object
  wp_localize_script(
    'content-craft-ai-admin',
    'contentCraftAIData',
    array_merge(
      (array) wp_scripts()->get_data('content-craft-ai-admin', 'data'),
      array(
        'page' => 'dashboard',
        'user' => $user,
        'wpApiUrl' => rest_url('content-craft-ai/v1'),
        'nonce' => wp_create_nonce('wp_rest'),
        'siteUrl' => get_site_url(),
        'adminUrl' => admin_url()
      )
    )
  );

  // Render the app container
  echo '<div id="content-craft-ai-app"></div>';
}
