<?php

namespace WPOauth2\Client;

use Exception;
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
use Twig\Environment;
use Wp_Oauth2_Client;

class Oauth_Client_Callback
{

    private static $instance;
    use OauthSettings;

    /**
     *
     * @var Environment $twig TWIG autoload for PHP-Template-Engine
     */
    protected Environment $twig;

    /**
     * @since    1.0.0
     * @var Wp_Oauth2_Client The main class.
     */
    protected Wp_Oauth2_Client $main;

    /**
     * The ID of this Plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $basename The ID of this theme.
     */
    protected string $basename;

    private string $client_scopes;
    private string $server_url;
    private string $authorizeUrl;
    private string $tokenUrl;
    private string $callback_url;
    private string $app_id;
    private string $app_secret;
    private string $wellKnown;


    /**
     * @return static
     */
    public static function instance(string $basename, Wp_Oauth2_Client $main): self
    {
        if (is_null(self::$instance)) {
            self::$instance = new self($basename, $main);
        }

        return self::$instance;
    }

    public function __construct(string $basename, Wp_Oauth2_Client $main)
    {

        $this->main = $main;

        $this->basename = $basename;
        $settings = get_option('wp_oauth2_client_settings');
        $this->client_scopes = $settings['client_scopes'] ?? 'BASIC PRODUCT';
        $this->server_url = $settings['server_url'] ?? '';
        $this->app_id = $settings['app_id'] ?? '';
        $this->app_secret = $settings['app_secret'] ?? '';
        $this->authorizeUrl = $settings['server_url'] . '/' . $settings['authorize_uri'];
        $this->tokenUrl = $settings['server_url'] . '/' . $settings['token_uri'];
        $this->callback_url = $settings['callback_url'] ?? '';
        $this->wellKnown = $settings['server_url'] . '/' . $settings['well_known_url'];
    }

    public function oauth_api_callback()
    {
        include ABSPATH . '/wp-includes/pluggable.php';
        $redirectAdmin = admin_url('admin.php?page=wp-oauth2-client');
        $errorTitle = '';
        $errorMsg = '';
        if (isset($_GET['error'])) {
            $errorTitle = 'No code provided';
            if (isset($_GET['error_description'])) {
                $errorMsg = $_GET['error_description'];
            }
            $oauthData = [
                'error_title' => $errorTitle,
                'error_msg' => $errorMsg,
                'authentifizierung' => false
            ];
            update_option($this->basename . '/oauth_api_data', $oauthData);
            delete_option($this->basename . '/refresh_token');
            wp_redirect($redirectAdmin);
            exit();
        }

        if (
            !$this->client_scopes ||
            !$this->server_url ||
            !$this->authorizeUrl ||
            !$this->tokenUrl ||
            !$this->app_id ||
            !$this->app_secret ||
            !$this->callback_url
        ) {
            $errorTitle = 'Ungültige Einstellungen';
            $errorMsg = 'Einstellungen im Backend überprüfen. (' . __LINE__ . ')';
            $oauthData = [
                'error_title' => $errorTitle,
                'error_msg' => $errorMsg,
                'authentifizierung' => false
            ];

            update_option($this->basename . '/oauth_api_data', $oauthData);
            delete_option($this->basename . '/refresh_token');
            wp_redirect($redirectAdmin);
            exit();
        }

        $code = $_GET['code'] ?? null;
        if (null === $code) {
            $errorTitle = 'No code provided';
            if (isset($_GET['error_description'])) {
                $errorMsg = $_GET['error_description'];
            }
            $oauthData = [
                'error_title' => $errorTitle,
                'error_msg' => $errorMsg,
                'authentifizierung' => false
            ];
            update_option($this->basename . '/oauth_api_data', $oauthData);
            delete_option($this->basename . '/refresh_token');
            wp_redirect($redirectAdmin);
            exit();
        }
        // Swap the code for an access token.
        $body = [
            'method' => 'POST',
            'timeout' => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking' => true,
            'sslverify' => true,
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
            ],
            'body' => [
                'grant_type' => 'authorization_code',
                'client_id' => $this->app_id,
                'client_secret' => $this->app_secret,
                'redirect_uri' => $this->callback_url,
                'code' => $code,
            ]
        ];
        $response = wp_remote_post($this->tokenUrl, $body);
        if (is_wp_error($response)) {
            $errorTitle = 'API Error';
            $errorMsg = $response->get_error_message();
            $oauthData = [
                'error_title' => $errorTitle,
                'error_msg' => $errorMsg,
                'refresh_token' => false,
                'authentifizierung' => false
            ];
            update_option($this->basename . '/oauth_api_data', $oauthData);
            delete_option($this->basename . '/refresh_token');
            wp_redirect($redirectAdmin);
            exit();
        }

        $response = json_decode($response['body'], true);
        $accessToken = $response['access_token'] ?? null;
        if (!$accessToken) {
            if (isset($response['hint'])) {
                $errorTitle = 'Error: ' . $response['hint'];
            }
            if (isset($response['message'])) {
                $errorMsg = $response['message'];
            }
            $oauthData = [
                'error_title' => $errorTitle,
                'error_msg' => $errorMsg,
                'refresh_token' => false,
                'authentifizierung' => false
            ];
            update_option($this->basename . '/oauth_api_data', $oauthData);
            delete_option($this->basename . '/refresh_token');
            wp_redirect($redirectAdmin);
            exit();
        }

        $validateJwt = $this->check_jwt_token($accessToken);
        if (!$validateJwt['status']) {
            update_option($this->basename . '/oauth_api_data', $validateJwt);
            delete_option($this->basename . '/refresh_token');
            wp_redirect($redirectAdmin);
            exit();
        }

        $refreshToken = $response['refresh_token'] ?? false;
        $oauthData = [
            'error_title' => '',
            'error_msg' => '',
            'refresh_token' => $refreshToken,
            'authentifizierung' => true
        ];

        $expires_in = (int)$response['expires_in'] ?? 3600;
        update_option($this->basename . '/oauth_api_data', $oauthData);

        $token = [
            'access_token' => $accessToken,
            'expires_in' => current_time('timestamp') + $expires_in,
        ];
        update_option($this->basename . '/refresh_token', $refreshToken);
        update_option($this->basename . '/access_token', $token);
        update_option($this->basename . '/code_referer', $_SERVER['HTTP_REFERER']);
        wp_redirect($redirectAdmin);
        exit();
    }

    public function oauth_api_download_product($code, $type, $slug)
    {
        include ABSPATH . '/wp-includes/pluggable.php';
        if (!function_exists('unzip_file')) {
            include ABSPATH . '/wp-admin/includes/file.php';
        }


        $error = '&code_error=1';
        if (!$code || !$type || !$slug) {
            wp_redirect(admin_url('admin.php?page=wp-oauth2-client'.$error));
        }

        $url = $this->server_url . '/api/' . $code . '/lizenz-product-download';
	    $access_token = $this->oauth_login_get_access_token();

        if (!$access_token['status']) {
            return $access_token;
        }

        $access_token = $access_token['access_token'];

        $body = [
            'method' => 'GET',
            'timeout' => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'sslverify' => true,
            'blocking' => true,
            'headers' => [
                'Content-Type' => '/*/',
                'Authorization' => "Bearer $access_token"
            ],
            'body' => []
        ];

        $response = wp_remote_get($url, $body);
        $response_code = wp_remote_retrieve_response_code( $response );
        if(is_wp_error($response) || $response_code != 200){
         wp_redirect(admin_url('admin.php?page=wp-oauth2-client'.$error));
        }

        $install_dir = '';
        $filePath = '';
        switch ($type) {
            case '1':
                $install_dir = get_theme_root() . DIRECTORY_SEPARATOR;
                $filePath = $install_dir . $slug . '.zip';
                break;
            case'2':
                $install_dir = WP_PLUGIN_DIR . DIRECTORY_SEPARATOR;
                $filePath = $install_dir . $slug . '.zip';
                break;
        }

        if (!$filePath) {
            wp_redirect(admin_url('admin.php?page=wp-oauth2-client'. $error) );
        }

        $zipFile = $response['body'];

        if(isset($zipFile['error'])){
            wp_redirect(admin_url('admin.php?page=wp-oauth2-client') . '&error='.$zipFile['error']);

        }

        file_put_contents($filePath, $zipFile);
        WP_Filesystem();
        $unZipFile = unzip_file($filePath, $install_dir);
        if (is_wp_error($unZipFile)) {
            $error_string = $unZipFile->get_error_message();
            wp_redirect(admin_url('admin.php?page=wp-oauth2-client&error='.$error_string));

        }

        if (!$unZipFile) {
            wp_redirect(admin_url('admin.php?page=wp-oauth2-client&error=unzip-error'));

        }
        unlink($filePath);
        wp_redirect(admin_url('admin.php?page=wp-oauth2-client'));

    }

    public function oauth_api_download_file($code, $type, $slug)
    {

    }

    public function oauth2_get_client_data($url = null)
    {
        if (!$url) {
            $url = $this->server_url . '/' . $this->api_get_client;
        }
        $access_token = $this->oauth_login_get_access_token();

        if (!$access_token['status']) {
            return $access_token;
        }
        $access_token = $access_token['access_token'];

        $args = [
            'method' => 'POST',
            'timeout' => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking' => true,
            'sslverify' => true,
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
                'Authorization' => "Bearer $access_token"
            ],
            'body' => [
                'client_id' => $this->app_id,
                'client_secret' => $this->app_secret,
                'redirect_uri' => $this->callback_url
            ]
        ];

        $response = wp_remote_post($url, $args);

        if (is_wp_error($response)) {
            $errorTitle = 'API Error Response';
            return [
                'error_title' => $errorTitle,
                'error_msg' => $response->get_error_message(),
                'status' => false
            ];
        }

        return json_decode($response['body'], true);
    }

    public function fn_api_get_callback($uri, $accept = '*/*'): array
    {

        $url = $this->server_url . '/api/' . $uri;
        $access_token = $this->oauth_login_get_access_token();
        if (!$access_token['status']) {
            return $access_token;
        }

        $access_token = $access_token['access_token'];

        $body = [
            'method' => 'GET',
            'timeout' => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'sslverify' => true,
            'blocking' => true,
            'headers' => [
                'Content-Type' => $accept,
                'Authorization' => "Bearer $access_token"
            ],
            'body' => []
        ];

        $response = wp_remote_get($url, $body);
        if (is_wp_error($response)) {
            return [
                'error_title' => 'API Error',
                'error_msg' => $response->get_error_message(),
            ];
        }

        return json_decode($response['body'], true);

    }

    public function fn_get_upload_token($uri, $accept = '*/*')
    {
        $url = $this->server_url . '/api/' . $uri;
        $access_token = $this->oauth_login_get_access_token();

        if (!$access_token['status']) {
            return $access_token;
        }

        $access_token = $access_token['access_token'];
        $body = [
            'method' => 'GET',
            'timeout' => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'sslverify' => true,
            'blocking' => true,
            'headers' => [
                'Content-Type' => $accept,
                'Authorization' => "Bearer $access_token"
            ],
            'body' => []
        ];
        wp_remote_get($url, $body);
    }

    public function fn_product_download($uri)
    {
        $url = $this->server_url . $uri;
        $access_token = $this->oauth_login_get_access_token();
        if (!$access_token['status']) {
            return $access_token;
        }

        $access_token = $access_token['access_token'];
        $body = [
            'method' => 'GET',
            'timeout' => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'sslverify' => true,
            'blocking' => true,
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
                'Authorization' => "Bearer $access_token"
            ],
            'body' => []
        ];
        $response = wp_remote_get($url, $body);
        if (is_wp_error($response)) {
            return [
                'error_title' => 'API Error',
                'error_msg' => $response->get_error_message(),
            ];
        }
        return $response['body'];
    }

    public function fn_api_post_callback($uri, $bodyArr = '', $accept = '*/*'): array
    {

        $url = $this->server_url . '/api/' . $uri;
        $access_token = $this->oauth_login_get_access_token();
        if (!$access_token['status']) {
            return $access_token;
        }

        $access_token = $access_token['access_token'];

        if (!$bodyArr) {
            $bodyArr = json_encode([]);
        }

        $body = [
            'method' => 'POST',
            'timeout' => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'sslverify' => true,
            'blocking' => true,
            'headers' => [
                //'Content-Type' => $accept,
                'Content-Type' => 'application/x-www-form-urlencoded',
                'Authorization' => "Bearer $access_token"
            ],
            'body' => $bodyArr
        ];

        $response = wp_remote_post($url, $body);
        if (is_wp_error($response)) {
            return [
                'error_title' => 'API Error',
                'error_msg' => $response->get_error_message(),
            ];
        }

        return json_decode($response['body'], true);

    }

    private function oauth_login_set_access_token($loginCall = true): array
    {
        if ($loginCall) {
            $refreshToken = get_option($this->basename . '/refresh_token');
            if (isset($refreshToken)) {
                $isRefreshToken = $this->get_refresh_token();
                if ($isRefreshToken['status']) {
                    $oauthData = get_option($this->basename . '/oauth_api_data');
                    $oauthData ['authentifizierung'] = true;
                    update_option($this->basename . '/oauth_api_data', $oauthData);

                    return $isRefreshToken;
                } else {
                    delete_option($this->basename . '/refresh_token');
                    //$oauthData = get_option( $this->basename . '/oauth_api_data' );
                    //$oauthData ['authentifizierung'] = false;
                    //update_option( $this->basename . '/oauth_api_data', $oauthData );
                }
            }
        }

        $body = [
            'method' => 'POST',
            'timeout' => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking' => true,
            'sslverify' => true,
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
            ],
            'body' => [
                'grant_type' => 'client_credentials',
                'client_id' => $this->app_id,
                'client_secret' => $this->app_secret,
                'scope' => $this->client_scopes,
            ]
        ];
        $response = wp_remote_post($this->tokenUrl, $body);

        if (is_wp_error($response)) {
            $errorTitle = 'API Token Error';
            $errorMsg = $response->get_error_message();

            return [
                'error_code' => $response->get_error_code(),
                'error_title' => $errorTitle,
                'error_msg' => $errorMsg,
                'status' => false
            ];
        }
        $errorMsg = '';
        $response = json_decode($response['body'], true);
        $accessToken = $response['access_token'] ?? null;
        if (!$accessToken) {
            if (isset($response['message'])) {
                $errorMsg = $response['message'];
            }

            return [
                'error_title' => 'Invalid Client',
                'error_msg' => $errorMsg,
                'status' => false
            ];
        }

        $validateJwt = $this->check_jwt_token($accessToken);
        if (!$validateJwt['status']) {
            return $validateJwt;
        }

        $expires_in = (int)$response['expires_in'] ?? 3600;

        $token = [
            'access_token' => $accessToken,
            'expires_in' => current_time('timestamp') + $expires_in,
        ];
        update_option($this->basename . '/access_token', $token);
        delete_option($this->basename . '/refresh_token');
        return ['status' => true, 'access_token' => $accessToken, 'expires_in' => $expires_in];
    }

    private function get_refresh_token(): array
    {

        $refresh_token = get_option($this->basename . '/refresh_token') ?? null;
        if (!$refresh_token) {
            return [
                'status' => false,
                'error_msg' => 'No refresh token available',
                'error_title' => 'Token error',
            ];
        }

        $body = [
            'method' => 'POST',
            'timeout' => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking' => true,
            'sslverify' => true,
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
            ],
            'body' => [
                'grant_type' => 'refresh_token',
                'refresh_token' => $refresh_token,
                'client_id' => $this->app_id,
                'client_secret' => $this->app_secret,
                'scope' => $this->client_scopes,
            ]
        ];

        $response = wp_remote_post($this->tokenUrl, $body);
        if (is_wp_error($response)) {
            $errorTitle = 'API Token Error';
            $errorMsg = $response->get_error_message();

            return [
                'error_code' => $response->get_error_code(),
                'error_title' => $errorTitle,
                'error_msg' => $errorMsg,
                'status' => false
            ];
        }

        $errorMsg = '';
        $response = json_decode($response['body'], true);
        $accessToken = $response['access_token'] ?? null;
        if (!$accessToken) {
            if (isset($response['message'])) {
                $errorMsg = $response['message'];
            }

            return [
                'error_title' => 'Invalid Client',
                'error_msg' => $errorMsg,
                'status' => false
            ];
        }
        $validateJwt = $this->check_jwt_token($accessToken);
        if (!$validateJwt['status']) {
            return $validateJwt;
        }

        $expires_in = (int)$response['expires_in'] ?? 3600;

        $token = [
            'access_token' => $accessToken,
            'expires_in' => current_time('timestamp') + $expires_in,
        ];

        $refreshToken = $response['refresh_token'] ?? false;
        if ($refreshToken) {
            update_option($this->basename . '/refresh_token', $refreshToken);
        } else {
            delete_option($this->basename . '/refresh_token');
        }

        update_option($this->basename . '/access_token', $token);

        return [
            'access_token' => $accessToken,
            'expires_in' => current_time('timestamp') + $expires_in,
            'status' => true
        ];
    }

    public function oauth_login_get_access_token(): array
    {
      //  delete_option( $this->basename . '/access_token' );
        $sToken = get_option($this->basename . '/access_token');
        if (!$sToken) {
            return $this->oauth_login_set_access_token();
        }

        if (current_time('timestamp') > $sToken['expires_in']) {
            return $this->oauth_login_set_access_token();
        }

        return [
            'status' => true,
            'access_token' => $sToken['access_token']
        ];
    }

    public function oauth_login_remove_access_token(): void
    {
        setcookie("access_token", "", 1, '/');
        unset($_COOKIE["access_token"]);
        //$oauthData = get_option($this->basename . '/oauth_api_data');
        //$oauthData ['authentifizierung'] = false;
        //update_option( $this->basename . '/oauth_api_data', $oauthData );
        delete_option($this->basename . '/access_token');
    }

    private function check_jwt_token($accessToken): array
    {
        try {
            $arrContextOptions = array(
                "ssl" => array(
                    "verify_peer" => false,
                    "verify_peer_name" => false,
                ),
            );
            $jwks = JWK::parseKeySet(json_decode(file_get_contents($this->wellKnown, false, stream_context_create($arrContextOptions)), true));
            JWT::$leeway = 10;
            JWT::decode($accessToken, $jwks[$this->jwt_id]);
        } catch (Exception $e) {
            return [
                'error_title' => 'Error decoding JWT',
                'error_msg' => $e->getMessage(),
                'status' => false
            ];
        }

        return ['status' => true];
    }

    public function fn_wp_oauth_client_sync(): void
    {

        $settings = get_option('wp_oauth2_client_settings');
        if ($this->main->url_check($settings['server_url'])) {
            $data = $this->oauth2_get_client_data();
            if (isset($data['cronjob']) && !$data['cronjob']) {
                if ($settings['cron_sync_interval']) {
                    $settings['cron_sync_interval'] = '';
                    wp_clear_scheduled_hook('wp_oauth_client_sync');
                    update_option('wp_oauth2_client_settings', $settings);
                }
            }
            if ($settings['cron_sync_interval'] != $data['cronjob']) {
                if ($data['cronjob']) {
                    wp_clear_scheduled_hook('wp_oauth_client_sync');
                    @apply_filters($this->basename . '/fn_oath2_client_run_schedule_task', false);
                    $settings['cron_sync_interval'] = $data['cronjob'];
                    update_option('wp_oauth2_client_settings', $settings);
                }
            }

            $failArr = [];
            $localData = get_option($this->basename . '/lizenz_data');
            if ($localData) {

                foreach ($localData as $tmp) {
                    $url = $settings['server_url'] . '/api/' . $tmp['product_license'] . '/wp-cron' . '?redirect_uri=' . site_url();
                    $body = [
                        'method' => 'GET',
                        'timeout' => 45,
                        'redirection' => 5,
                        'httpversion' => '1.0',
                        'sslverify' => true,
                        'blocking' => true,
                        'headers' => [
                            'Content-Type' => '*/*',
                        ],
                        'body' => []
                    ];
                    $response = wp_remote_get($url, $body);
                    if (is_wp_error($response)) {
                        continue;
                    }
                    $response = json_decode($response['body'], true);

                    $error = $response['error'] ?? '';
                    if ($error) {
                        $item = [
                            'license' => $tmp['product_license'],
                            'type' => $tmp['config']['type'],
                            'slug' => $tmp['config']['basename'],
                            'file' => $tmp['config']['aktivierungs_file_path'],
                            'error' => $response['error'],
                            'delete_file' => $response['delete_file']
                        ];
                        $failArr[] = $item;
                    }
                }
            }
            $theme = '';
            $licenseProducts = get_option($this->basename . '/lizenz_products') ?? NULL;
            if($licenseProducts){
                foreach ($licenseProducts as $tmp){
                    if ($tmp['raw_type'] == 'plugin') {
                        if (is_plugin_active($tmp['basename'] . '/' . $tmp['basename'] . '.php')) {
                            $isLocalActive = $this->find_install_product($localData, $tmp['basename']);
                            if(get_option($tmp['basename'].'_product_install_authorize') && !$isLocalActive){
                                deactivate_plugins($tmp['basename'] . '/' . $tmp['basename'] . '.php');
                                delete_option($tmp['basename'] . '_product_install_authorize');
                            }
                        }
                    }
                    if ($tmp['raw_type'] == 'theme') {
                        $isInstall = apply_filters($this->basename . '/is_theme_install', $tmp['basename']);
                        $isLocalActive = $this->find_install_product($localData, $tmp['basename']);
                        //var_dump($isLocalActive);
                        if($isInstall && get_option($tmp['basename'].'_product_install_authorize') && !$isLocalActive){
                            $all_themes = wp_get_themes();
                            $re = sprintf('/%s?+/', $tmp['basename']);
                            foreach ($all_themes as $key => $val){
                                if(preg_match($re, $key)){
                                    continue;
                                }
                                $theme = $key;
                            }
                            if($theme){
                               switch_theme($theme);
                            }
                            update_option($tmp['basename'] . '_product_install_authorize', 0);
                        }
                    }
                }
            }

            if ($failArr) {
                foreach ($failArr as $tmp) {

                    if ($tmp['type'] == 'plugin') {
                        if (is_plugin_active($tmp['slug'] . '/' . $tmp['slug'] . '.php')) {
                            deactivate_plugins($tmp['slug'] . '/' . $tmp['slug'] . '.php');
                        }
                        update_option($tmp['slug'] . '_product_install_authorize', 0);
                        if ($tmp['delete_file']) {
                            $file = WP_PLUGIN_DIR . '/' . $tmp['slug'] . '/' . $tmp['file'];
                            if (is_file($file)) {
                                unlink($file);
                            }
                        }
                    }
                    if ($tmp['type'] == 'theme') {
                        $isInstall = apply_filters($this->basename . '/is_theme_install', $tmp['slug']);
                        $isLocalActive = $this->find_install_product($localData, $tmp['slug']);
                        if($isInstall && get_option($tmp['slug'].'_product_install_authorize') && $isLocalActive){
                            $all_themes = wp_get_themes();
                            $re = sprintf('/%s?+/', $tmp['slug']);
                            foreach ($all_themes as $key => $val){
                                if(preg_match($re, $key)){
                                    continue;
                                }
                                $theme = $key;
                            }
                            if($theme){
                                switch_theme($theme);
                            }
                            if ($tmp['delete_file']) {
                                $file = get_theme_root() . '/' . $tmp['slug'] . '/' . $tmp['file'];
                                if (is_file($file)) {
                                    unlink($file);
                                }
                            }
                            update_option($tmp['basename'] . '_product_install_authorize', 0);
                        }
                    }
                }
            }
        }
    }

    private function find_install_product($data, $slug):bool
    {
        if($data && $slug){
            foreach ($data as $tmp){
               if($tmp['config']){
                   if($tmp['config']['basename'] == $slug){
                       return true;
                   }
               }
            }
        }

        return false;
    }
}