<?php

namespace PloverCRM\Common;

/**
 * Update Checker
 * 
 * Hooks into WordPress plugin update system to check for updates
 * via the PloverCRM Hub API instead of wordpress.org.
 */
class UpdateChecker
{
  const PLUGIN_SLUG = 'plover-crm';
  const PLUGIN_FILE = 'plover-crm/plover-crm.php';
  const CHECK_INTERVAL = 12 * HOUR_IN_SECONDS;

  public static function init(): void
  {
    add_filter('pre_set_site_transient_update_plugins', [self::class, 'checkForUpdate']);
    add_filter('plugins_api', [self::class, 'pluginInfo'], 10, 3);
  }

  /**
   * Check for plugin updates via hub API
   */
  public static function checkForUpdate($transient)
  {
    if (empty($transient->checked)) {
      return $transient;
    }

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

    $currentVersion = $transient->checked[self::PLUGIN_FILE] ?? PLOVER_CRM_PLUGIN_VERSION;

    // Rate limit checks
    $lastCheck = get_option('plover_crm_update_last_check', 0);
    if ((time() - $lastCheck) < self::CHECK_INTERVAL) {
      $cached = get_option('plover_crm_update_data');
      if (
        $cached
        && ($cached['checked_version'] ?? '') === $currentVersion
        && !empty($cached['update_available'])
      ) {
        $transient->response[self::PLUGIN_FILE] = self::buildUpdateObject($cached);
      } elseif ($cached && ($cached['checked_version'] ?? '') === $currentVersion) {
        unset($transient->response[self::PLUGIN_FILE]);
        $transient->no_update[self::PLUGIN_FILE] = self::buildUpdateObject($cached);
      }
      return $transient;
    }

    update_option('plover_crm_update_last_check', time());

    $response = wp_remote_post(LicenseChecker::getHubUrl() . '/wp-json/plovercrm-hub/v1/update-check', [
      'body'    => [
        'token'   => $license['token'],
        'version' => $currentVersion,
      ],
      'timeout' => 15,
    ]);

    if (is_wp_error($response)) {
      return $transient;
    }

    $data = json_decode(wp_remote_retrieve_body($response), true);

    if (!is_array($data) || !empty($data['error'])) {
      return $transient;
    }

    $data['checked_version'] = $currentVersion;
    update_option('plover_crm_update_data', $data);

    if (!empty($data['update_available'])) {
      $transient->response[self::PLUGIN_FILE] = self::buildUpdateObject($data);
    } else {
      // No update — make sure it's not in the response
      unset($transient->response[self::PLUGIN_FILE]);
      $transient->no_update[self::PLUGIN_FILE] = self::buildUpdateObject($data);
    }

    return $transient;
  }

  /**
   * Build the update object WordPress expects
   */
  private static function buildUpdateObject(array $data): object
  {
    return (object) [
      'slug'         => self::PLUGIN_SLUG,
      'plugin'       => self::PLUGIN_FILE,
      'new_version'  => $data['version'] ?? '1.0.0',
      'url'          => LicenseChecker::getHubUrl(),
      'package'      => $data['download_url'] ?? '',
      'requires'     => $data['requires'] ?? '6.0',
      'requires_php' => $data['requires_php'] ?? '7.4',
      'tested'       => $data['tested'] ?? '',
    ];
  }

  /**
   * Provide plugin info for the "View Details" modal
   */
  public static function pluginInfo($result, $action, $args)
  {
    if ($action !== 'plugin_information' || ($args->slug ?? '') !== self::PLUGIN_SLUG) {
      return $result;
    }

    $data = get_option('plover_crm_update_data');
    if (!$data) {
      return $result;
    }

    return (object) [
      'name'          => $data['name'] ?? 'PloverCRM',
      'slug'          => self::PLUGIN_SLUG,
      'version'       => $data['version'] ?? '1.0.0',
      'author'        => '<a href="https://plovercrm.com">PloverCRM</a>',
      'homepage'      => LicenseChecker::getHubUrl(),
      'download_link' => $data['download_url'] ?? '',
      'requires'      => $data['requires'] ?? '6.0',
      'requires_php'  => $data['requires_php'] ?? '7.4',
      'tested'        => $data['tested'] ?? '',
      'sections'      => [
        'description' => 'A powerful CRM plugin for WordPress with mobile app integration.',
      ],
    ];
  }
}
