<?php
use Comator\Payments\ProviderFactory;

require_once __DIR__ . '/../../comator/modules/orders/includes/payments/autoload.php';
require_once __DIR__ . '/../../comator/modules/orders/includes/payments/vendor/autoload.php';

final class FrontendPaymentBridge {
	
	public static function preCapture(PDO $pdo, Orders $orders, string $provider_key, string $session_id, ?string $language = null): array {
    $provider = ProviderFactory::make($pdo, $orders, $provider_key);
    if (!$provider) return ['type' => 'error', 'note' => 'payment.provider_missing'];
    if (!method_exists($provider, 'preCapture')) {
      return ['type' => 'error', 'note' => 'payment.precapture_unsupported'];
    }
    return $provider->preCapture($session_id, $language);
	}
	
	public static function captureApproved(PDO $pdo, Orders $orders, string $provider_key, int $id_order, string $provider_ref): bool {
    $provider = ProviderFactory::make($pdo, $orders, $provider_key);
    if (!$provider || !method_exists($provider, 'captureApproved')) return false;
    $res = $provider->captureApproved($id_order, $provider_ref);
    return !empty($res['ok']);
  }
	
  public static function startCheckout(PDO $pdo, Orders $orders, string $provider_key, int $id_order, string $session_id, ?string $language = null): array {
    $provider = ProviderFactory::make($pdo, $orders, $provider_key);
    if (!$provider) return ['type' => 'error', 'note' => 'payment.provider_missing'];
    return $provider->startCheckout($id_order, $session_id, $language);
  }

  public static function handleReturn(PDO $pdo, Orders $orders, string $provider_key, array $query, ?string $language = null): array {
    $provider = ProviderFactory::make($pdo, $orders, $provider_key);
    if (!$provider) return ['ok' => false, 'note' => 'payment.provider_missing'];
    return $provider->handleReturn($query, $language);
  }

  public static function handleWebhook(PDO $pdo, Orders $orders, string $provider_key): void {
    $provider = ProviderFactory::make($pdo, $orders, $provider_key);
    if ($provider) $provider->handleWebhook();
  }
}
