<?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 Payment extends Page
{
	use Log;

	public function actionIndex()
	{
		$paymentId = $_GET['id'] ?? '';

		try {
			$result = $this->db->pQuery("SELECT * FROM transactions where payment_id=:payment_id:", ['payment_id' => $paymentId]);
			$data   = $result->fetch_assoc();

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

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

			if (empty($info['create'])) {
				throw new \Exception("Операция по платежу уже проведена", 1);
			}
			$create = json_decode($info['create']);

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

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

			$order  = new Models\Order();
			$amount = floatval($create->amount);

			if (empty($create->items)) {
				throw new \Exception("Не передан список товаров", 1);
			}
			if (empty($create->customer->phone)) {
				throw new \Exception("Не указан номер телефона", 1);
			}
			$items = [];
			foreach ($create->items as $item) {
				if (!$item->price) {
					continue;
				}
				$name      = $item->name;
				$id        = sprintf('%s-p-%s', $create->orderNumber, $item->offerId ?? 'shipping');
				$price     = floatval($item->price);
				$modelItem = new Models\Item();
				$modelItem
					->setId($id)
					->setName($name)
					->setAmount($price)
					->setQuantity($item->quantity);
				$items[] = $modelItem;
			}

			$order
				->setAmount($amount)
				->setId($create->invoiceUuid)
				->setItems($items);
			if (!$settings['preauth']) {
				$order->disableTwoStagePayment();
			}

			if (empty($create->customer->lastName)) {
				throw new \Exception("Необходимо указать фамилию покупателя", 1);
			}
			$clientInfo = new Models\ClientInfo();
			$clientInfo
				->setFirstName($create->customer->firstName)
				->setLastName($create->customer->lastName)
				->setPhone($create->customer->phone)
				->setEmail($create->customer->email);
			$order->setPhoneRecipient($clientInfo->getPhone());

			$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\Create($api);
			$method
				->setOrder($order)
				->setClientInfo($clientInfo)
				->setFailUrl($settings['fail_url'] ?: $create->siteUrl)
				->setSuccessUrl($settings['success_url'] ?? $create->siteUrl)
				->setNotificationUrl('https://podeli.retailcrm.proxypay.ru/callback.php?client_id=' . $info['client_id'] . '&shop_id=' . $info['shop_id'] . '&uuid=' . $create->invoiceUuid);
			$result = $method->execute();
			header("Location: " . $result['redirectUrl']);
			exit();
		} catch (\Exception $e) {
			$this->setTitle('Подели - Ошибка платежа');
			$data = [
				'message' => $e->getMessage(),
			];
			return $this->render('payment_error', $data);
		}
	}

}
