<?php
/**
 * Invision Commerce payment gateway extension.
 */

namespace IPS\makepay\extensions\nexus\Gateway;

use IPS\makepay\Api\Client;
use IPS\makepay\Storage\Storage;

if (!\defined('\IPS\SUITE_UNIQUE_KEY')) {
    exit;
}

class _MakePay extends \IPS\nexus\Gateway
{
    public function name(): string
    {
        return 'MakePay';
    }

    public function settings(&$form): void
    {
        $form->add(new \IPS\Helpers\Form\YesNo('makepay_enabled', true));
        $form->add(new \IPS\Helpers\Form\Text('makepay_company_id', Storage::get('company_id'), false));
        $form->add(new \IPS\Helpers\Form\Text('makepay_api_key_id', Storage::get('api_key_id'), false));
        $form->add(new \IPS\Helpers\Form\Password('makepay_api_key_secret', '', false));
        $form->add(new \IPS\Helpers\Form\Password('makepay_webhook_secret', '', false));
        $form->add(new \IPS\Helpers\Form\YesNo('makepay_debug', false));
    }

    public function testSettings($settings): bool
    {
        if (!empty($settings['makepay_api_key_secret'])) {
            Storage::setSecret('api_key_secret', (string) $settings['makepay_api_key_secret']);
        }
        if (!empty($settings['makepay_webhook_secret'])) {
            Storage::setSecret('webhook_secret', (string) $settings['makepay_webhook_secret']);
        }
        foreach (['company_id', 'api_key_id'] as $key) {
            $formKey = 'makepay_' . $key;
            if (isset($settings[$formKey])) {
                Storage::set($key, (string) $settings[$formKey]);
            }
        }

        return true;
    }

    public function auth(\IPS\nexus\Transaction $transaction, $values, ?\IPS\nexus\Fraud\MaxMind\Request $maxMind = null, $recurrings = [], $source = null)
    {
        $invoice = $transaction->invoice;
        $companyId = Storage::get('company_id');
        if (!$companyId) {
            throw new \RuntimeException('MakePay company ID is not configured.');
        }

        $client = new Client();
        $returnUrl = (string) \IPS\Http\Url::internal('app=makepay&module=webhook&controller=notify&do=return', 'front', 'makepay_return');
        $link = $client->createPaymentLink($companyId, [
            'status' => 'active',
            'sendPaymentRequestEmail' => false,
            'payload' => [
                'title' => 'Invision invoice #' . $invoice->id,
                'description' => 'Hosted MakePay checkout for Invision Community invoice #' . $invoice->id,
                'amount' => (string) $transaction->amount->amount,
                'fiatCurrency' => (string) $transaction->amount->currency,
                'currency' => 'USDT',
                'orderId' => 'invision_invoice_' . $invoice->id,
                'customerEmail' => (string) ($invoice->member->email ?? ''),
                'clientId' => (string) ($invoice->member->member_id ?? 0),
                'callbackUrl' => rtrim((string) \IPS\Settings::i()->base_url, '/') . '/index.php?/makepay/webhook/notify',
                'returnUrl' => $returnUrl,
                'successUrl' => $returnUrl,
                'failureUrl' => (string) $invoice->checkoutUrl(),
                'metadata' => [
                    'source' => 'invision',
                    'invoiceId' => (string) $invoice->id,
                    'transactionId' => (string) $transaction->id,
                    'memberId' => (string) ($invoice->member->member_id ?? 0),
                    'moduleVersion' => '0.1.0',
                ],
            ],
        ]);

        $paymentUrl = $client->extractPaymentUrl($link);
        $paymentUid = (string) ($link['paymentLink']['uid'] ?? $link['uid'] ?? $link['id'] ?? '');
        $transaction->gw_id = $paymentUid;
        $transaction->save();

        \IPS\Output::i()->redirect(\IPS\Http\Url::external($paymentUrl));
    }

    public function capture(\IPS\nexus\Transaction $transaction): void
    {
        $transaction->approve();
    }

    public function refund(\IPS\nexus\Transaction $transaction, $amount = null): bool
    {
        $transaction->status = \IPS\nexus\Transaction::STATUS_REFUNDED;
        $transaction->save();

        return true;
    }

    public function checkValidity(\IPS\nexus\Money $amount, ?\IPS\nexus\Customer $customer = null, array $recurrings = [], $billingAddress = null): bool
    {
        return (bool) Storage::get('company_id');
    }
}
