<?php

namespace App\Modules\Payment\Shopier;

use App\Core\Payment\AbstractPayment;

/**
 * Shopier — redirect/hosted ödeme (form-POST). Kanonik sözleşme WiseCP çalışan
 * referansından birebir: get_form_data (imza: random_nr.platform_order_id.
 * total_order_value.currency, binary HMAC-SHA256 → base64) + payment_result
 * (status/platform_order_id/signature/random_nr; expected=binary hmac(random_nr.
 * platform_order_id)). Ref: ~/Downloads/wisecp.../Payment/Shopier/Shopier.php.
 */
class Shopier extends AbstractPayment
{
    // WiseCP config.php: payment_url. .php uzantısı ZORUNLU (redirect form action).
    protected $apiUrl = 'https://www.shopier.com/ShowProduct/api_pay4.php';

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

    /**
     * Ödeme ön-koşullarını doğrular. Sözleşme zarfı success|error|pending.
     * Kritik alanlar: amount>0 + platform_order_id (invoice_id) + currency + buyer email.
     */
    public function attemptPayment(array $params)
    {
        $orderId = $params['invoice_id'] ?? $params['order_id'] ?? null;
        $email = $params['customer_email'] ?? $params['buyer_email'] ?? null;
        $amount = $params['amount'] ?? null;

        if (empty($orderId)) {
            return ['status' => 'error', 'message' => 'Missing required parameter: invoice_id'];
        }
        if (empty($email)) {
            return ['status' => 'error', 'message' => 'Missing required parameter: customer_email'];
        }
        if ($amount === null || (float) $amount <= 0) {
            return ['status' => 'error', 'message' => 'Amount must be greater than zero'];
        }

        return [
            'status' => 'success',
            'message' => 'Payment is ready to proceed via Shopier',
            'data' => [
                'payment_method' => 'shopier',
                'platform_order_id' => (string) $orderId,
                'amount' => number_format((float) $amount, 2, '.', ''),
            ],
        ];
    }

    /**
     * Shopier redirect form-POST verilerini üretir. WiseCP get_form_data alan seti +
     * imza formülü birebir. Transport: form-POST (callApi'ye dokunmaz).
     */
    public function makePayment(array $params)
    {
        $apiKey = $this->getConfig('api_key');
        $apiSecret = $this->getConfig('api_secret');

        if (empty($apiKey) || empty($apiSecret)) {
            return ['status' => 'error', 'message' => 'Shopier API credentials are not configured'];
        }

        $platformOrderId = (string) ($params['invoice_id'] ?? $params['order_id'] ?? '');
        if ($platformOrderId === '') {
            return ['status' => 'error', 'message' => 'Missing platform_order_id (invoice_id) for Shopier payment'];
        }

        // Shopier currency: 0=TRY, 1=USD, 2=EUR (WiseCP payform get_form_data:80-82).
        $currencyMap = ['TRY' => 0, 'USD' => 1, 'EUR' => 2];
        $currencyCode = strtoupper((string) ($params['currency'] ?? 'TRY'));
        $currency = $currencyMap[$currencyCode] ?? 0;

        // WiseCP: total_order_value = number_format(total, 2, '.', '') — cent DEĞİL, decimal string.
        $totalOrderValue = number_format((float) ($params['amount'] ?? 0), 2, '.', '');

        $buyerName = $params['customer_name'] ?? $params['buyer_name'] ?? '';
        $buyerSurname = $params['customer_surname'] ?? $params['buyer_surname'] ?? '';
        $buyerEmail = $params['customer_email'] ?? $params['buyer_email'] ?? '';
        $buyerPhone = $params['customer_phone'] ?? $params['buyer_phone'] ?? '';
        $billing = $params['billing_address'] ?? [];

        $randomNr = (string) rand(100000, 999999);

        // WiseCP get_form_data alan seti (:91-119) birebir.
        $formData = [
            'API_key' => $apiKey,
            'website_index' => 1,
            'platform_order_id' => $platformOrderId,
            'product_name' => $params['product_name'] ?? ('Invoice #'.$platformOrderId),
            'product_type' => 1,
            'buyer_name' => $buyerName,
            'buyer_surname' => $buyerSurname,
            'buyer_email' => $buyerEmail,
            'buyer_account_age' => $params['buyer_account_age'] ?? 0,
            'buyer_id_nr' => (string) ($params['customer_id'] ?? $params['buyer_id_nr'] ?? ''),
            'buyer_phone' => $buyerPhone,
            'billing_address' => $billing['address1'] ?? '',
            'billing_city' => $billing['city'] ?? '',
            'billing_country' => $billing['country'] ?? '',
            'billing_postcode' => $billing['postcode'] ?? '',
            'shipping_address' => 'NA',
            'shipping_city' => 'NA',
            'shipping_country' => 'NA',
            'shipping_postcode' => 'NA',
            'total_order_value' => $totalOrderValue,
            'currency' => $currency,
            'current_language' => 0,
            'modul_version' => '1.0.0',
            'version' => false,
            'platform' => 4,
            'is_in_frame' => 0,
            'random_nr' => $randomNr,
        ];

        // WiseCP imza (get_form_data:121-124): random_nr . platform_order_id .
        // total_order_value . currency → binary HMAC-SHA256 → base64.
        $signatureData = $randomNr.$platformOrderId.$totalOrderValue.$currency;
        $formData['signature'] = base64_encode($this->hmac('sha256', $signatureData, $apiSecret, true));

        return [
            'status' => 'redirect',
            'message' => 'Redirecting to Shopier payment page',
            'redirect_url' => $this->apiUrl,
            'form_data' => $formData,
            'method' => 'POST',
        ];
    }

    /**
     * Shopier callback'ini işler. WiseCP payment_result (:133-176) field/veri/encoding
     * birebir. İmza FAIL-CLOSED (secureCompare/hash_equals; imza yok/gecersiz → error).
     */
    public function handlePaymentCallback(array $params)
    {
        $apiSecret = $this->getConfig('api_secret');

        if (empty($apiSecret)) {
            return ['status' => 'error', 'message' => 'API secret is not configured'];
        }

        // WiseCP payment_result:134-137 — gerçek Shopier callback alanları.
        $status = $params['status'] ?? '';
        $platformOrderId = (string) ($params['platform_order_id'] ?? '');
        $signature = $params['signature'] ?? '';
        $randomNr = (string) ($params['random_nr'] ?? '');

        if ($signature === '' || $randomNr === '' || $platformOrderId === '') {
            return ['status' => 'error', 'message' => 'Missing callback signature data'];
        }

        // WiseCP payment_result:148-150 — expected = binary hmac(random_nr.platform_order_id);
        // gelen signature base64_decode edilir; ham binary'ler secureCompare ile (fail-closed).
        $expected = $this->hmac('sha256', $randomNr.$platformOrderId, $apiSecret, true);
        $received = base64_decode($signature, true);

        if ($received === false || ! $this->secureCompare(base64_encode($expected), base64_encode($received))) {
            return ['status' => 'error', 'message' => 'Invalid callback signature'];
        }

        if (strtolower((string) $status) === 'success') {
            return [
                'status' => 'success',
                'message' => 'Payment completed successfully via Shopier',
                'transaction_id' => $platformOrderId,
                'platform_order_id' => $platformOrderId,
                'data' => $params,
            ];
        }

        return [
            'status' => 'failed',
            'message' => 'Payment was not successful',
            'transaction_id' => $platformOrderId,
            'platform_order_id' => $platformOrderId,
            'data' => $params,
        ];
    }

    /**
     * Shopier API iade sunmaz — net unsupported (sahte-success YOK).
     */
    public function refundPayment(array $params)
    {
        return [
            'status' => 'error',
            'message' => 'Shopier does not support API refunds. Please process the refund manually through the Shopier dashboard.',
        ];
    }

    /**
     * Redirect form-POST döndürür (Shopier'de tek-URL GET link yok; WiseCP payform
     * otomatik-submit POST). makePayment'ı sarmalar.
     */
    public function generatePaymentLink(array $params)
    {
        $paymentResult = $this->makePayment($params);

        if (($paymentResult['status'] ?? '') === 'redirect') {
            return [
                'status' => 'success',
                'payment_url' => $paymentResult['redirect_url'],
                'form_data' => $paymentResult['form_data'],
                'method' => 'POST',
            ];
        }

        return $paymentResult;
    }

    /**
     * Shopier'de auth/ping REST endpoint'i yok (redirect-only) → cred VARLIK kontrolü.
     * Bağlantı doğrulandığı iddia edilmez (yalnızca "credentials present").
     */
    public function testConnection(array $params = [])
    {
        $apiKey = $this->getConfig('api_key');
        $apiSecret = $this->getConfig('api_secret');

        if (empty($apiKey) || empty($apiSecret)) {
            return [
                'status' => 'error',
                'message' => 'Shopier API credentials are missing. Please configure API Key and API Secret.',
            ];
        }

        return [
            'status' => 'success',
            'message' => 'Shopier API credentials are present. Shopier has no verification endpoint (redirect-only); a live round-trip cannot be validated here.',
        ];
    }

    /**
     * Konfigürasyon doğrulama
     */
    public function validateConfig()
    {
        $required = ['api_key', 'api_secret'];
        $missing = [];

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

        if (! empty($missing)) {
            return [
                'status' => 'error',
                'message' => 'Missing required fields: '.implode(', ', $missing),
            ];
        }

        return ['status' => 'success', 'message' => 'Configuration is valid'];
    }

    /**
     * Modülün desteklediği özellikleri döndürür. Shopier redirect/hosted:
     * refund/3DS/save_card/recurring desteklenmez.
     */
    public function getFeatures(): array
    {
        return [
            'refund' => false,
            '3d_secure' => false,
            'save_card' => false,
            'recurring' => false,
            'fraud_check' => false,
        ];
    }

    /**
     * Get configuration fields for admin panel
     */
    public function getConfigFields(): array
    {
        return array_merge(parent::getConfigFields(), [
            'api_key' => [
                'type' => 'text',
                'label' => 'API Key',
                'description' => 'Shopier API key',
                'required' => true,
                'value' => '',
                'placeholder' => 'Enter Shopier API key',
            ],
            'api_secret' => [
                'type' => 'password',
                'label' => 'API Secret',
                'description' => 'Shopier API secret',
                'required' => true,
                'value' => '',
                'placeholder' => 'Enter Shopier API secret',
            ],
        ]);
    }

    public function getSupportedFeatures(): array
    {
        return $this->getFeatures();
    }
}
