<?php

namespace Vinteract\Payments\Providers\PinPayments\Transfers;

use \Vinteract\Payments\Providers\PinPayments\Request;
use \Vinteract\Payments\Providers\PinPayments\PinPayments;

use \Vinteract\Payments\Providers\PinPayments\Transfers\TransferCollection;

class TransferRequest {
	
	private function remapUrlParams($oldParams = []) {
		
		$newParams = [];
		
		if (array_key_exists("keywords", $oldParams)) {
			$newParams["query"] = $oldParams["keywords"];
		}
		
		if (array_key_exists("from", $oldParams)) {
			$newParams["end_date"] = $oldParams["from"];
		}
		
		if (array_key_exists("to", $oldParams)) {
			$newParams["start_date"] = $oldParams["to"];
		}
		
		return $newParams;
		
	}
	
	public function process($params = []) {
		
		// Create transfer collection instance.
		
		$transferCollection = new TransferCollection();
		
		// Create request instance.
		
		$transferRequest = new Request("GET");
		
		// Create request URL.
		
		if (count($params)) {
			$url = PinPayments::getRequestUrl("transfers/search?" . http_build_query($this->remapUrlParams($params)));
		} else {
			$url = PinPayments::getRequestUrl("transfers");
		}
		
		// Process the request and get the response.
		
		$transferResponse = $transferRequest->process($url);
		
		if ($transferResponse->success()) {
			$transferCollection->setItems($transferResponse->getValue("data"));
			foreach($transferCollection->getItems() as &$transfer) {
				// Request the line items for this transfer.
				$transferLineItemsResponse = $transferRequest->process(PinPayments::getRequestUrl("transfers/{$transfer->token}/line_items"));
				// Add the line items to the transfer.
				$transfer->setLineItems($transferLineItemsResponse->getValue("data"));
			}
		}
		
		return $transferCollection;
		
	}
	
}
