<?php

namespace App\Helpers\Payment\Banks;

use App\Settings;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;

class IdPay
{
    /**
     * @var $Api_Key
     */
    protected $Api_Key;

    /**
     * @var bool
     */
    protected $isSandbox = true;


    /**
     * get value IdpayToken from table settings
     */
    public function __construct()
    {
        $this->Api_Key = Settings::query()
            ->where('name','IdpayToken')
            ->first()->value;

    }


    /**
     * send request payment towards idpay
     * @param $amount
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \Exception
     */
    public function request ($amount, $CallbackURL, $params = null)
    {
        $user = Auth::user();
        $params =[
            'order_id' => time(),
            'amount' => $amount*10,
            'name' => $user->name .' '. $user->family,
            'phone' => $user->mobile,
            'mail' => $user->email,
            'desc' => 'شارژ کیف پول ',
            'callback' => $CallbackURL,
        ];
        $request = Http::withHeaders([
            'Content-Type: application/json',
            'Accept: application/json',
            'charset: utf-8',
            'X-API-KEY'     =>  $this->Api_Key,
            'X-SANDBOX'     =>  $this->isSandbox,
        ])->post('https://api.idpay.ir/v1.1/payment', $params);

        $response = json_decode($request->getBody()->getContents(), true);

        if (isset($response['error_message']) || isset($response['error_code'])){
            return $response['error_message'] . ':' .  $response['error_code'];
        }

        header('Location:' . $response['link']);exit();
    }


    /**
     * @param $param
     * @return mixed
     */
    public function verify ($params_idpay)
    {
        $params = [
            'id' => $params_idpay['id'],
            'order_id' => $params_idpay['order_id'],
        ];

        $request = Http::withHeaders([
            'Content-Type: application/json',
            'Accept: application/json',
            'charset: utf-8',
            'X-API-KEY'     =>  $this->Api_Key,
            'X-SANDBOX'     =>  $this->isSandbox,
        ])->post( 'https://api.idpay.ir/v1.1/payment/verify', $params);

        return json_decode($request->getBody()->getContents(), true);
    }
}
