<?php

namespace App\Http\Controllers;

use App\Models\Ecommerce\Product\Order\Order;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class OnlinePaymentController extends Controller
{
    public function index(Request $request)
    {
        $request->validate([
            'orderId' => ['required', 'string'],
        ]);

        $resource = Order::query()->where('halkbank_id', $request->orderId)->first();

        if (! $resource) {
            return $this->view(false, 'Sargyt tapylmady');
        }

        $response = Http::asForm()->post('https://mpi.gov.tm/payment/rest/getOrderStatusExtended.do', [
            'language' => 'ru',
            'orderId' => $request->orderId,
            'userName' => halkbankCredentials('username'),
            'password' => halkbankCredentials('password'),
        ]);

        if ($response->failed()) {
            return $this->data(false, 'Näsazlyk, operator bilen habarlaşyň');
        }

        $payment_status = $response['paymentAmountInfo']['depositedAmount'] > 0;

        // Update resource
        $resource->update(['paid' => $payment_status]);

        return $this->view(
            status: $payment_status,
            message: $payment_status ? 'Töleg geçdi' : 'Töleg geçmedi',
            pnr: $response['orderNumber'],
            price_amount: convertToOriginalFormat($response['amount']),
        );
    }

    public function view(
        $status,
        $message,
        string $pnr = '-',
        string $branch_name = 'MM.COM.TM',
        int|string $price_amount = '-',
        string $return_url = 'https://mm.com.tm/orders',
    ): View {
        return view('halkbank.status', [
            'success' => $status,
            'title' => $message,
            'pnr' => $pnr,
            'branch_name' => $branch_name,
            'price_amount' => $price_amount,
            'return_url' => $return_url,
        ]);
    }
}
