<?php

namespace App\Helpers\Payment\Banks;

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

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

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

    public function __construct() {
        $this->Token = Settings::query()
            ->where('name','ZibalToken')
            ->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 = null)
    {
        $parameters = [
            "merchant"=> $this->Token,
            "callbackUrl"=> $CallbackURL,
            "amount"=> $amount*10,
            "orderId"=> time(),
            "mobile"=> Auth::user()->mobile
        ];
        $request = Http::withHeaders($this->headers)
            ->post('https://gateway.zibal.ir/v1/request', $parameters);
        $response = json_decode($request->getBody()->getContents(), true);

        if ($response['result'] !== 100) {
            return [
                'message' => $response['message'],
                'code'   => $response['result']
            ];
        }

        header('Location:https://gateway.zibal.ir/start/' . $response['trackId']);exit();
    }

    /**
     * active Payment done
     * @param $Authority
     * @param $amount
     * @return mixed
     * @throws \Exception
     */
    public function verify($trackId)
    {
        $parameters = [
            "merchant" => $this->Token,
            "trackId" => $trackId
        ];

        $request = Http::withHeaders($this->headers)
            ->post('https://gateway.zibal.ir/v1/verify', $parameters);
        $response = json_decode($request->getBody()->getContents(), true);
        if(isset($response['result']) && $response['result'] == 100){
            return $response;
        }
        return  [
            'status' => false,
            'message' => "پرداخت با شکست مواجه شد!"
        ];
    }
}
