<?php

namespace PloverCRM\Common;

/**
 * License Settings Page
 * 
 * Renders the license activation UI in WP Admin.
 * Single flow: "Connect & Activate" — OAuth redirect to plovercrm.com
 */
class LicensePage
{
  public static function init(): void
  {
    add_action('admin_menu', [self::class, 'addMenu'], 99);
    add_action('admin_init', [self::class, 'handleActions']);
    add_action('template_redirect', [self::class, 'handleFrontendCallback']);
  }

  public static function addMenu(): void
  {
    // When unlicensed, the main menu already points to this page (slug: plover-crm-license)
    // so we don't need a separate submenu. Only add as submenu when licensed.
    if (!LicenseChecker::isValid()) {
      return;
    }

    add_submenu_page(
      'plover-crm',
      'License',
      'License',
      'manage_options',
      'plover-crm-license',
      [self::class, 'render']
    );
  }

  /**
   * Handle form submissions and OAuth callback
   */
  public static function handleActions(): void
  {
    if (!current_user_can('manage_options')) return;

    $page = $_GET['page'] ?? '';
    if ($page !== 'plover-crm-license') return;

    $action = $_GET['action'] ?? $_POST['action'] ?? '';

    // Deactivate
    if ($action === 'deactivate') {
      check_admin_referer('plovercrm_deactivate');
      LicenseChecker::deactivate();
      wp_redirect(admin_url('admin.php?page=plover-crm-license&deactivated=1'));
      exit;
    }
  }

  /**
   * Handle the front-end activation callback and return users to their site.
   */
  public static function handleFrontendCallback(): void
  {
    if (is_admin() || empty($_GET[LicenseChecker::CALLBACK_QUERY_VAR])) {
      return;
    }

    $params = wp_unslash($_GET);
    $state = sanitize_text_field($params[LicenseChecker::CALLBACK_STATE_QUERY_VAR] ?? '');

    if (!LicenseChecker::consumeCallbackState($state)) {
      wp_safe_redirect(admin_url('admin.php?page=plover-crm-license&error=' . urlencode('Your activation session expired. Please try again.')));
      exit;
    }

    $result = LicenseChecker::handleCallback($params);
    if ($result['success']) {
      wp_safe_redirect(LicenseChecker::getPostActivationUrl($params));
      exit;
    }

    wp_safe_redirect(admin_url('admin.php?page=plover-crm-license&error=' . urlencode($result['error'])));
    exit;
  }

  public static function render(): void
  {
    $licenseStatus = LicenseChecker::getStatus();
    $license = LicenseChecker::getLicense();
    $isActive = $licenseStatus['is_active'];
    $hasStoredActivation = !empty($license['token']);
    $authUrl = LicenseChecker::getAuthUrl();
    $seatUsage = LicenseChecker::getCrmUserSeatUsage();
    $statusLabel = $licenseStatus['label'] ?? ($isActive ? 'Active' : 'Inactive');
    $statusMessage = $licenseStatus['message'] ?? '';
?>
    <div class="wrap">
      <h1>PloverCRM License</h1>

      <?php if (!empty($_GET['activated'])): ?>
        <div class="notice notice-success">
          <p>License activated successfully.</p>
        </div>
      <?php endif; ?>
      <?php if (!empty($_GET['deactivated'])): ?>
        <div class="notice notice-info">
          <p>License deactivated.</p>
        </div>
      <?php endif; ?>
      <?php if (!empty($_GET['error'])): ?>
        <div class="notice notice-error">
          <p><?php echo esc_html(sanitize_text_field($_GET['error'])); ?></p>
        </div>
      <?php endif; ?>

      <?php if ($isActive): ?>
        <!-- Active License -->
        <div style="background:#fff; border:1px solid #c3c4c7; border-left:4px solid #00a32a; padding:20px; margin-top:20px; max-width:600px;">
          <h2 style="margin-top:0;">✓ License Active</h2>
          <table class="form-table" style="margin:0;">
            <tr>
              <th style="padding:8px 10px 8px 0;">Plan</th>
              <td style="padding:8px 0;"><?php echo esc_html(ucfirst($license['plan'] ?: 'Unknown')); ?></td>
            </tr>
            <?php if (!empty($license['expires'])): ?>
              <tr>
                <th style="padding:8px 10px 8px 0;">Expires</th>
                <td style="padding:8px 0;"><?php echo esc_html(date('F j, Y', strtotime($license['expires']))); ?></td>
              </tr>
            <?php endif; ?>
            <tr>
              <th style="padding:8px 10px 8px 0;">Activated</th>
              <td style="padding:8px 0;"><?php echo esc_html($license['activated_at'] ? date('F j, Y', strtotime($license['activated_at'])) : '—'); ?></td>
            </tr>
            <?php if (!empty($seatUsage['is_limited'])): ?>
              <tr>
                <th style="padding:8px 10px 8px 0;">Assigned CRM Users</th>
                <td style="padding:8px 0;"><?php echo esc_html($seatUsage['used'] . ' / ' . $seatUsage['limit']); ?></td>
              </tr>
            <?php endif; ?>
          </table>

          <div style="margin-top:15px; padding-top:15px; border-top:1px solid #eee;">
            <form method="post" style="display:inline;">
              <input type="hidden" name="action" value="deactivate">
              <?php wp_nonce_field('plovercrm_deactivate'); ?>
              <button type="submit" class="button" onclick="return confirm('Disconnect this site from your PloverCRM account? You can reconnect later.');">
                Disconnect License
              </button>
            </form>
            <a href="<?php echo esc_url(LicenseChecker::getDashboardUrl()); ?>" target="_blank" class="button" style="margin-left:8px;">
              Manage Account →
            </a>
          </div>
        </div>

      <?php else: ?>
        <!-- No License -->
        <div style="max-width:600px; margin-top:20px;">
          <?php if ($hasStoredActivation): ?>
            <div style="background:#fff7ed; border:1px solid #fed7aa; border-left:4px solid #f59e0b; padding:18px 20px; margin-bottom:16px;">
              <h2 style="margin-top:0;"><?php echo esc_html($statusLabel); ?></h2>
              <p style="margin-bottom:0;"><?php echo esc_html($statusMessage); ?></p>
            </div>
          <?php endif; ?>

          <!-- Connect Account -->
          <div style="background:#fff; border:1px solid #c3c4c7; padding:24px;">
            <h2 style="margin-top:0;"><?php echo $hasStoredActivation ? 'Reconnect Your Account' : 'Connect Your Account'; ?></h2>
            <p>Connect your PloverCRM account to activate this site and receive updates.</p>
            <a href="<?php echo esc_url($authUrl); ?>" class="button button-primary button-hero">
              <?php echo $hasStoredActivation ? 'Reconnect License' : 'Connect & Activate'; ?>
            </a>
            <p class="description" style="margin-top:10px;">You'll be redirected to plovercrm.com to log in and select your subscription.</p>
            <?php if ($hasStoredActivation): ?>
              <p style="margin-top:16px;">
                <a href="<?php echo esc_url(LicenseChecker::getDashboardUrl()); ?>" target="_blank" class="button">
                  Manage Account →
                </a>
              </p>
            <?php endif; ?>
          </div>
        </div>
      <?php endif; ?>
    </div>
<?php
  }
}
