<?php
declare (strict_types = 1);
namespace ProxyPay\Pages;

use Podeli\Payment\Client;
use Podeli\Payment\Methods;
use Podeli\Payment\Models;
use ProxyPay\Core\Page;
use ProxyPay\Core\Utils;
use ProxyPay\Traits\Log;

class Refund extends Page
{
	use Log;

	public function actionIndex()
	{
		$this->log($_REQUEST, 'refund');
		$response = [
			'success'  => false,
			'errorMsg' => 'Не удалось сделать возврат',
		];
		try {
			$client = $this->db->pQuery("SELECT * FROM clients WHERE `uuid`=:client_id:", [
				'client_id' => $_POST['clientId'] ?? '',
			])->fetch_assoc();
			if (!$client) {
				throw new \Exception("Аккаунт не найден", 1);
			}
			$refund = json_decode($_POST['refund'] ?? '');
			if (!$refund || empty($refund->paymentId)) {
				throw new \Exception("Нет информации о возврате", 1);
			}
			$result = $this->db->pQuery("SELECT * FROM transactions where payment_id=:payment_id:", [
				'payment_id' => $refund->paymentId,
			]);
			$data = $result->fetch_assoc();

			if (!$data) {
				throw new \Exception("Платеж не найден", 1);
			}

			$info = Utils::decode($data['info'], $refund->paymentId . $this->config->cipher_key);

			$shopData = $this->db->pQuery("SELECT settings FROM shops WHERE shop_id=:shop_id: and client_id=:client_id:", [
				'shop_id'   => $info['shop_id'],
				'client_id' => $client['client_id'],
			])->fetch_assoc();
			if (!$shopData) {
				throw new \Exception("Магазин не найден", 1);
			}

			$settings = Utils::decode($shopData['settings'], $this->config->cipher_key);

			$api = new Client($settings['login'], $settings['password']);
			$api->setCertPath($settings['cert_text']);
			$api->setKeyPath($settings['key_text']);
			$api->useCurl();
			if ($settings['sandbox']) {
				$api->setSandboxMode();
			}

			$refundId = Client::generateCorrelationId();
			$method   = new Methods\Refund($api);

			$order = new Models\RefundOrder();
			$order->setId($refundId);

			foreach ($info['order']['items'] as $position) {
				$item = new Models\RefundItem();
				$item
					->setRefundedQuantity($position['quantity'])
					->setId($position['id']);
				$order->addItem($item);
			}

			$method->setRefundOrder($order);
			$method->setOrderId($refund->paymentId);
			$this->log($method->getData(), 'refund');
			$result = $method->execute();
			$this->log($result, 'refund response');

			$response['success'] = true;
			$response['result']  = [
				'status' => 'pending',
				'id'     => $refundId,
				//'comment' => $result->refund->message,
				'amount' => $result['refund']['totalRefundedAmount'],
			];

		} catch (\Exception $e) {
			$response['errorMsg'] = $e->getMessage();
		}

		return $response;

	}

}
