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

use ProxyPay\Core\Page;
use ProxyPay\Core\Utils;
use ProxyPay\Core\Retailcrm;

class Index extends Page
{

	public function actionIndex()
	{
		$this->setTitle('ProxyPay - Подели Настройки');
		$logged   = false;
		$shops    = [];
		$settings = [];
		$data     = [];

		if (isset($_SESSION['client_id'])) {
			$logged   = true;
			$data     = $this->db->pQuery("SELECT * FROM clients WHERE client_id=:client_id:", $_SESSION)->fetch_assoc();
			$settings = Utils::decode($data['settings'], $this->config->cipher_key);

			$res = $this->db->pQuery("SELECT * FROM shops where client_id=:client_id:", $_SESSION);
			while ($row = $res->fetch_assoc()) {
				$row['settings'] = Utils::decode($row['settings'], $this->config->cipher_key);
				$shops[]         = $row;
			}
		}

		$data = [
			'shops'    => $shops,
			'account'  => $_GET['account'] ?? '',
			'settings' => $settings,
			'url'      => $data['url'] ?? '',
		];

		if (!$logged) {
			$content = $this->render('index_noauth', $data);
		} else {
			$content = $this->render('index_auth', $data);
		}

		return $content;
	}

	public function actionAutologin()
	{
		$url        = str_replace(['http://', 'https://', '/'], "", $_POST['url'] ?? '');
		$authResult = Utils::checkCredentials($url, $_POST['key'] ?? '');

		if ($authResult < 1) {
			switch ($authResult) {
				case -1:$msg = 'Не удалось подключиться к RetailCRM, попробуйте ещё раз';
					break;
				case -2:$msg = 'Ошибка авторизации, проверьте ключ API';
					break;
				case -3:$msg = 'Ошибка, включите необходимые методы у ключа';
					break;
			}
			$_SESSION['error'] = $msg;

			$this->redirect('index.php');
		}

		$data = $this->db->pQuery("SELECT * FROM clients WHERE url=:url:", ['url' => $url])->fetch_assoc();
		if (!$data) {
			$uuid            = Utils::generageUUID();
			$settings        = ['key' => $_POST['key']];
			$encodedSettings = Utils::encode($settings, $this->config->cipher_key);
			$this->db->pQuery("INSERT INTO clients (uuid, settings, url, status) values (:uuid:,:settings:,:url:,1)", [
				'uuid'     => $uuid,
				'settings' => $encodedSettings,
				'url'      => $url,
			]);
			$_SESSION['client_id'] = $db->insert_id;
			$_SESSION['uuid']      = $uuid;
		} else {
			$_SESSION['client_id'] = $data['client_id'];
			$_SESSION['uuid']      = $data['uuid'];
		}
		$_SESSION['url'] = $url;

		$this->redirect('index.php');
	}

	public function actionLogin()
	{
		if (empty($_POST['clientId'])) {
			$this->redirect('index.php');
		}
		$data = $this->db->pQuery("SELECT * FROM clients WHERE `uuid`=:client_id:", [
			'client_id' => $_POST['clientId'],
		])->fetch_assoc();
		if ($data) {
			$_SESSION['client_id'] = $data['client_id'];
			$_SESSION['uuid']      = $data['uuid'];
			$_SESSION['url']       = $data['url'];
		}
	}

	public function actionSave()
	{
		if (empty($_SESSION['client_id'])) {
			$this->redirect('index.php');
		}
		$shopList = [];
		if (!empty($_POST['login'])) {
			foreach ($_POST['login'] as $key => $merchant) {
				$key = intval($key);
				if (!$merchant) {
					continue;
				}
				$shopList[$key] = $_POST['login'][$key];
				$settings       = [
					'login'       => $_POST['login'][$key],
					'password'    => $_POST['password'][$key],
					'sandbox'     => $_POST['sandbox'][$key],
					'preauth'     => $_POST['preauth'][$key],
					'key_text'    => $_POST['key_text'][$key],
					'cert_text'   => $_POST['cert_text'][$key],
					'success_url' => $_POST['success_url'][$key],
					'fail_url'    => $_POST['fail_url'][$key],
				];

				$settings = Utils::encode($settings, $this->config->cipher_key);

				if ($key) {
					$this->db->pQuery("UPDATE shops SET settings=:settings: WHERE client_id=:client_id: and shop_id=:shop_id:", [
						'settings'  => $settings,
						'client_id' => $_SESSION['client_id'],
						'shop_id'   => $key,
					]);
				} else {
					$this->db->pQuery("INSERT INTO shops (client_id, settings) values (:clinet_id:, :settings:)");
					$shopList[$db->insert_id] = $_POST['login'][$key];
				}
			}
			unset($shopList[0]);
			$this->db->pQuery("DELETE FROM shops WHERE client_id=:client_id: and shop_id not in (:shops:)", [
				'client_id' => $_SESSION['client_id'],
				'shops'     => array_keys($shopList),
			]);
		}

		//
		$settings = ['key' => $_POST['key']];
		$settings = Utils::encode($settings, $this->config->cipher_key);
		$this->db->pQuery("UPDATE clients SET settings=:settings: WHERE client_id=:client_id:", [
			'settings'  => $settings,
			'client_id' => $_SESSION['client_id'],
		]);

		$shops = [];
		foreach ($shopList as $id => $shop) {
			$shops[] = [
				'code' => "shop-{$id}",
				'name' => "Мерчант {$shop}",
				'active' => true,
			];
		}

		$api = new Retailcrm($_SESSION['url'], $_POST['key']);

		$settings = [
			"code"         => "proxypay_podeli",
			"clientId"     => $_SESSION['uuid'],
			"baseUrl"      => "https://podeli.retailcrm.proxypay.ru",
			"accountUrl"   => "https://podeli.retailcrm.proxypay.ru/index.php?action=login",
			"active"       => true,
			"name"         => "Подели",
			"actions"      => [
				"activity" => "activity.php",
			],
			"integrations" => [
				"payment" => [
					"actions"      => [
						"create"  => "create.php",
						"approve" => "approve.php",
						"cancel"  => "cancel.php",
						"refund"  => "refund.php",
					],
					"currencies"   => ["RUB"],
					"invoiceTypes" => ["link"],
					"shops"        => $shops,
				],
			],
		];
		$api->setPaymentMethod('proxypay_podeli', $settings);
		$this->redirect('index.php');
	}

}
