<?php

namespace App\Modules\Payment\CashU;

use App\Core\Payment\AbstractPayment;

class CashU extends AbstractPayment
{
    // Ref: WHMCS gateways/cashu.php:29 — tek canonical action URL (POST form)
    protected $paymentUrl = 'https://www.cashu.com/cgi-bin/pcashu.cgi';

    public function __construct(array $config = [])
    {
        parent::__construct($config);
    }

    /**
     * Validate payment parameters and return readiness status
     *
     * @return array
     */
    public function attemptPayment(array $params)
    {
        $requiredParams = ['amount', 'currency', 'order_id'];

        foreach ($requiredParams as $param) {
            if (! isset($params[$param]) || empty($params[$param])) {
                return [
                    'status' => 'error',
                    'message' => __('admin/modules.cashu_missing_param', ['param' => $param]),
                ];
            }
        }

        if ($params['amount'] <= 0) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.cashu_invalid_amount'),
            ];
        }

        return [
            'status' => 'ready',
            'message' => __('admin/modules.cashu_ready'),
            'data' => [
                'payment_method' => 'cashu',
                'amount' => $params['amount'],
                'currency' => $params['currency'],
                'order_id' => $params['order_id'],
            ],
        ];
    }

    /**
     * Build CashU redirect form parameters and return redirect URL
     *
     * @return array
     */
    public function makePayment(array $params)
    {
        return [
            'status' => 'redirect',
            'message' => __('admin/modules.cashu_redirect'),
            'redirect_url' => $this->paymentUrl,
            'method' => 'POST',
            // Ref: WHMCS gateways/cashu.php:29 — POST form alanları (merchant_id/token/
            // display_text/currency/amount/language/email/session_id/txt1[,test_mode])
            'data' => $this->buildRequestFields($params),
        ];
    }

    /**
     * Build CashU POST form fields (WHMCS gateways/cashu.php:29 birebir).
     */
    private function buildRequestFields(array $params): array
    {
        $merchantId = $this->getConfig('merchant_id');
        $currency = $params['currency'] ?? $this->getConfig('currency', 'USD');
        $amount = number_format($params['amount'], 2, '.', '');
        $sessionId = $params['order_id'];
        $language = $this->getConfig('language', 'en');
        $displayText = $params['description'] ?? __('admin/modules.cashu_order_description', ['order_id' => $params['order_id']]);

        $fields = [
            'merchant_id' => $merchantId,
            'token' => $this->generateToken($merchantId, $amount, $currency),
            'display_text' => $displayText,
            'currency' => $currency,
            'amount' => $amount,
            'language' => $language,
            'email' => $params['customer_email'] ?? '',
            'session_id' => $sessionId,
            'txt1' => $params['invoice_id'] ?? $params['order_id'],
        ];

        // Ref: WHMCS gateways/cashu.php:30-31 — ayrı test URL yok, test_mode=1 alanı
        if ($this->isTestMode()) {
            $fields['test_mode'] = '1';
        }

        return $fields;
    }

    /**
     * Validate CashU IPN/return notification and process payment result.
     *
     * FAIL-CLOSED imza doğrulaması (Ref: WHMCS callback/cashu.php:22-24):
     *   verificationString = sha1(strtolower(merchant_id):strtolower(trn_id):encryption_keyword)
     * trn_id = transaction id; amount/currency hash'e GİRMEZ. Tek başarı yolu var.
     *
     * @return array
     */
    public function handlePaymentCallback(array $params)
    {
        $merchantId = (string) $this->getConfig('merchant_id');
        $encryptionKey = (string) $this->getConfig('encryption_key');
        $trnId = (string) ($params['trn_id'] ?? '');
        $received = $params['verificationString'] ?? null;

        $expected = sha1(strtolower($merchantId).':'.strtolower($trnId).':'.$encryptionKey);

        // FAIL-CLOSED: geçersiz/eksik imza → ödeme ASLA başarılı sayılmaz.
        if (! $this->secureCompare($expected, is_string($received) ? $received : null)) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.cashu_invalid_token'),
            ];
        }

        return [
            'status' => 'success',
            'message' => __('admin/modules.cashu_payment_success'),
            'transaction_id' => $trnId,
            'data' => [
                'transaction_id' => $trnId,
                'amount' => $params['amount'] ?? '',
                'currency' => $params['currency'] ?? '',
                'session_id' => $params['session_id'] ?? '',
            ],
        ];
    }

    /**
     * Refund is not supported by CashU gateway
     *
     * @return array
     */
    public function refundPayment(array $params)
    {
        return [
            'status' => 'error',
            'message' => __('admin/modules.cashu_refund_not_supported'),
        ];
    }

    /**
     * Generate a CashU payment URL with pre-filled parameters
     *
     * @return array
     */
    public function generatePaymentLink(array $params)
    {
        // CashU canonical akışı POST form (Ref: WHMCS gateways/cashu.php:29).
        // Hassas token'ı GET query-string'e KOYMA (log/referer sızıntısı) — POST
        // form alanı olarak döndür; caller auto-submit form ile yönlendirir.
        return [
            'status' => 'success',
            'payment_url' => $this->paymentUrl,
            'method' => 'POST',
            'data' => $this->buildRequestFields($params),
        ];
    }

    /**
     * Test connection by validating configuration
     *
     * CashU does not provide a dedicated API endpoint for connection testing,
     * so we validate that all required configuration fields are present.
     *
     * @return array
     */
    public function testConnection(array $params = [])
    {
        $configValidation = $this->validateConfig();

        if ($configValidation['status'] !== 'success') {
            return [
                'status' => 'error',
                'message' => __('admin/modules.cashu_connection_failed'),
                'data' => $configValidation,
            ];
        }

        // CashU dedike reachability endpoint'i sunmaz; yalnız config doğrulanır.
        return [
            'status' => 'success',
            'message' => __('admin/modules.cashu_config_valid'),
            'data' => [
                'payment_url' => $this->paymentUrl,
                'test_mode' => $this->isTestMode(),
            ],
        ];
    }

    /**
     * Validate required configuration fields
     *
     * @return array
     */
    public function validateConfig()
    {
        $required = ['merchant_id', 'encryption_key'];
        $missing = [];

        foreach ($required as $field) {
            if (empty($this->config[$field])) {
                $missing[] = $field;
            }
        }

        if (! empty($missing)) {
            return [
                'status' => 'error',
                'message' => __('admin/modules.cashu_missing_config', ['fields' => implode(', ', $missing)]),
            ];
        }

        return [
            'status' => 'success',
            'message' => __('admin/modules.cashu_config_valid'),
        ];
    }

    /**
     * CashU supported features
     */
    public function getFeatures(): array
    {
        return [
            'refund' => false,
            '3d_secure' => false,
            'save_card' => false,
            'recurring' => false,
            'fraud_check' => false,
        ];
    }

    /**
     * Return supported features (alias for AbstractPayment compatibility)
     */
    public function getSupportedFeatures(): array
    {
        return $this->getFeatures();
    }

    /**
     * Get configuration fields for admin panel
     */
    public function getConfigFields(): array
    {
        return array_merge(parent::getConfigFields(), [
            'merchant_id' => [
                'type' => 'text',
                'label' => __('admin/modules.cashu_merchant_id'),
                'description' => __('admin/modules.cashu_merchant_id_desc'),
                'required' => true,
                'value' => '',
                'placeholder' => __('admin/modules.cashu_merchant_id_placeholder'),
            ],
            'encryption_key' => [
                'type' => 'password',
                'label' => __('admin/modules.cashu_encryption_key'),
                'description' => __('admin/modules.cashu_encryption_key_desc'),
                'required' => true,
                'value' => '',
                'placeholder' => '',
            ],
            'currency' => [
                'type' => 'select',
                'label' => __('admin/modules.cashu_currency'),
                'description' => __('admin/modules.cashu_currency_desc'),
                'required' => true,
                'value' => 'USD',
                'options' => [
                    'USD' => 'USD - US Dollar',
                    'EUR' => 'EUR - Euro',
                    'AED' => 'AED - UAE Dirham',
                    'SAR' => 'SAR - Saudi Riyal',
                    'EGP' => 'EGP - Egyptian Pound',
                    'JOD' => 'JOD - Jordanian Dinar',
                    'KWD' => 'KWD - Kuwaiti Dinar',
                    'QAR' => 'QAR - Qatari Riyal',
                    'BHD' => 'BHD - Bahraini Dinar',
                ],
            ],
            'language' => [
                'type' => 'select',
                'label' => __('admin/modules.cashu_language'),
                'description' => __('admin/modules.cashu_language_desc'),
                'required' => false,
                'value' => 'en',
                'options' => [
                    'en' => 'English',
                    'ar' => 'Arabic',
                ],
            ],
        ]);
    }

    /**
     * Generate CashU request token.
     *
     * Ref: WHMCS gateways/cashu.php:28 —
     *   md5(merchant_id:amount:strtolower(currency):encryption_keyword)
     * session_id token'a GİRMEZ; currency KÜÇÜK-HARF; sadece 4 alan.
     */
    private function generateToken(string $merchantId, string $amount, string $currency): string
    {
        $encryptionKey = (string) $this->getConfig('encryption_key');

        return md5($merchantId.':'.$amount.':'.strtolower($currency).':'.$encryptionKey);
    }
}
