<?php

namespace Vinteract\Payments\Providers\PinPayments;

use \Vinteract\Payments\Providers\PinPayments\RequestResponse as RequestResponse;

class CardToken {
	
	public function process($postData) {
		
		/*
			Create request instance.
		*/
		
		$request = new \Vinteract\Payments\Providers\PinPayments\Request("POST");
		
		/*
			Process request and get the response.
		*/
		
		$response = $request->process(\Vinteract\Payments\Providers\PinPayments\PinPayments::getRequestUrl("customers"), [
			"email" => $postData["customer"]["email"],
			"card_token" => $postData["card"]["token"],
		]);
		
		/*
			Success or error?
		*/
		
		if ($response->success()) {
			
			/*
				Create card token record.
			*/
				
				// Variables.
				
				$card_number = $response->getValue("data.card.display_number");
				
				// Create record.
				
				$cardTokenRecord = \Vinteract\Payments\CardTokenRecord::create([
					"user_id" => $postData["customer"]["user_id"],
					"token" => $response->getValue("data.token"),
					"type" => $response->getValue("data.card.scheme"),
					"last_4" => substr($card_number, strlen($card_number) - 4),
					"expiry_month" => $response->getValue("data.card.expiry_month"),
					"expiry_year" => $response->getValue("data.card.expiry_year"),
				]);
				
			/*
				Return the response.
			*/
			
			return new RequestResponse([
				"code" => $response->getResponseCode(),
				"contents" => [
					"card" => $cardTokenRecord->getAttributes(),
				]
			]);
			
		}
		
		/*
			Return the response.
		*/
		
		return $response;
		
	}
	
}
