<?php

namespace kernel\services;

use GuzzleHttp\Exception\GuzzleException;
use kernel\Flash;
use kernel\helpers\Debug;
use kernel\helpers\Files;
use kernel\helpers\RESTClient;
use kernel\Request;

class ModuleShopService
{
    protected string $url;
    protected string $token;

    public function __construct()
    {
        $this->url = $_ENV['MODULE_SHOP_URL'];
        $this->token = $_ENV['MODULE_SHOP_TOKEN'];
    }

    /**
     * @param string $email
     * @return mixed
     * @throws GuzzleException
     */
    public function email_auth(string $email): mixed
    {
        $request = RESTClient::post($this->url . "/api/secure/email_auth", ['email' => $email], false);

        return json_decode($request->getBody()->getContents(), true);
    }

    /**
     * @param string $code
     * @return mixed
     * @throws GuzzleException
     */
    public function code_check(string $code): mixed
    {
        $request = RESTClient::post($this->url . "/api/secure/code_check", ['code' => $code], false);

        return json_decode($request->getBody()->getContents(), true);
    }

    /**
     * @return mixed
     * @throws GuzzleException
     */
    public function getGroupedBySlugModules(): mixed
    {
        $modulesInfo = RESTClient::request($_ENV['MODULE_SHOP_URL'] . '/api/module_shop/gb_slug');
        return json_decode($modulesInfo->getBody()->getContents(), true);
    }

    /**
     * @param string $slug
     * @return void
     * @throws GuzzleException
     */
    public function installModule(string $slug): void
    {
        $moduleInfo = $this->getModuleInfoBySlug($slug);

        $moduleInfo = RESTClient::request($_ENV['MODULE_SHOP_URL'] . '/api/module_shop/install/' . $moduleInfo['id']);
        $moduleInfo = json_decode($moduleInfo->getBody()->getContents(), true);

        Files::uploadByUrl($_ENV['MODULE_SHOP_URL'] . $moduleInfo['path_to_archive'], RESOURCES_DIR . "/tmp/modules");

        (new ModuleService())->installModule('/resources/tmp/modules/' . basename($moduleInfo['path_to_archive']));
    }

    /**
     * @param string $slug
     * @return false|mixed
     * @throws GuzzleException
     */
    public function getModuleInfoBySlug(string $slug): mixed
    {
        $modulesInfo = $this->getGroupedBySlugModules();
        foreach ($modulesInfo as $module) {
            if ($module['slug'] === $slug) {
                return $module;
            }
        }

        return false;
    }

    /**
     * @param string $slug
     * @return bool
     * @throws GuzzleException
     */
    public function existsInModuleShop(string $slug): bool
    {
        $modulesInfo = $this->getGroupedBySlugModules();
        foreach ($modulesInfo as $module) {
            if ($module['slug'] === $slug) {
                return true;
            }
        }

        return false;
    }

}