<?php


namespace Nabik\Gateland\Gateways;

use Exception;
use Nabik\Gateland\Enums\Transaction\CurrenciesEnum;
use Nabik\Gateland\Enums\Transaction\StatusesEnum;
use Nabik\Gateland\Exceptions\InquiryException;
use Nabik\Gateland\Exceptions\VerifyException;
use Nabik\Gateland\Gateways\Features\ShaparakFeature;
use Nabik\Gateland\Models\Transaction;

class PayIRGateway extends BaseGateway implements \Nabik\Gateland\Gateways\Features\FreeFeature, ShaparakFeature {

	protected string $name = 'پی.آی.آر';

	protected string $description = 'pay.ir';

	protected string $url = 'https://l.nabik.net/payir';

	/**
	 * @param Transaction $transaction
	 *
	 * @return bool|mixed
	 * @throws Exception
	 */
	public function request( Transaction $transaction ): void {
		try {

			$data = [
				'api'          => $this->options['api_key'],
				'amount'       => $transaction->amount * 10,
				'redirect'     => urlencode( $transaction->gateway_callback ),
				'factorNumber' => $transaction->id,
				'description'  => $transaction->description,
				'resellerId'   => '1000000800',
			];


			if ( $transaction->mobile ) {
				$data['mobile'] = str_replace( '+98', '0', $transaction->mobile );
			}

			if ( $transaction->allowed_cards ) {
				$data['validCardNumber'] = $transaction->allowed_cards[0];
			}

			$response = $this->curl( 'https://pay.ir/pg/send', $data );
		} catch ( Exception $e ) {
			throw new Exception( 'خطا در اتصال به درگاه! لطفا دوباره تلاش کنید.' );
		}

		if ( $response['status'] !== 1 ) {
			throw new Exception( $response['errorMessage'], $response['errorCode'] );
		}

		$transaction->update( [
			'gateway_au' => $response['token'],
		] );

		return;
	}

	/**
	 * @param Transaction $transaction
	 *
	 * @return bool
	 * @throws InquiryException
	 * @throws VerifyException
	 */
	public function inquiry( Transaction $transaction ): bool {
		$this->log( $transaction, 'inquiry', [
			'transaction' => $transaction->toArray(),
		] );

		$parameters = [
			'api'   => $this->options['api_key'],
			'token' => $transaction->gateway_au,
		];

		try {
			$response = $this->curl( 'https://pay.ir/pg/verify', $parameters );
		} catch ( Exception $e ) {
			$this->log( $transaction, 'requestFailed', [
				'parameters' => $parameters,
				'error'      => $e->getMessage(),
			] );

			throw new VerifyException();
		}

		if ( $response['status'] === 1 ) {
			$this->log( $transaction, 'verifySuccess' );

			$transaction->update( [
				'gateway_trans_id' => $response['transId'],
				'gateway_status'   => 1,
				'status'           => StatusesEnum::STATUS_PAID,
				'card_number'      => $response['cardNumber'],
				'paid_at'          => \Carbon\Carbon::now(),
			] );

			return true;
		}

		throw new InquiryException( $response['errorCode'] );
	}

	public function redirect( Transaction $transaction ) {
		return wp_redirect( sprintf( 'https://pay.ir/pg/%s', $transaction->gateway_au ) );
	}

	/**
	 * @return CurrenciesEnum[]
	 */
	public function currencies(): array {
		return [
			CurrenciesEnum::IRT,
		];
	}

	public function options(): array {
		return [
			[
				'label'       => 'کلید API',
				'key'         => 'api_key',
				'description' => 'برای تست درگاه می توانید از کلید test استفاده کنید.',
			],
		];
	}
}
