<?php

namespace PloverCRM\Common;

/**
 * License Cron
 * 
 * Daily revalidation of the license token against plovercrm.com.
 * If the license is invalid/expired, shows an admin notice.
 */
class LicenseCron
{
  public static function init(): void
  {
    add_action('plover_crm_license_revalidate', [self::class, 'revalidate']);

    if (!wp_next_scheduled('plover_crm_license_revalidate')) {
      wp_schedule_event(time(), 'twicedaily', 'plover_crm_license_revalidate');
    }

    // Recheck on admin page loads when cache has expired
    add_action('admin_init', [self::class, 'maybeRevalidateOnAdmin']);

    // Show notice if license is invalid
    add_action('admin_notices', [self::class, 'maybeShowNotice']);
  }

  /**
   * Lightweight recheck on admin load — only fires when the transient has expired
   */
  public static function maybeRevalidateOnAdmin(): void
  {
    // Only run if cache is already expired (transient gone)
    if (get_transient(LicenseChecker::TRANSIENT_KEY) === 'valid') {
      return;
    }

    $license = LicenseChecker::getLicense();
    if (empty($license['token'])) {
      return;
    }

    // Revalidate — this sets the transient if valid
    LicenseChecker::isValid();
  }

  /**
   * Daily revalidation
   */
  public static function revalidate(): void
  {
    $license = LicenseChecker::getLicense();

    if (empty($license['token'])) {
      delete_transient(LicenseChecker::TRANSIENT_KEY);
      return;
    }

    $result = LicenseChecker::validateRemote($license['token']);

    if ($result && !empty($result['valid'])) {
      set_transient(LicenseChecker::TRANSIENT_KEY, 'valid', LicenseChecker::CACHE_DURATION);
      LicenseChecker::updateLicense([
        'plan'         => $result['plan'] ?? '',
        'expires'      => $result['expires'] ?? '',
        'entitlements' => is_array($result['entitlements'] ?? null) ? $result['entitlements'] : [],
      ]);
    } else {
      delete_transient(LicenseChecker::TRANSIENT_KEY);
    }
  }

  /**
   * Show admin notice if no valid license
   */
  public static function maybeShowNotice(): void
  {
    if (!current_user_can('manage_options')) return;

    $license = LicenseChecker::getLicense();

    // Only show notice if license exists but validation failed
    if (!empty($license['token'])) {
      $cached = get_transient(LicenseChecker::TRANSIENT_KEY);
      if ($cached !== 'valid') {
        $url = admin_url('admin.php?page=plover-crm-license');
        echo '<div class="notice notice-error"><p>';
        echo '<strong>PloverCRM:</strong> Your license could not be verified. ';
        echo '<a href="' . esc_url($url) . '">Check your license</a>.';
        echo '</p></div>';
      }
    }
  }
}
