<?php
use App\Models\GenericBackoffice\WebsiteObject;

if (!function_exists('generateLink')) {
    function generateLink($link, $classes = '', $suffix = '')
    {
        if (empty($link)) {
            return "";
        }
        if (is_string($link)) {
            $link = json_decode($link);
        }

        if (is_array($link)) {
            $link = (object) $link;
        }

        $url = "";

        if ($link->isExternal && !$link->url || !$link->isExternal && !$link->objectId) {
            return "";
        } else {
            $url = $link->url;
        }

        if ($link->isExternal) {
            return $link->url;
        } else {
            $uri = WebsiteObject::select('uri')
                ->where('website_object_id', $link->objectId)
                ->first();
            if (empty($uri)) {
                return "";
            }
            $url = lang_url($uri->uri);
        }

        $label = $link->label ? $link->label : "";

        return '<a href="'.$url.'" class="'.$classes.'" >'.$label.$suffix.'</a>';
    }
}

if (!function_exists('getFilterHash')) {
    function getFilterHash($filtersInput)
    {
        $hash = "";
        foreach ($filtersInput as $filterType => $value) {
            if (!empty($value)) {
                if (!empty($hash)) {
                    $hash .= "&";
                }
                $hash .= $filterType."=".$value;
            }
        }

        if (!empty($hash)) {
            $hash = "#".$hash;
        }

        return $hash;
    }
}

if (!function_exists('checkRecaptcha')) {
    function checkRecaptcha($response, $action)
    {
        $parameters = http_build_query([
            'secret' => config('backoffice.recaptcha.private_key'),
            'remoteip' => request()->ip(),
            'response' => $response,
        ]);
        $url = 'https://www.google.com/recaptcha/api/siteverify?'.$parameters;
        $checkResponse = null;
        // prefer curl, but fall back to file_get_contents
        if ('curl' === Config::get('backoffice.recaptcha.driver') && function_exists('curl_version')) {
            $curl = curl_init($url);
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_TIMEOUT, Config::get('backoffice.recaptcha.options.curl_timeout', 1));
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            $checkResponse = curl_exec($curl);
        } else {
            $checkResponse = file_get_contents($url);
        }
        if (is_null($checkResponse) || empty($checkResponse)) {
            return false;
        }
        $decodedResponse = json_decode($checkResponse, true);
        return $decodedResponse['success'] && $decodedResponse['action'] === $action;
    }
}
