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

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

class Cancel extends Page
{
	use Log;

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

			if ($data) {
				$info = Utils::decode($data['info'], $cancel->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();
				}

				$method = new Methods\Cancel($api);
				$method->setOrderId($cancel->paymentId);
				$method->execute();
			}
			$response['success'] = true;

		} catch (\Exception $e) {
			$response['errorMsg'] = $e->getMessage();
		}
		$this->log($response, 'cancel response');
		return $response;
	}

}
