<?php

namespace App\Repos\Payment;

use App\Models\Payment\ApiKeyHalkbank;
use App\Models\Payment\OnlinePaymentHistory;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class OnlinePaymentRepo
{
    /**
     * Pending orders are brand new orders that have not been processed yet.
     */
    public const PENDING = 'pending';

    /**
     * Failed orders are existing orders that could be paid
     */
    public const FAILED = 'failed';

    /**
     * Paid orders are existing order that could be paid successfully
     */
    public const PAID = 'paid';

    /**
     * Pay card order
     *
     * @param  [type] $resource
     */
    public function payCardOrder($resource): array
    {
        $orderNumber = $this->generateOrderNumber($resource);

        $paymentResponse = Http::get('https://mpi.gov.tm/payment/rest/register.do', [
            'orderNumber' => $orderNumber,
            'amount' => '00'.$resource->priceAmount(),
            'currency' => 934,
            'language' => 'ru',
            'userName' => $resource->branch->billing_username,
            'password' => $resource->branch->billing_password,
            'returnUrl' => route('online-payment-store'),
            'pageView' => 'DESKTOP',
            'description' => urlencode('Kart tölegi'),
        ])->onError(function ($response) {
            Log::channel('halkbank_payment_error')
                ->error('Payment error', [
                    'response' => [
                        'body' => $response->body(),
                    ],
                ]);
        });

        if ($paymentResponse->failed()) {
            return [
                'status' => 'failed',
                'url' => '',
            ];
        }

        OnlinePaymentHistory::create([
            'online_paymantable_id' => $resource->id,
            'online_paymantable_type' => $resource::$model,
            'amount' => $resource->priceAmount(),
            'orderNumber' => $orderNumber,
            'description' => 'Kart tölegi',
            'orderId' => $paymentResponse['orderId'],
            'formUrl' => $paymentResponse['formUrl'],
            'successUrl' => route('online-payment-store'),
            'errorUrl' => route('online-payment-store'),
            'api_client' => config('app.url'),
            'username' => $resource->branch->billing_username,
            'paymentStatus' => self::PENDING,
        ]);

        return [
            'status' => 'success',
            'url' => $paymentResponse['formUrl'],
        ];
    }

    /**
     * Generate order number for payment
     */
    public function generateOrderNumber($resource): int
    {
        return ApiKeyHalkbank::generateOrderNumber($resource);
    }

    /**
     * Status view
     */
    public static function statusView(): string
    {
        return 'orders.cards.online-payment.status';
    }
}
