<?php

use App\Libs\Facades\ContentTypes;
use App\Libs\Facades\Localization;
use App\Libs\Facades\RequestContext;
use App\Models\WebsiteObject;
use Illuminate\Support\Str;

if (!function_exists('generateFormField')) {
    function generateFormField($fieldName, $field, $lists)
    {

        switch ($field["fieldType"]) {
            case "textbox":
                $attributes = array(
                    'class' => 'input',
                    'maxlength' => '255',
                    'size' => '50'
                );

                if (!empty($field['fieldMaxSize'])) {
                    $attributes['maxlength'] = $field['fieldMaxSize'];
                }

                if (!empty($field['fieldSize'])) {
                    $attributes['size'] = $field['fieldSize'];
                }

                return html()->text($fieldName)->attributes($attributes);
            case "textarea":
                return html()->textarea($fieldName)->attributes(['cols' => '60']);
            case "tinyMCE":
                return html()->textarea($fieldName)->attributes(['class' => 'mceEditor', 'cols' => '60']);
            case "checkbox":
                return html()->checkbox($fieldName, true)->attributes(['class' => 'checkbox']);
            case "calendar":
                $attributes = array(
                    'class' => 'input',
                    'rel' => 'input_calendar',
                    'maxlength' => '10',
                    'size' => '10'
                );

                if (!empty($field['fieldMaxSize'])) {
                    $attributes['maxlength'] = $field['fieldMaxSize'];
                }

                if (!empty($field['fieldSize'])) {
                    $attributes['size'] = $field['fieldSize'];
                }

                $html = html()->text($fieldName)->attributes($attributes);

                if (!Str::contains($field["validation"], "required")) {
                    $html .= '<a href="#" data-delete-input="'.$fieldName.'"><img src="'.config("path.backoffice.images_path").'/delimage.jpeg" /></a>';
                }

                return $html;
            case "calendar_time":
                $attributes = array(
                    'class' => 'input',
                    'rel' => 'input_calendar_time',
                    'maxlength' => '19',
                    'size' => '19'
                );

                if (!empty($field['fieldMaxSize'])) {
                    $attributes['maxlength'] = $field['fieldMaxSize'];
                }

                if (!empty($field['fieldSize'])) {
                    $attributes['size'] = $field['fieldSize'];
                }

                $html = html()->text($fieldName)->attributes($attributes);

                if (!Str::contains($field["validation"], "required")) {
                    $html .= '<a href="#" data-delete-input="'.$fieldName.'"><img src="'.config("path.backoffice.images_path").'/delimage.jpeg" style="margin-top: 10px" /></a>';
                }

                return $html;
            case "file":
            case "image":
                $attributes = array(
                    'style' => 'vertical-align:top'
                );
                return html()->file($fieldName)->attributes($attributes);
            case "combobox":
                if (isset($lists[$field['name']])) {
                    $list = $lists[$field['name']]['list'];
                } else {
                    $list = array();
                }

                return html()->select($fieldName, ['' => ''] + $list)->attributes(['class' => 'select']);
            case "list_checkbox":
                if (isset($lists[$field['name']])) {
                    $list = $lists[$field['name']]['list'];
                    $selectedValues = $lists[$field['name']]['selectedValues'];
                } else {
                    $list = array();
                    $selectedValues = array();
                }

                $checkboxes = '';

                foreach ($list as $key => $value) {
                    $checked = array_key_exists($key, $selectedValues);
                    $checkboxes .=
                        '<div class="fleft" style="width:200px;height:25px">'.
                        html()->checkbox($fieldName.'[]', $checked)->value($key)->attributes(['class' => 'checkbox', 'style' => 'margin:0 5px 0 0']).
                        $value.
                        '</div>';
                }

                return $checkboxes;

        }
        return "";
    }
}

if (!function_exists('generateDeleteFile')) {
    function generateDeleteFile($fieldName, $field)
    {
        if (!empty($field["validation"]) && Str::contains($field["validation"], "required") === false) {
            return '<div class="fleft" style="margin:0 0 0 10px">'.html()->checkbox("delete_{$fieldName}", true)->attributes([
                    'class' => 'checkbox fleft', 'style' => 'margin:6px 2px 0 10px'
                ]).'<div class="fleft" style="margin-top: 5px;">delete file</div></div>';
        }

        return "";
    }
}

if (!function_exists('generateLink')) {
    function generateLink($link, $classes = '', $suffix = '', $style = '', $allowTarget = false, $overrideLabel = null, $noClasses = false)
    {
        if (empty($link)) {
            return "";
        }
        if (is_string($link)) {
            $link = json_decode($link);
        }
        if ($overrideLabel) {
            $label = $overrideLabel;
        } else {
            $label = $link->label ? $link->label : "";
        }

        if (!empty($link->contentType) && $link->contentType === 'contact') {
            $websiteObject = WebsiteObject::where('website_object_id', $link->objectId * 1)
                ->first();

            if ($websiteObject == null) {
                return '';
            }
            $contact = $websiteObject->objectable;
            return '<a href="#" class="contact-open '.$classes.'" '
                . ($style ? 'style="'.$style.'" ' : '')
                . ' data-name="' . $contact->name . '"'
                . ' data-contact="' . base64_encode(json_encode(["Contact_person" => $contact->name ])) . '"'
                . ' data-controller="components/form-modal" data-popupid="contact-us-modal" '
                . '>' . $label.$suffix . '<span class="link-underline"></a>';
        } else if (!empty($link->contentType) && $link->contentType === 'pardot_form') {
            $websiteObject = WebsiteObject::where('website_object_id', $link->objectId * 1)
                ->first();

            if ($websiteObject == null) {
                return '';
            }
            $pardotForm = $websiteObject->objectable;
            $extraAttrs = [];
            if ($pardotForm->type == 'event' && $pardotForm->extra_title) {
                $extraAttrs['Event_Title'] = htmlspecialchars($pardotForm->extra_title);
            }
            if ($pardotForm->type == 'webinar' && $pardotForm->extra_title) {
                $extraAttrs['Webinar_Title'] = htmlspecialchars($pardotForm->extra_title);
            }
            return '<a href="#" class="'.$classes.'" '
                . ($style ? 'style="'.$style.'" ' : '')
                . ' data-formid="' . $pardotForm->id . '"'
                . ' data-formurl="' . $pardotForm->form_url . '"'
                . ' data-controller="components/form-modal" data-popupid="pardot-modal" '
                . ' data-fields="' .base64_encode(json_encode($extraAttrs)) . '"'
                . '>' . $label.$suffix . '<span class="link-underline"></a>';
        } else if (!empty($link->contentType) && $link->contentType === 'publication') {
            $websiteObject = WebsiteObject::where('website_object_id', $link->objectId * 1)
                ->first();

            if ($websiteObject == null) {
                return '';
            }
            $publication = $websiteObject->objectable;

            if (!$publication->pardot_url) {
                return '';
            }

            return '<a href="#" class="' . $classes . '" '
                . ($style ? 'style="'.$style.'" ' : '')
                . ' data-download_id="' . $publication->id . '"'
                . ' data-download="' . base64_encode(json_encode(["title" => $publication->title, "url" => $publication->pardot_url ])) . '"'
                . ' data-controller="components/form-modal" data-popupid="download-modal">' . $label.$suffix . '<span class="link-underline"></span></a>';
        } else if (!empty($link->contentType) && $link->contentType === 'overlay') {
            $websiteObject = WebsiteObject::where('website_object_id', $link->objectId * 1)
                ->first();

            if ($websiteObject == null) {
                return '';
            }

            $overlayReg = RequestContext::get('overlays_reg');
            if (empty($overlayReg)) {
                $overlayReg = [];
            }

            if (!in_array($websiteObject->object_id, $overlayReg)) {
                $overlayReg[] = $websiteObject->object_id;
                RequestContext::set('overlays_reg', $overlayReg);
            }

            return '<a href="#" class="'.$classes.'" '
                . ($style ? 'style="'.$style.'" ' : '')
                . ' data-controller="components/overlay-trigger" data-overlay-id="' . $websiteObject->object_id . '">' . $label.$suffix . '<span class="link-underline"></a>';
        } else {
            $url = getUrlFromLink($link);
            $target = '';

            if($link->isExternal && $allowTarget || !empty($link->isNewtab) && $link->isNewtab) {
                $target = ' target="_blank" ';
            }

            if ($url) {
                return '<a href="'.$url.'" class="'.$classes.'" ' . $target
                    .($style ? 'style="'.$style.'" ' : '').' >'.$label.$suffix.'<span class="link-underline"></a>';
            } else {
                return "";
            }
        }
    }
}

if (!function_exists('getUrlFromLink')) {
    function getUrlFromLink($link)
    {
        if (empty($link)) {
            return "";
        }

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

        if ($link->isExternal) {
            return $link->url;
        } else {
            $langId = Localization::getActiveLocale();
            $uri = WebsiteObject::select('lang_uri', 'content_type', 'lang_slug')
                ->join('website_objects_lang', 'website_objects.website_object_id',
                    '=', 'website_objects_lang.website_object_id')
                ->where('wo_language_id', $langId)
                ->where('website_objects.website_object_id', $link->objectId)
                ->first();

            // If object hasn't a prebuilt uri, checks the content type to try to build one
            if (!empty($uri) && !$uri->lang_uri) {
                $website = Localization::getWebsite();
                $contentType = ContentTypes::find($uri->content_type);
                $baseUri = $contentType->getBaseUri($website->id);
                if ($baseUri && is_string($baseUri)) {
                    $uri = $baseUri.'/'.$uri->lang_slug;
                }
            } elseif (!empty($uri)) {
                $uri = $uri->lang_uri;
            }

            if (empty($uri)) {
                return "";
            }
            $url = lang_url($uri);
        }
        return $url;
    }
}

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('genSelectOptions')) {
    function genSelectOptions($selectField, $noPlaceholder = false, $multiple = false)
    {
        $optionStrings = explode("\n", $selectField->options);
        $defaultValue = $selectField->default_value;
        $html = '';
        if (!$multiple) {
            $html = '<option value="">Select</option>';
            if (!$noPlaceholder) {
                $html = '<option value="">'.$selectField->label.'</option>';
            }
        }
        foreach ($optionStrings as $optionString) {
            $option = explode(":", $optionString);
            if (sizeof($option) != 2) {
                continue;
            }
            $optionValue = $option[0];
            $optionLabel = $option[1];
            $selected = $defaultValue == $optionValue ? ' selected ' : '';

            $html .= '<option '.$selected.' value="'.$optionValue.'">'.$optionLabel.'</option>';
        }
        return $html;
    }
}
if (!function_exists('genRadioOptions')) {
    function genRadioOptions($radioField)
    {
        $optionStrings = explode("\n", $radioField->options);
        $defaultValue = $radioField->default_value;
        $html = "";
        foreach ($optionStrings as $optionString) {
            $option = explode(":", $optionString);
            if (sizeof($option) != 2) {
                continue;
            }
            $optionValue = $option[0];
            $optionLabel = $option[1];
            $selected = $defaultValue == $optionValue ? ' checked ' : '';
            $optionId = $radioField->field_id.'_'.$optionValue;
            $html .= '<div class="radio-option">';
            $html .= '<input id="'.$optionId
                .'" name="'.$radioField->field_name.'" type="radio" '
                .$selected.' value="'.$optionValue.'"/>';
            $html .= '<label for="'.$optionId.'">'.$optionLabel.'</label>';
            $html .= '</div>';
        }
        return $html;
    }
}
if (!function_exists('insertCustomForm')) {
    function insertCustomForm($formSlug, $content)
    {
        $view = view('frontend.cf.templates.components.custom_form')->with('formSlug', $formSlug);
        $content = preg_replace("((<p>)?\[custom_form:$formSlug\](</p>)?)", $view, $content, 1);
        return $content;
    }
}
if (!function_exists('applyExtras')) {
    function applyExtras($content)
    {
        $matches = [];
        preg_match_all("(\[([a-z0-9_-]*):([a-z0-9_-]*)\])", $content, $matches);
        if (sizeof($matches) == 3) {
            foreach ($matches[1] as $i => $extra) {

                switch ($extra) {
                    case 'custom_form' :
                        $content = insertCustomForm($matches[2][$i], $content);
                        break;
                }
            }
        }
        return $content;
    }
}
if (!function_exists('applyForecolor')) {
    function applyForecolor($content, $color)
    {
        if (!$color) {
            return $content;
        }
        $tags = ['p', 'h1', 'h2', 'h3', 'h4', 'h5'];
        foreach ($tags as $tag) {
            $style = ' style="color: '.$color.'"';
            $content = str_replace("<{$tag}>", "<{$tag} {$style}>", $content);
        }
        return $content;
    }
}

if (!function_exists('generateObjectLinkJson')) {
    function generateObjectLinkJson($object, $label = '')
    {
        $label = $label ? $label : __('frontend.read_more');
        $ctaData = [
            'label' => $label,
            'isExternal' => true,
            'url' => lang_url($object->lang_uri)
        ];

        return json_encode($ctaData);
    }
}

if (!function_exists('getCtaLink')) {
    function getCtaLink($cta)
    {
        $link = '';

        if (empty($cta)) {
            return '';
        }

        if (is_string($cta)) {
            $cta = json_decode($cta);
        }

        if (!empty($cta) && $cta->objectId) {
            $wo = WebsiteObject::where('website_object_id', $cta->objectId)
                ->first();
            $link = "/$wo->wo_language_id$wo->lang_uri";
        }

        return $link;
    }
}

if (!function_exists('ctaNotEmpty')) {
    function ctaNotEmpty($cta)
    {
        if (empty($cta)) {
            return false;
        }

        if (is_string($cta)) {
            $cta = json_decode($cta);
        }

        return !empty($cta) && ($cta->objectId || $cta->url);
    }
}

if (!function_exists('getRequestContext')) {
    function getRequestContext($key)
    {
        return RequestContext::get($key);
    }
}

if (!function_exists('setRequestContext')) {
    function setRequestContext($key, $value)
    {
        return RequestContext::set($key, $value);
    }
}
