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

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

class Create extends Page
{
	use Log;

	public function actionIndex()
	{
		$this->log($_REQUEST, 'create');
		$response = [
			'success'  => false,
			'errorMsg' => 'Не удалось выставить счёт',
		];

		try {
			$data = $_POST;
			if (empty($data)) {
				throw new \Exception("Пустой запрос", 1);
			}

			$create = json_decode($data['create']);

			if (empty($create)) {
				throw new \Exception("Пустой запрос", 1);
			}

			$client = $this->db->pQuery("SELECT * FROM clients WHERE `uuid`=:client_id:", ['client_id' => $data['clientId']])->fetch_assoc();
			if (!$client) {
				throw new \Exception("Аккаунт не найден", 1);
			}

			list(, $shopId) = explode('-', $create->shopId);

			$shopData = $this->db->pQuery("SELECT * FROM shops WHERE client_id=:client_id: and shop_id=:shop_id:", [
				'client_id' => $client['client_id'],
				'shop_id'   => $shopId,
			])->fetch_assoc();

			if (!$shopData) {
				throw new \Exception("Магазин не найден", 1);
			}

			if (empty($create->items)) {
				throw new \Exception("Не передан список товаров", 1);
			}
			if (empty($create->customer->phone)) {
				throw new \Exception("Не указан номер телефона", 1);
			}

			if (empty($create->customer->lastName)) {
				throw new \Exception("Необходимо указать фамилию покупателя", 1);
			}

			$info['create']    = $data['create'];
			$info['client_id'] = $client['client_id'];
			$info['shop_id']   = $shopId;

			$infoEncoded = Utils::encode($info, $create->invoiceUuid . $this->config->cipher_key);

			$this->db->pQuery("REPLACE INTO transactions (payment_id, info) values (:payment_id:, :info:)", [
				'payment_id' => $create->invoiceUuid,
				'info'       => $infoEncoded,
			]);

			$response['success'] = true;
			$response['result']  = [
				'paymentId'   => $create->invoiceUuid,
				'invoiceUrl'  => 'https://podeli.retailcrm.proxypay.ru/payment.php?id=' . $create->invoiceUuid,
				'cancellable' => true,
			];

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

		return $response;

	}

}
