<?php

namespace CCDN\Helpers\Modules\Calendar;

use dle_template;

class XFieldTpl
{
    /**
     * @param  dle_template  $dle_template
     * @param $post
     * @return dle_template
     */
    public static function handler($dle_template, $post)
    {
        global $config, $lang;

        $xFound = false;
        $xfields = null;
        $tplCopy = $dle_template->copy_template;
        if (stripos($tplCopy, '[xf') !== false || stripos($tplCopy, '[ifxf') !== false) {
            $xFound = true;
            $xfields = xfieldsload();

            if (count($xfields)) {
                $temp_xf = $xfields;
                foreach ($temp_xf as $k => $v) {
                    if (stripos($tplCopy, $v[0]) === false) {
                        unset($xfields[$k]);
                    }
                }
                unset($temp_xf);
            }
        }


        if (!$xFound && empty($xfields)) {
            return $dle_template;
        }

        $post['xfields'] = stripslashes($post['xfields']);
        $postXfieldsData = xfieldsdataload($post['xfields']);

        foreach ($xfields as $value) {
            $preg_safe_name = preg_quote($value[0], "'");

            if ($value[20]) {

                $value[20] = explode(',', $value[20]);

                if ($value[20][0] and !in_array($member_id['user_group'], $value[20])) {
                    $postXfieldsData[$value[0]] = '';
                }

            }

            if ($value[3] === 'yesorno') {

                if ((int) $postXfieldsData[$value[0]]) {
                    $xFieldGiven = true;
                    $postXfieldsData[$value[0]] = $lang['xfield_xyes'];
                } else {
                    $xFieldGiven = false;
                    $postXfieldsData[$value[0]] = $lang['xfield_xno'];
                }

            } else {
                $xFieldGiven = !((string) $postXfieldsData[$value[0]] === '');
            }

            if (!$xFieldGiven) {
                $pattern = "/\[xfgiven_{$preg_safe_name}\](.*?)\[\/xfgiven_{$preg_safe_name}\]/sm";
                $pattern_2_open = "[xfnotgiven_{$value[0]}]";
                $pattern_2_close = "[/xfnotgiven_{$value[0]}]";

                $dle_template->copy_template = preg_replace($pattern, '', $dle_template->copy_template);
                $dle_template->copy_template = str_ireplace($pattern_2_open, '', $dle_template->copy_template);
                $dle_template->copy_template = str_ireplace($pattern_2_close, '', $dle_template->copy_template);

            } else {
                $pattern = "/\[xfnotgiven_{$preg_safe_name}\](.*?)\[\/xfnotgiven_{$preg_safe_name}\]/sm";
                $pattern_2_open = "[xfgiven_{$value[0]}]";
                $pattern_2_close = "[/xfgiven_{$value[0]}]";

                $dle_template->copy_template = preg_replace($pattern, '', $dle_template->copy_template);
                $dle_template->copy_template = str_ireplace($pattern_2_open, '', $dle_template->copy_template);
                $dle_template->copy_template = str_ireplace($pattern_2_close, '', $dle_template->copy_template);
            }

            if (strpos($dle_template->copy_template, "[ifxfvalue {$value[0]}") !== false) {
                $dle_template->copy_template = preg_replace_callback(
                    "#\\[ifxfvalue(.+?)\\](.+?)\\[/ifxfvalue\\]#is",
                    'check_xfvalue',
                    $dle_template->copy_template
                );
            }

            if ($value[6] and !empty($postXfieldsData[$value[0]])) {
                $temp_array = explode(',', $postXfieldsData[$value[0]]);
                $value3 = [];

                foreach ($temp_array as $value2) {

                    $value2 = trim($value2);

                    if ($value2) {

                        $value2 = str_replace(['&#039;', '&quot;', '&amp;'], ["'", '"', '&'], $value2);

                        if ($config['allow_alt_url']) {
                            $value3[] =
                                '<a href="'.$config['http_home_url'].'xfsearch/'.$value[0].'/'.rawurlencode(
                                    $value2
                                ).'/">'.$value2.'</a>';
                        } else {
                            $value3[] =
                                "<a href=\"{$PHP_SELF}?do=xfsearch&amp;xfname={$value[0]}&amp;xf=".rawurlencode($value2)."\">{$value2}</a>";
                        }

                    }

                }

                if (empty($value[21])) {
                    $value[21] = ', ';
                }

                $postXfieldsData[$value[0]] = implode($value[21], $value3);

                unset($temp_array, $value2, $value3);

            }

            if ($config['allow_links'] and $value[3] == 'textarea' and function_exists('replace_links')) {
                $postXfieldsData[$value[0]] = replace_links($postXfieldsData[$value[0]], $replace_links['news']);
            }

            if ($value[3] == 'image' and $postXfieldsData[$value[0]]) {

                $temp_array = explode('|', $postXfieldsData[$value[0]]);

                if (count($temp_array) > 1) {

                    $temp_alt = $temp_array[0];
                    $temp_value = $temp_array[1];

                } else {

                    $temp_alt = '';
                    $temp_value = $temp_array[0];

                }

                $path_parts = @pathinfo($temp_value);

                if ($value[12] and file_exists(
                        ROOT_DIR.'/uploads/posts/'.$path_parts['dirname'].'/thumbs/'.$path_parts['basename']
                    )
                ) {
                    $thumb_url = $config['http_home_url'].'uploads/posts/'.$path_parts['dirname'].'/thumbs/'
                        .$path_parts['basename'];
                    $img_url = $config['http_home_url'].'uploads/posts/'.$path_parts['dirname'].'/'
                        .$path_parts['basename'];
                } else {
                    $img_url = $config['http_home_url'].'uploads/posts/'.$path_parts['dirname'].'/'
                        .$path_parts['basename'];
                    $thumb_url = '';
                }

                if ($thumb_url) {
                    $dle_template->set("[xfvalue_thumb_url_{$value[0]}]", $thumb_url);
                    $postXfieldsData[$value[0]] =
                        "<a href=\"{$img_url}\" class=\"highslide\" target=\"_blank\"><img class=\"xfieldimage {$value[0]}\" src=\"{$thumb_url}\" alt=\"{$temp_alt}\"></a>";

                } else {
                    $dle_template->set("[xfvalue_thumb_url_{$value[0]}]", $img_url);
                    $postXfieldsData[$value[0]] =
                        "<img class=\"xfieldimage {$value[0]}\" src=\"{$img_url}\" alt=\"{$temp_alt}\">";

                }

                $dle_template->set("[xfvalue_image_url_{$value[0]}]", $img_url);

            }

            if ($value[3] === 'image' and !$postXfieldsData[$value[0]]) {
                $dle_template->set("[xfvalue_thumb_url_{$value[0]}]", '');
                $dle_template->set("[xfvalue_image_url_{$value[0]}]", '');
            }

            if ($value[3] === 'imagegalery' and $postXfieldsData[$value[0]] and stripos(
                    $dle_template->copy_template,
                    "[xfvalue_{$value[0]}"
                ) !== false
            ) {

                $fieldvalue_arr = explode(',', $postXfieldsData[$value[0]]);
                $gallery_image = [];
                $gallery_single_image = [];
                $xf_image_count = 0;
                $single_need = false;

                if (stripos($dle_template->copy_template, "[xfvalue_{$value[0]} image=") !== false) {
                    $single_need = true;
                }

                foreach ($fieldvalue_arr as $temp_value) {
                    $xf_image_count++;

                    $temp_value = trim($temp_value);

                    if ($temp_value === '') {
                        continue;
                    }

                    $temp_array = explode('|', $temp_value);

                    if (count($temp_array) > 1) {

                        $temp_alt = $temp_array[0];
                        $temp_value = $temp_array[1];

                    } else {

                        $temp_alt = '';
                        $temp_value = $temp_array[0];

                    }

                    $path_parts = @pathinfo($temp_value);

                    if ($value[12] and file_exists(
                            ROOT_DIR.'/uploads/posts/'.$path_parts['dirname'].'/thumbs/'.$path_parts['basename']
                        )
                    ) {
                        $thumb_url = $config['http_home_url'].'uploads/posts/'.$path_parts['dirname'].'/thumbs/'
                            .$path_parts['basename'];
                        $img_url = $config['http_home_url'].'uploads/posts/'.$path_parts['dirname'].'/'
                            .$path_parts['basename'];
                    } else {
                        $img_url = $config['http_home_url'].'uploads/posts/'.$path_parts['dirname'].'/'
                            .$path_parts['basename'];
                        $thumb_url = '';
                    }

                    if ($thumb_url) {

                        $gallery_image[] =
                            "<li><a href=\"{$img_url}\" onclick=\"return hs.expand(this, { slideshowGroup: 'xf_{$post['id']}_{$value[0]}' })\" target=\"_blank\"><img src=\"{$thumb_url}\" alt=\"{$temp_alt}\"></a></li>";
                        $gallery_single_image['[xfvalue_'.$value[0].' image="'.$xf_image_count.'"]'] =
                            "<a href=\"{$img_url}\" class=\"highslide\" target=\"_blank\"><img class=\"xfieldimage {$value[0]}\" src=\"{$thumb_url}\" alt=\"{$temp_alt}\"></a>";

                    } else {
                        $gallery_image[] =
                            "<li><img src=\"{$img_url}\" alt=\"{$temp_alt}\"></li>";
                        $gallery_single_image['[xfvalue_'.$value[0].' image="'.$xf_image_count.'"]'] =
                            "<img class=\"xfieldimage {$value[0]}\" src=\"{$img_url}\" alt=\"{$temp_alt}\">";
                    }

                }

                if ($single_need and count($gallery_single_image)) {
                    foreach ($gallery_single_image as $temp_key => $temp_value) {
                        $dle_template->set($temp_key, $temp_value);
                    }
                }

                $postXfieldsData[$value[0]] =
                    "<ul class=\"xfieldimagegallery {$value[0]}\">".implode($gallery_image)."</ul>";

            }

            if ($config['image_lazy']) {
                $postXfieldsData[$value[0]] =
                    preg_replace_callback('#<img(.+?)>#i', 'enable_lazyload', $postXfieldsData[$value[0]]);
            }

            $dle_template->set("[xfvalue_{$value[0]}]", $postXfieldsData[$value[0]]);

            if (preg_match(
                "#\\[xfvalue_{$preg_safe_name} limit=['\"](.+?)['\"]\\]#i",
                $dle_template->copy_template,
                $matches
            )
            ) {
                $count = (int) $matches[1];

                $postXfieldsData[$value[0]] = str_replace('><', '> <', $postXfieldsData[$value[0]]);
                $postXfieldsData[$value[0]] = strip_tags($postXfieldsData[$value[0]], '<br>');
                $postXfieldsData[$value[0]] = trim(
                    str_replace(
                        '<br>',
                        ' ',
                        str_replace(
                            '<br />',
                            ' ',
                            str_replace("\n", ' ', str_replace("\r", '', $postXfieldsData[$value[0]]))
                        )
                    )
                );
                $postXfieldsData[$value[0]] = preg_replace('/\s+/u', ' ', $postXfieldsData[$value[0]]);

                if ($count and dle_strlen($postXfieldsData[$value[0]], $config['charset']) > $count) {

                    $postXfieldsData[$value[0]] = dle_substr($postXfieldsData[$value[0]], 0, $count,
                        $config['charset']);

                    if (($temp_dmax = dle_strrpos($postXfieldsData[$value[0]], ' ', $config['charset']))) {
                        $postXfieldsData[$value[0]] =
                            dle_substr($postXfieldsData[$value[0]], 0, $temp_dmax, $config['charset']);
                    }

                }
                $dle_template->set($matches[0], $postXfieldsData[$value[0]]);
            }
        }

        global $category_id;
        $url_cat = $category_id;

        $GLOBALS['category_id'] = $post['category'];

        if (strpos($dle_template->copy_template, "[catlist=") !== false) {
            $dle_template->copy_template = preg_replace_callback("#\\[(catlist)=(.+?)\\](.*?)\\[/catlist\\]#is",
                "check_category", $dle_template->copy_template);
        }

        if (strpos($dle_template->copy_template, "[not-catlist=") !== false) {
            $dle_template->copy_template = preg_replace_callback("#\\[(not-catlist)=(.+?)\\](.*?)\\[/not-catlist\\]#is",
                "check_category", $dle_template->copy_template);
        }

        $GLOBALS['category_id'] = $url_cat;

        return $dle_template;
    }
}
