<?php
namespace PayCal\Modules\Invoices;

defined('ABSPATH') || exit;

use PayCal\Core\Plugin;
class InvoicesModule {
  public static function init(): void {
    if (!class_exists('\WooCommerce')) return;

    if (!defined('PAYCAL_INV_PATH')) define('PAYCAL_INV_PATH', PAYCAL_PATH . 'includes/Modules/Invoices/Legacy/');
    if (!defined('PAYCAL_INV_URL'))  define('PAYCAL_INV_URL',  PAYCAL_URL .  'includes/Modules/Invoices/Legacy/');

    // Back-compat constants used in legacy files.
    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound
    if (!defined('ASP_INV_PATH')) define('ASP_INV_PATH', PAYCAL_INV_PATH);
    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound
    if (!defined('ASP_INV_URL'))  define('ASP_INV_URL',  PAYCAL_INV_URL);

    $files = [
      'includes/render.php',
      'includes/cpt.php',
      'includes/numbering.php',
      'includes/order-hook.php',
      'includes/email.php',
      'includes/pdf/download.php',
      'admin/settings.php',
    ];

    foreach ($files as $file) {
      if (!self::safe_require(PAYCAL_INV_PATH . $file, 'Invoices ' . $file)) {
        self::notice('PayCal invoices module could not load all required files. The rest of the site continues to run.');
        return;
      }
    }
  }

  private static function safe_require(string $file, string $label): bool {
    if (!file_exists($file)) {
      self::notice('PayCal: ' . $label . ' is missing.');
      \paycal_debug_log('[PayCal] Missing file: ' . $file);
      return false;
    }

    try {
      require_once $file;
      return true;
    } catch (\Throwable $e) {
      self::notice('PayCal: ' . $label . ' failed to load safely.');
      \paycal_debug_log('[PayCal] Failed loading ' . $file . ': ' . $e->getMessage());
      return false;
    }
  }

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