<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class HyperpayService
{
    protected $baseUrl;
    protected $headers;
    protected $entityId;
    protected $paymentType;
    protected $currency;

    public function __construct()
    {
        $this->baseUrl = config('services.hyperpay.base_url');
        $this->headers = [
            'Authorization' => 'Bearer ' . config('services.hyperpay.access_token'),
        ];
        $this->entityId = config('services.hyperpay.entity_id');
        $this->paymentType = config('services.hyperpay.payment_type');
        $this->currency = config('services.hyperpay.currency');
    }

    public function checkout($amount, $email, $bookingId)
    {
        $url = $this->baseUrl . '/v1/checkouts';
        $data = [
            'entityId' => $this->entityId,
            'amount' => number_format($amount, 2, '.', ''),
            'currency' => $this->currency,
            'paymentType' => $this->paymentType,
            'merchantTransactionId' => $bookingId,
            'customer.email' => $email,
        ];
        if (!app()->isProduction()) {
            $data['testMode'] = 'EXTERNAL';
            // $data['customParameters[3DS2_enrolled]'] = true;
        }
        Log::info("creating pyament data", $data);
        $response = Http::asForm()->withHeaders($this->headers)->post($url, $data);

        return $response->json();
    }

    public function getPaymentStatus($checkoutId)
    {
        $url = $this->baseUrl . '/v1/checkouts/' . $checkoutId . '/payment';
        $url .= '?entityId=' . $this->entityId;

        $response = Http::withHeaders($this->headers)->get($url);

        return $response->json();
    }
}
