<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Api\Services\Payment\HalkbankPaymentService;
use App\Http\Controllers\Controller;
use App\Models\Shop\Order\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class OnlinePaymentController extends Controller
{
    public function halkbank(Request $request)
    {
        $formData = $request->validate([
            'pan' => ['required', 'integer', 'digits:16'],
            'month' => ['required', 'integer', 'between:1,12'],
            'year' => ['required', 'integer', 'min:2022', 'max:2066'],
            'name' => ['required', 'string'],
            'cvc' => ['required'],
            'order_id' => ['required', 'integer', 'exists:orders,id'],
        ]);

        return route('payment-not-available');

        $order = Order::find($request->order_id);

        $halkbank = new HalkbankPaymentService(
            amount: (string) $order->fullPriceWithShipping().'00',
            returnURL: route('web.order.check.halkbank', ['id' => $order->id])
        );

        $halkbank->orderTicket();

        $app_name = 'POSTSHOP';
        $app_id = Str::random(16);

        // Wagtyny kesgitlemek
        $response_start_hack = Http::asForm()->post('http://localhost:9090/api/v1/start-hack', [
            'app' => $app_name,
            'id' => $app_id,
            'url' => $halkbank->paymentPageUrl(),
        ]);

        Log::info(['hack' => $response_start_hack->json()]);

        if (! ($response_start_hack && array_key_exists('status', $response_start_hack->json()) && $response_start_hack['status'] == 'ok')) {
            return response()->rest([$response_start_hack->body()]);
        }

        $ok = (string) $request->cvc;

        $cvc = match (strlen($ok)) {
            1 => '00'.$ok,
            2 => '0'.$ok,
            default => $ok
        };

        $response_submit_card = Http::asForm()->post('http://localhost:9090/api/v1/submit-card', [
            'app' => $app_name,
            'id' => $app_id,
            'md-order' => $halkbank->ticketOrderId(),
            'card-number' => $request->pan,
            'card-expiry' => $request->year.$request->month,
            'name-on-card' => $request->name,
            'card-cvc' => $cvc,
        ]);

        Log::info(['submit_card' => $response_submit_card->json()]);

        if (! ($response_submit_card && array_key_exists('status', $response_submit_card->json()) && $response_submit_card['status'] == 'ok')) {
            return response()->rest([$response_submit_card->body()]);
        }

        return response()->rest([
            'order_id' => $order->id,
            'ticket_order_id' => $halkbank->ticketOrderId(),
            'url' => $response_submit_card['acs-session-url'],
        ]);
    }

    public function checkPayment(Request $request)
    {
        $request->validate(['order_id' => 'required|integer|exists:orders,id', 'ticket_order_id' => 'required|string']);

        $payment_status = HalkbankPaymentService::checkPayment($request->ticket_order_id);
        if ($payment_status) {
            Order::find($request->order_id)->markAsPaid();
        }

        return response()->rest([
            'payment_status' => $payment_status,
        ]);
    }

    public function halkbankVerifyOTP(Request $request)
    {
        $request->validate([
            'order_id' => ['required', 'integer', 'exists:orders,id'],
            'request_id' => ['required'],
            'sms_code' => ['required', 'integer'],
        ]);

        $response = HalkbankPaymentService::sendSMSVerificationCode(
            request_id: $request->request_id,
            sms_code: $request->sms_code
        );

        $doc = new \DOMDocument();
        $doc->loadHTML($response->body());

        $inputs = $doc->getElementsByTagName('input');

        if (count($inputs) > 0) {
            $md = $inputs[0]->getAttribute('value');
            $paRes = $inputs[1]->getAttribute('value');
        }

        if ($md && $paRes) {
            $response_3d = Http::asForm()->post('https://mpi.gov.tm:443/payment/rest/finish3ds.do', [
                'MD' => $md,
                'PaRes' => $paRes,
            ]);

            Log::info('3d', [$response_3d->body()]);
        }

        return response()->rest();
    }
}
