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

use ProxyPay\Core\Page;
use ProxyPay\Core\Utils;
use ProxyPay\Traits\Log;

use Podeli\Payment\Methods;
use Podeli\Payment\Models;
use Podeli\Payment\Client;

class Approve extends Page
{
	use Log;

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

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

			$info = Utils::decode($data['info'], $approve->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\Commit($api);

			$order = new Models\CommitOrder();
			$order->setId($approve->paymentId);

			foreach($info['order']['items'] as $position) {

				$item = new Models\Item();
				$item
					->setQuantity($position['quantity'])
					->setId($position['id']);
				$order->addItem($item);
			}

			$order->setAmount($approve->amount);

			$method->setOrder($order);
			$result = $method->execute();
			$this->log($result, 'approve');

			$response['success'] = true;

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

}