<?php

namespace Config;

use CodeIgniter\Config\BaseConfig;

class PesaPal extends BaseConfig
{
    /**
     * PesaPal API 3.0 configuration.
     * Override in .env: pesapal.consumer_key, pesapal.consumer_secret, pesapal.environment, etc.
     */

    /** @var string Sandbox base URL (no trailing slash) */
    public string $sandboxBaseUrl = 'https://cybqa.pesapal.com/pesapalv3/api';

    /** @var string Production base URL (no trailing slash) */
    public string $productionBaseUrl = 'https://pay.pesapal.com/v3/api';

    /** @var string Environment: sandbox | production */
    public string $environment = 'sandbox';

    /** @var string Consumer key from PesaPal merchant account */
    public string $consumerKey = '';

    /** @var string Consumer secret from PesaPal merchant account */
    public string $consumerSecret = '';

    /** @var string IPN URL to register with PesaPal (must be publicly reachable). Default: App::$baseURL + pesapal-ipn */
    public string $ipnUrl = '';

    /** @var string Base URL for building callback/cancellation URLs (no trailing slash). Default: App::$baseURL */
    public string $callbackBaseUrl = '';

    /** @var string Default currency for orders (ISO) */
    public string $currency = 'UGX';

    /** @var string|null Pre-registered IPN notification_id (GUID). Set after RegisterIPN or in env. */
    public ?string $notificationId = null;

    /**
     * Optional URL to redirect to when user taps "Close window" on the result page.
     * Used by in-house apps: set to your app's custom scheme so the WebView is closed.
     * Placeholders: {status}, {order_tracking_id}, {merchant_reference}
     * Example: myapp://pesapal-done?status={status}&order_tracking_id={order_tracking_id}&merchant_reference={merchant_reference}
     */
    public string $webviewCloseUrl = '';

    /**
     * Get the API base URL based on environment.
     */
    public function getBaseUrl(): string
    {
        return $this->environment === 'production'
            ? $this->productionBaseUrl
            : $this->sandboxBaseUrl;
    }

    /**
     * Get the application base URL (single source: Config\App::$baseURL).
     * Used for IPN URL, callback URL, and all PesaPal app links.
     */
    public function getAppBaseUrl(): string
    {
        $app = new App();
        return rtrim($app->baseURL ?? 'https://mm.finflo.online/public/', '/');
    }

    /**
     * Get IPN URL. Defaults to getAppBaseUrl() + '/pesapal-ipn' when not set.
     */
    public function getIpnUrl(): string
    {
        if ($this->ipnUrl !== '') {
            return $this->ipnUrl;
        }
        return $this->getAppBaseUrl() . '/pesapal-ipn';
    }

    /**
     * Get callback base URL. Defaults to getAppBaseUrl() when not set.
     */
    public function getCallbackBaseUrl(): string
    {
        if ($this->callbackBaseUrl !== '') {
            return $this->callbackBaseUrl;
        }
        return $this->getAppBaseUrl();
    }

    /**
     * Get WebView close URL with placeholders replaced.
     * Placeholders: {status}, {order_tracking_id}, {merchant_reference}
     */
    public function getWebviewCloseUrl(string $status = '', string $orderTrackingId = '', string $merchantReference = ''): string
    {
        $url = $_ENV['pesapal.webview_close_url'] ?? $this->webviewCloseUrl;
        if ($url === '') {
            return '';
        }
        $url = str_replace('{status}', rawurlencode($status), $url);
        $url = str_replace('{order_tracking_id}', rawurlencode($orderTrackingId), $url);
        $url = str_replace('{merchant_reference}', rawurlencode($merchantReference), $url);
        return $url;
    }
}
