<?php
namespace PayCal\Gateway;

defined('ABSPATH') || exit;

use PayCal\Core\Plugin;

class HostedGateway {
  public static function init(): void {
    add_action('plugins_loaded', [__CLASS__, 'load_gateway'], 20);
  }

  public static function load_gateway(): void {
    if (!class_exists('WooCommerce') || !class_exists('WC_Payment_Gateway')) {
      self::notice('PayCal hosted gateway is waiting for WooCommerce. Activate WooCommerce to use PayCal checkout.');
      \paycal_debug_log('[PayCal] Hosted gateway not loaded because WooCommerce classes are unavailable.');
      return;
    }

    $gateway_file = __DIR__ . '/WC_Gateway_PayCal_Hosted.php';
    if (!file_exists($gateway_file)) {
      self::notice('PayCal hosted gateway file is missing. WooCommerce checkout will continue without PayCal.');
      \paycal_debug_log('[PayCal] Missing hosted gateway file: ' . $gateway_file);
      return;
    }

    try {
      require_once $gateway_file;
    } catch (\Throwable $e) {
      self::notice('PayCal hosted gateway failed to load safely. WooCommerce checkout will continue without PayCal.');
      \paycal_debug_log('[PayCal] Hosted gateway load failed: ' . $e->getMessage());
      return;
    }

    add_filter('woocommerce_payment_gateways', [__CLASS__, 'register_gateway']);
  }

  public static function register_gateway(array $gateways): array {
    if (class_exists(__NAMESPACE__ . '\\WC_Gateway_PayCal_Hosted')) {
      $gateways[] = __NAMESPACE__ . '\\WC_Gateway_PayCal_Hosted';
    }
    return $gateways;
  }

  private static function notice(string $message): void {
    if (class_exists(Plugin::class)) {
      Plugin::register_admin_notice($message);
    }
  }
}
