<?php

namespace App\Helpers\Payment\Banks;

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

class PayIr
{
    /**
     * @var \Illuminate\Database\Eloquent\HigherOrderBuilderProxy|mixed
     */
    private $Api;

    /**
     * @var string[]
     */
    private $headers = [
        'Accept: application/json',
        'charset: utf-8',
        'Content-Type: application/json',
    ];

    public function __construct() {
        $this->Api = Settings::query()
            ->where('name','PayIrToken')
            ->first()->value;
    }

    /**
     * send request Payment towards zarinpal
     * @param $amount
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \Exception
     */
    public function request($amount, $CallbackURL, $params)
    {
        $user = Auth::user();
        $params = [
            'api' => $this->Api,
            'amount' => $amount*10,
            'name' => $user->name .' '. $user->family,
            'mobile' => $user->mobile,
            'factorNumber' => $params,
            'description' => 'شارژ کیف پول ',
            'redirect' => $CallbackURL,
        ];
        $request = Http::withHeaders($this->headers)
            ->post('https://pay.ir/pg/send', $params);
        $response = json_decode($request->getBody()->getContents(), true);

        if (!$response['status'])
            return $response['errorMessage'];

        header('Location:https://pay.ir/pg/' . $response['token']);exit();
    }

    /**
     * active Payment done
     * @param $Authority
     * @param $amount
     * @return mixed
     * @throws \Exception
     */
    public function verify($token)
    {
        $params = [
            'api' => $this->Api,
            'token' => $token,
        ];

        $request = Http::withHeaders($this->headers)
            ->post('https://pay.ir/pg/verify', $params);

        $result = json_decode($request->getBody()->getContents(), true);
        if(isset($result['status'])){
            return $result;
        }
        return [
            'status' => false,
            'message' => "خطا در پرداخت!"
        ];
    }
}
