<?php

use App\Models\Cars;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * Helper functions
 */

function offers() 
{
    return Cars::count();
}

function hpToKw($hp)
{
    return number_format($hp * 0.7457);
}

function createInvoice($amount, $car_id, $price, $duration, $plan, $errorCallback)
{
    try {

        $apiKey = config("app.payment_key");

        $payload = [
            'price_amount' => intval($amount),
            'price_currency' => 'USD',
            'order_id' => uniqid(),
            'pay_currency' => 'usdttrc20',
        ];

        $response = Http::withHeaders([
            'x-api-key' => $apiKey,
            'Content-Type' => 'application/json',
        ])->post('https://api.nowpayments.io/v1/invoice', $payload);

        if ($response->successful()) {

            $invoiceData = $response->json();

            $invoiceData['car_id'] = $car_id;
            $invoiceData['duration'] = $duration;
            $invoiceData['plan'] = $plan;
            $invoiceData['price'] = $price;

            return redirect()->route("payment", ['order_id' => $payload['order_id']])->with([
                'success' => true,
                'invoice_data' => $invoiceData
            ]);
        } else {
            $errorCallback($response);
            // ddd('An error occurred somewhere: ' . $response->status());
        }
    } catch(\Exception $e) {
        Log::error($e->getMessage());
    }
}