<?php

namespace App\Payment\Perfectmoney;

use App\Facades\TransactionFacade as Transaction;
use App\Models\PaymentGateway;
use App\Payment\PaymentGateway as PaymentGatewayInterface;
use Illuminate\Http\Request;
use Log;

class PerfectMoneyPaymentGateway implements PaymentGatewayInterface
{
    protected string $perfectMoneyUrl = 'https://perfectmoney.is/api/step1.asp';
    protected array $credentials;

    /**
     * @throws \Exception
     */
    public function __construct()
    {
        $this->credentials = PaymentGateway::getCredentials('perfectmoney');

        // Ensure all credentials are available
        if (empty($this->credentials['merchant_id']) || empty($this->credentials['pass_phrase'])) {
            throw new \Exception('Perfect Money credentials are not set.');
        }
    }

    public function deposit($amount, $currency, $txid)
    {
        $paymentPayload = $this->buildPaymentPayload($amount, $currency, $txid);

        // Generate the HTML form with auto-submit JavaScript
        $htmlForm = $this->generateAutoSubmitForm($paymentPayload);

        return response($htmlForm, 200)
            ->header('Content-Type', 'text/html');
    }
    protected function buildPaymentPayload($amount, $currency, $txid): array
    {
        return [
            'PAYEE_ACCOUNT' => $this->credentials['merchant_id'],
            'PAYEE_NAME' => setting('site_title'),
            'PAYMENT_ID' => $txid,
            'PAYMENT_AMOUNT' => number_format($amount, 2, '.', ''),
            'PAYMENT_UNITS' => $currency,
            'STATUS_URL' => route('ipn.handle', ['gateway' => 'perfectmoney']),
            'PAYMENT_URL' => route('status.success', ['txid' => $txid]),
            'NOPAYMENT_URL' => route('status.cancel', ['txid' => $txid]),
            'SUGGESTED_MEMO' => 'Payment for Order ' . $txid,
            'BAGGAGE_FIELDS' => 'order_id',
            'order_id' => $txid,
        ];
    }

    protected function generateAutoSubmitForm(array $paymentPayload): string
    {
        $formFields = '';

        // Build hidden form fields for each payload entry
        foreach ($paymentPayload as $name => $value) {
            $formFields .= "<input type='hidden' name='{$name}' value='{$value}'>";
        }

        // Generate the HTML with auto-submit
        return <<<HTML
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Redirecting to Perfect Money</title>
            </head>
            <body>
                <p>Redirecting to Perfect Money...</p>
                <form id="perfectmoney-form" action="{$this->perfectMoneyUrl}" method="POST">
                    {$formFields}
                </form>
                <script>
                    // Automatically submit the form when the page loads
                    document.getElementById('perfectmoney-form').submit();
                </script>
            </body>
            </html>
        HTML;
    }

    public function handleIPN(Request $request): \Illuminate\Http\JsonResponse
    {
        $paymentId = $request->input('order_id');

        if ($this->validateIPN($request)) {
            Transaction::completeTransaction($paymentId);
            return response()->json(['status' => 'success']);
        }

        Log::error('Invalid Perfect Money IPN', $request->all());

        return response()->json(['status' => 'failed'], 400);
    }

    protected function validateIPN(Request $request): bool
    {
        $generatedHash = strtoupper(md5(
            $this->credentials['pass_phrase'] . ':' .
            $request->input('PAYMENT_AMOUNT') . ':' .
            $request->input('PAYEE_ACCOUNT')
        ));

        return $generatedHash === $request->input('V2_HASH');
    }
}
