<?php
require_once (dirname(__FILE__) . "/../common/helpers.php");
$optres['js'][] = $path . 'assets/js/moment.min.js';
$optres['css'][] = $module_css_path . 'amodules/filter_adverts_list/css/filter_adverts_list_lazy_schema.css';
$optres['js'][] = $path . 'amodules/filter_adverts_list/js/filter_adverts_list_lazy_schema.js';
$filter_content_show = 0;

if(!function_exists("is_nofollow")) {
    function is_nofollow($nofollow_domains)
    {
        global $domain_id;

        $formated_domain_id = sprintf("%04.0f", $domain_id);

        if (strpos($nofollow_domains, $formated_domain_id) !== false) return true;

        return false;
    }
}

if (!isset($jsonld['filter_adverts_list'])) {
    $jsonld['filter_adverts_list'] = [];
}

ob_start();

$filter_title = (isset($module_params['filter_title']) && trim($module_params['filter_title']) != "") ? trim($module_params['filter_title']) : '';
$filter_description = (isset($module_params['filter_description']) && trim($module_params['filter_description']) != "") ? trim($module_params['filter_description']) : '';
$filter_id = (isset($module_params['filter_id']) && intval($module_params['filter_id']) > 0) ? intval($module_params['filter_id']) : 0;
$filter_pagination = (isset($module_params['filter_pagination']) && intval($module_params['filter_pagination']) > 0) ? intval($module_params['filter_pagination']) : 0;
$filter_range = (isset($module_params['filter_range']) && intval($module_params['filter_range']) > 0) ? intval($module_params['filter_range']) : 10;


$filter_locations = (isset($module_params['filter_locations']) && count($module_params['filter_locations'])>0 ) ? $module_params['filter_locations'] : array();
$filter_locations_tmp = array_keys($locations_map);

if($filter_id > 0) {

    $filter_friendly_url = '';
    $p_url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $p_f = parse_url($p_url);
    $b_f = parse_url($base_url);

    $filter_friendly_url = ltrim(str_replace($b_f['path'], '', $p_f['path']), '/');

    $canonical_link = $protocol . $p_f['host'] . $p_f['path'];
    $def_canonical_link = $canonical_link;

    $current_page = 1;
    if(isset($_GET['p']) && intval($_GET['p']) > 0) {
        $current_page = intval($_GET['p']);
        if($filter_pagination == 0) {
            $send301 = array("send301" => 1, "url" => $def_canonical_link);
        }
    }

    // Reset the current page if we do not care about pagination
    if($filter_pagination == 0) $current_page = 1;

    $filter_str = sprintf("%'.04d", $filter_id);
    $filter_adverts_key = "filter_adverts_" . $middle_catdom_module_id;
    //$pfcache->delete($filter_adverts_key);
    $filter_adverts = $pfcache->get($filter_adverts_key);
    if($filter_adverts == null) {

        $catdoms = array();
        $catdoms [] = $domain_id;
        $result_sub = mysql_query ("SELECT * FROM  domaincategories WHERE parent_id='$domain_id' AND active='yes';");
        if (mysql_num_rows($result_sub) <> 0){
            while($line_sub = mysql_fetch_array($result_sub)){
                $catdoms [] = intval($line_sub["catdom_id"]);
            }
        }

        $results = array();
        $q = "SELECT
                      a.*,
                      d.catdom_id as bound_catdom_id,
                      d.active as bound_active,
                      d.category_top as bound_top,
                      d.params as bound_params
                      FROM
                      advertisment a
                      LEFT JOIN domain_advertisment d
                        ON d.advertisment_id=a.advertisment_id AND d.catdom_id IN (" . (implode(",", $catdoms)) . ")
                      WHERE
                      a.active='yes'
                      AND a.filter_id LIKE ('%$filter_str%')
                      ";

        if (count($filter_locations) > 0) {

            foreach ($filter_locations as $i => $f_loc) {
                $filter_locations[$i] = "'" . $f_loc . "'";
            }

            $filter_locations_str = implode(",", $filter_locations);
            $q = "SELECT
                      a.*,
                      d.catdom_id as bound_catdom_id,
                      d.active as bound_active,
                      d.category_top as bound_top,
                      d.params as bound_params
                      FROM
                      (advertisment a,
                      advertisment_locations l)
                      LEFT JOIN domain_advertisment d ON d.advertisment_id=a.advertisment_id AND d.catdom_id IN (" . (implode(",", $catdoms)) . ")
                      WHERE
                      a.advertisment_id=l.advertisment_id
                      AND l.district IN ($filter_locations_str)
                      AND a.active='yes'
                      AND a.filter_id LIKE ('%$filter_str%')
                      ";
        }

        if (isset($_REQUEST['debug_filters'])) echo $q;


        //$wb_search_params['wb_adverts'] = array();

        //$qq [] = $q;

        $r = mysql_query($q) or die(mysql_error());
        if ($r && mysql_num_rows($r) > 0) {
            $count = 0;
            while ($line = mysql_fetch_assoc($r)) {
                $adv_id = $line['advertisment_id'];
                if (!isset($results[$adv_id])) {
                    $count++;
                    $results[$adv_id] = array();
                    $results[$adv_id]["order"] = 0;
                    $results[$adv_id]["categ_order"] = 0;
                    $results[$adv_id]["title_en"] = stripslashes($line["short_title_en"]);
                    $results[$adv_id]["advertisment_id"] = $line["advertisment_id"];
                    $results[$adv_id]["use_town_dir"] = false;
                    $results[$adv_id]["town_locations"] = array();
                    $results[$adv_id]["paying"] = false;
                    $results[$adv_id]["data"] = array_map('stripslashes', $line);
                }

                if ($line['bound_top'] == "yes") {
                    $results[$adv_id]["paying"] = true;
                    if ($line['bound_catdom_id'] == $domain_id) {
                        if ($results[$adv_id]["order"] < 10) {
                            $results[$adv_id]["order"] = 10;
                            $results[$adv_id]["categ_order"] = 10;
                        }

                    } elseif ($results[$adv_id]["order"] < 6) {
                        $results[$adv_id]["order"] = 6;
                        $results[$adv_id]["categ_order"] = 6;
                    }
                }

                if ($line['bound_active'] == "yes") {
                    $results[$adv_id]["paying"] = true;
                    if ($line['bound_catdom_id'] == $domain_id) {
                        if ($results[$adv_id]["order"] < 8) {
                            $results[$adv_id]["order"] = 8;
                            $results[$adv_id]["categ_order"] = 8;
                        }

                    } elseif ($results[$adv_id]["order"] < 6) {
                        $results[$adv_id]["order"] = 6;
                        $results[$adv_id]["categ_order"] = 6;
                    }
                }

                $params = $line['bound_params'];
                if (!empty($params) && $params != "") {
                    $params = unserialize(base64_decode($params));
                    if (is_array($params) && count($params) > 0) {
                        $results[$adv_id]["town_locations"] = $params;
                    }
                }


                //$wb_search_params['wb_adverts'][] = $line['adv_code'];


            }
            $filter_adverts = $results;
            unset($results);
            $pfcache->set($filter_adverts_key, $filter_adverts, 600);
        }
    }

    if(is_array($filter_adverts) && count($filter_adverts) > 0) {
        $results = $filter_adverts;
        $num_results = count($results);
        $filter_content_show = 1;

        $range = $filter_range;
        $num_pages = intval($num_results/$range);
        if($num_results % $range !== 0) $num_pages += 1;

        if($current_page > $num_pages) {
            $send301 = array("send301" => 1, "url" => $def_canonical_link);
        }

        if($filter_pagination == 1) {
            if($current_page > 1) {

                if ($current_page < $num_pages) {
                    $rel_next_page = $def_canonical_link . "?p=" . ($current_page + 1);
                    $rel_prev_page = $def_canonical_link . "?p=" . ($current_page - 1);
                    $canonical_link .= "?p=" . $current_page;
                } else {
                    $rel_prev_page = $canonical_link . "?p=" . ($current_page - 1);
                    $canonical_link .= "?p=" . $current_page;
                }
                if($current_page == 2) {
                    $rel_prev_page = $def_canonical_link;
                }
            }
            elseif($current_page == 1 && $num_pages > 1) {
                $rel_next_page = $canonical_link . "?p=2";
            }
        }

        $start = ($current_page - 1) * $range;

        if($num_results > $start + $range){
            $end = $start + $range;
        }
        else{
            $end = $num_results;
        }

        if(!isset($send404) || $send404 === false) {
            ?>
            <div class="filter-list">
                <?php
                if ($filter_title != '') {
                    echo '<header><h2>' . $filter_title . '</h2></header>';
                }

                if ($filter_description != '') {
                    echo '<p class="filter-desc">' . $filter_description . '</p>';
                }


                $order = array();
                $categ_order = array();
                $title_en = array();
                $advertisment_id = array();
                $town_locations = array();
                foreach ($results as $key => $row) {
                    $order [$key] = $row['order'];
                    $categ_order [$key] = $row['categ_order'];
                    $title_en [$key] = $row['title_en'];
                    $advertisment_id [$key] = $row['advertisment_id'];
                }

                array_multisort($categ_order, SORT_NUMERIC, SORT_DESC, $title_en, SORT_ASC, SORT_STRING, $results);

                //echo '<pre>', var_export($results, true), '</pre>';

                $i = 0;
                foreach ($results as $key => $row) {
                    $order[$i] = $row['order'];
                    $categ_order[$i] = $row['categ_order'];
                    $title_en[$i] = $row['title_en'];
                    $advertisment_id[$i] = $row['advertisment_id'];
                    $town_locations[$i] = $row['town_locations'];
                    $i++;
                }


                //echo "<hr>";


                $click_count_paths = array();

                if ($filter_pagination == 0) {
                    $start = 0;
                    $end = $num_results;
                }

                for ($i = $start; $i < $end; $i++) {
                    $paying_advert = false;


                    if (isset($results[$i])) {
                        $line = $results[$i]['data'];
                        $use_town_dir = false;
                        $current_advertisment_id = intval($line['advertisment_id']);
                        $adv_code = $line['adv_code'];

                        // Check if it is a paying advert
                        $paying_advert = $results[$i]['paying'];


                        $website = fix_url(trim($line['website']));
                        $show_website = intval($line['show_website']);
                        $nofollow_domains = $line["nofollow_domains"];


                        $advert_active = ($line['active'] == "yes") ? true : false;

                        $shortNameURL = $line["title_tr"];
                        $shortNameALT = str_replace('"', '', $line["short_title_en"]);

                        $thumbshot = trim($line['image']);
                        $thumbshot_file = dirname(__FILE__) . "/../../images/advertisments/advert_images/" . trim($line['image']);
                        $thumbshot_url = $protocol . $_SERVER['HTTP_HOST'] . "/images/advertisments/advert_images/" . trim($line['image']);
                        $has_thumbshot = ($thumbshot != "" && file_exists($thumbshot_file));
                        $has_thumbshot = false;

                        $box_class = "freelisting";
                        if ($categ_order[$i] == 10) $box_class = "freelisting featured_1";
                        if ($categ_order[$i] == 8) $box_class = "freelisting featured_2";
                        if ($categ_order[$i] == 6) $box_class = "freelisting featured_3";

                        $click_link_id = 'adv_' . $line['advertisment_id'];
                        if ($is_hotel) {
                            if ($paying_advert) {
                                if ($advert_active) {
                                    $click_count_paths [$click_link_id] = 'click_count.php?link=' . $line["website"] . '&amp;type=www&amp;id=' . $line['advertisment_id'] . '&amp;domain=' . $line_domain["domainname"] . '&amp;domain_id=' . $domain_id . '&amp;click_from=s';
                                } else {
                                    $click_count_paths [$click_link_id] = 'click_count.php?link=' . $line["website"] . '&amp;type=www&amp;id=' . $line['advertisment_id'] . '&amp;domain=' . $line_domain["domainname"] . '&amp;domain_id=' . $domain_id . '&amp;click_from=s';
                                }
                            } else {
                                $click_count_paths [$click_link_id] = 'click_count.php?link=' . $line["website"] . '&amp;type=www&amp;id=' . $line['advertisment_id'] . '&amp;domain=' . $line_domain["domainname"] . '&amp;domain_id=' . $domain_id . '&amp;click_from=s';
                            }
                        } else {
                            $click_count_paths [$click_link_id] = 'click_count.php?link=' . $line["website"] . '&amp;type=www&amp;id=' . $line['advertisment_id'] . '&amp;domain=' . $line_domain["domainname"] . '&amp;domain_id=' . $domain_id . '&amp;click_from=s';
                        }


                        $rec_locations = array();
                        $location = array();
                        $phones_array = array();
                        $wb_locations_tmp = $filter_locations;
                        $q = "select * from advertisment_locations where advertisment_id='{$advertisment_id[$i]}' and active='1' order by main_location desc;";
                        $qq [] = $q;
                        $r = @mysql_query($q);
                        if($r && mysql_num_rows($r)>0) {
                            while($row = mysql_fetch_assoc($r)) {

                                if(trim($row['tel1']) != "") {
                                    $phones_array [] = trim($row['tel1']);
                                }

                                if(in_array($row['district'], $wb_locations_tmp)) {
                                    $rec_locations [] = $row;

                                    if(isset($_REQUEST['debugx'])) {
                                        echo '<br/>' . $row['district'] . ' is in ' . var_export($wb_locations, true);
                                    }

                                }
                                else {
                                    if(isset($_REQUEST['debugx'])) {
                                        echo '<br/>' . $row['district'] . ' not in ' . var_export($wb_locations, true);
                                    }
                                }
                                if($row['main_location'] == 1 && count($location) == 0) $location = $row;
                            }
                        }

                        if(count($rec_locations) > 0) {
                            if(count($rec_locations) > 1 && count($location) == 0) $location = $rec_locations[0];
                            if(count($rec_locations) == 1) $location = $rec_locations[0];
                            if(count($town_locations[$i]) > 0){
                                //Decided not to use - htaccess issues
                                //$use_town_dir = true;
                            }
                        }

                        $location = array_map('stripslashes', $location);

                        $schema_address = [
                            "telephone" => null,
                            "streetAddress" => null,
                            "addressLocality" => null,
                            "addressRegion" => null,
                            "postalCode" => null,

                        ];
                        $show_schema = true;
                        $oh_status = null;
                        $show_opening_hours = false;

                        if(count($location) > 0) {
                            if (isset($location['tel1'])) {
                                $schema_address ['telephone'] = '+357' . substr(preg_replace("/[^0-9]/", "", trim($location['tel1'])), -8);
                            }
                            if (isset($location['street'])) {
                                $schema_address ['streetAddress'] = (trim($location['street_no']) != "" ? $location['street_no'] . ' ' : '') . $location['street'];
                            }
                            if (empty($schema_address ['streetAddress'])) {
                                $schema_address ['streetAddress'] = "N/A";
                            }
                            if (trim($location['city']) != "") {
                                $schema_address['addressLocality'] = $location['city'];
                            }
                            if (trim($location['district']) != "") {
                                $schema_address['addressRegion'] = $location['district'];
                            }
                            if (trim($location['postalcode']) != "") {
                                $schema_address['postalCode'] = $location['postalcode'];
                            } else {
                                $schema_address['postalCode'] = "N/A";
                            }


                            // Get Opening Hours
                            $oh_status = [
                                'today' => strtolower(date("l")),
                                'current_time' => intval(date("Hi")),
                                'is_open' => false,
                                'is_closed' => true,
                                'next_open' => null,
                                'next_close' => null
                            ];
                            $now_open = false;
                            $next_open = null;
                            $next_close = null;
                /* $cd_g = Global closing dates array for this week*/
                $cd_g = [];

                /* $cd_w = date intervals when it is closed */
                $cd_w = [];

                /* $oh_g = global opening hours struct */
                $oh_g = [];
                $cd = trim($location['closed_dates']);
                if($cd != "") {
                    $currentYear = date("Y");
                    $firstMonday = getStartOfWeekDate();
                    $firstMondayTimestamp = $firstMonday->getTimestamp();
                    $weekDates = [
                        'monday' => $firstMonday,
                        'tuesday' => (new DateTime())->setTimestamp($firstMondayTimestamp + 1 * (24 * 60 * 60)),
                        'wednesday' => (new DateTime())->setTimestamp($firstMondayTimestamp + 2 * (24 * 60 * 60)),
                        'thursday' => (new DateTime())->setTimestamp($firstMondayTimestamp + 3 * (24 * 60 * 60)),
                        'friday' => (new DateTime())->setTimestamp($firstMondayTimestamp + 4 * (24 * 60 * 60)),
                        'saturday' => (new DateTime())->setTimestamp($firstMondayTimestamp + 5 * (24 * 60 * 60)),
                        'sunday' => (new DateTime())->setTimestamp($firstMondayTimestamp + 6 * (24 * 60 * 60)),
                    ];
                    $cd = json_decode(stripslashes($cd), true);
                    foreach ($cd as $rx=>$range) {
                        if($range['repeat'] == 1) {
                            $r1 = new DateTime(substr_replace($range['from'], $currentYear, 0, 4));
                            $r2 = new DateTime(substr_replace($range['to'], $currentYear, 0, 4));
                        }
                        else {
                            $r1 = new DateTime($range['from']);
                            $r2 = new DateTime($range['to']);
                        }

                        foreach ($weekDates as $cday=>$cdate) {
                            if($r1 <= $cdate && $r2 >= $cdate) {
                                if(!isset($cd_g[$cday])) $cd_g[$cday] = [];
                                $cd_g[$cday][] = $range['comment'];
                                $cd_w [$rx] = ($r1 != $r2) ? $r1->format('d/m/Y') . ' - ' . $r2->format('d/m/Y') : $r1->format('d/m/Y');
                            }
                        }

                        /*$cd[$rx]['r1'] = $r1;
                        $cd[$rx]['r2'] = $r2;*/
                    }

                    //echo '<pre>$cd_g = ', var_export($cd_g, true), '</pre>';

                }
                $oh = trim($location['opening_hours']);
                if($oh != "") {
                    $today = strtolower(date("l"));
                    $current_time = intval(date("Hi"));
                    $oh = json_decode(stripslashes($oh), true);
                    //echo '<pre>$oh = ', var_export($oh, true), '</pre>';
                    foreach($oh as $d=>$dd) {
                        $t1 = trim(trim($dd[0]) . '-' . trim($dd[1]), '-');
                        $t2 = trim(trim($dd[2]) . '-' . trim($dd[3]), '-');
                        $alld = (isset($dd[4]) && intval($dd[4]) == 1) ? 1 : 0;


                        if($alld == 0 && $t1 != "") {

                            if($oh_status['today'] === $d) {
                                $t1_times = explode("-", $t1);
                                $t1_h1 = intval(str_replace(":", "", $t1_times[0]));
                                $t1_h2 = intval(str_replace(":", "", $t1_times[1]));
                                if ($current_time >= $t1_h1 && $current_time < $t1_h2) {
                                    $now_open = true;
                                    $oh_status['is_open'] = true;
                                    $oh_status['is_closed'] = false;
                                    $oh_status['next_open'] = null;
                                    $oh_status['next_close'] = trim($dd[1]);
                                }
                            }

                            $t = $t1;
                            if($t2 != "") {

                                if($oh_status['today'] === $d) {
                                    $t2_times = explode("-", $t2);
                                    $t2_h1 = intval(str_replace(":", "", $t2_times[0]));
                                    $t2_h2 = intval(str_replace(":", "", $t2_times[1]));
                                    if ($current_time >= $t2_h1 && $current_time < $t2_h2) {
                                        $now_open = true;
                                        $oh_status['is_open'] = true;
                                        $oh_status['is_closed'] = false;
                                        $oh_status['next_open'] = null;
                                        $oh_status['next_close'] = trim($dd[3]);
                                    }
                                }


                                $t .= ";$t2";
                            }
                            if(!isset($oh_g[$t])) $oh_g[$t] = [];
                            $oh_g[$t][] = $d;
                        }
                        elseif($alld == 0 && $t2 != "") {

                            if($oh_status['today'] === $d) {
                                $t2_times = explode("-", $t2);
                                $t2_h1 = intval(str_replace(":", "", $t2_times[0]));
                                $t2_h2 = intval(str_replace(":", "", $t2_times[1]));
                                if ($current_time >= $t2_h1 && $current_time < $t2_h2) {
                                    $now_open = true;
                                    $oh_status['is_open'] = true;
                                    $oh_status['is_closed'] = false;
                                    $oh_status['next_open'] = null;
                                    $oh_status['next_close'] = trim($dd[3]);
                                }
                            }

                            $t = $t2;
                            if(!isset($oh_g[$t])) $oh_g[$t] = [];
                            $oh_g[$t][] = $d;
                        }
                        elseif($alld == 0) {
                            /* Today is closed */
                            if($oh_status['today'] === $d) {
                                $now_open = false;
                                $oh_status['is_open'] = false;
                                $oh_status['is_closed'] = true;
                                $oh_status['next_open'] = null;
                                $oh_status['next_close'] = null;
                            }

                            if(!isset($oh_g['closed'])) $oh_g['closed'] = [];
                            $oh_g['closed'][] = $d;
                        }
                        else {
                            /* Today is open 24h */
                            if($oh_status['today'] === $d) {
                                $now_open = true;
                                $oh_status['is_open'] = true;
                                $oh_status['is_closed'] = false;
                                $oh_status['next_open'] = null;
                                $oh_status['next_close'] = null;
                            }

                            if(!isset($oh_g['allday'])) $oh_g['allday'] = [];
                            $oh_g['allday'][] = $d;
                        }

                                }
                                $show_opening_hours = true;
                                //echo '<pre>', var_export($oh_g, true), '</pre>';
                                // echo '<pre>', var_export($oh_status, true), '</pre>';
                            }




                        }
                        else {
                            $show_schema = false;
                        }


                        // Get the image code
                        //$img_placeholder = $path . "images/advertisments/blurred-640x480.jpg";
                        $img_placeholder = $path . "images/advertisments/placeholder.png";
                        $img_container_attr = array('tag' => 'div');
                        ob_start();
                        $nofollow_value = is_nofollow($nofollow_domains) ? 'nofollow' : '';
                        $img_container_attr ['tag'] = 'a';
                        $img_container_attr ['class'] = 'flimg';
                        $img_container_attr ['target'] = '_blank';
                        $img_container_attr ['rel'] = "noopener $nofollow_value";
                        $img_container_attr ['href'] = $protocol . $microdata_host . '/' . $shortNameURL;;
                        $img_container_attr ['title'] = $line['short_title_en'];


                        $screenshot_url_direct = "https://www.cypruspics.com/images/" . md5($line['website']) . "/"

                        ?>
                        <img
                            src="<?=$img_placeholder?>"
                            data-src="<?= $screenshot_url_direct; ?>160x120.jpg"
                            data-srcset="<?= $screenshot_url_direct; ?>160x120.jpg 160w, <?= $screenshot_url_direct; ?>640x480.jpg 640w"
                            sizes="(max-width: 767px) 640px,160px"
                            alt="<?php echo $line['short_title_en']; ?>"
                            title="<?php echo $line['short_title_en']; ?>"
                            class="img-responsive"/>
                        <?php

                        $img_tag = ob_get_clean();
                        /************************************************************/

                        // check schema definitions
                        $schema_types = [];
                        $mdata = trim($line['schema_types']);
                        if ($mdata != "") {
                            $schema_types = json_decode($mdata, true);
                        }

                        $schema_type = "LocalBusiness";
                        $schema_name = "Local Business";
                        foreach ($schema_types as $schema) {
                            if (is_array($schema['domains']) && in_array($ultra_domainname, $schema['domains'])) {
                                $schema_type = $schema['type'];
                                $schema_name = $schema['name'];
                            }
                        }


                        $wb_json = [
                            /*"@context" => "http://schema.org",*/
                            "@type" => $schema_type,
                            "@id" => $protocol . $microdata_host . '/' . $shortNameURL."#$shortNameURL",
                            "url" => $canonical_link . "#$shortNameURL",
                            "sameAs" => $protocol . $microdata_host . '/' . $shortNameURL,
                            "name" => trim(stripslashes($line["short_title_en"])),
                            "priceRange" => "€€",
                            "telephone" => $schema_address['telephone'],
                            "image" => $screenshot_url . "w=640&h=480&url=" . urlencode($website),
                            "address" => [
                                "@type" => "PostalAddress",
                                "streetAddress" => $schema_address['streetAddress'],
                                "addressLocality" => $schema_address['addressLocality'],
                                "addressRegion" => $schema_address['addressRegion'],
                                "postalCode" => $schema_address['postalCode'],
                                "addressCountry" => "Cyprus",
                            ]
                        ];

                        if(isset($location['opening_hours'])) {
                            $oh = trim($location['opening_hours']);
                            if($oh != "") {
                                $oh = json_decode(stripslashes($oh), true);
                            }
                        }

                        ?>
                        <div class="wb-flex" id="<?=$shortNameURL;?>">

                            <div class="wb-card-image">
                                <?php
                                $current_tag = $img_container_attr;
                                $tag = $current_tag['tag'];
                                unset($current_tag['tag']);
                                $tag_attr = array();
                                foreach ($current_tag as $tt => $tv) {
                                    $tag_attr [] = $tt . '="' . $tv . '"';
                                }
                                $tag_code = '<' . $tag . ' ' . implode(" ", $tag_attr) . '>' . $img_tag . '</' . $tag . '>';
                                echo $tag_code;
                                ?>

                            </div>

                            <div class="wb-card-content">
                                <?php
                                ob_start();
                                ?>
                                <div class="wb-card-details">
                            <?php
                            if(isset($_SESSION['user_id'])) {
                                ?>
                                <a class="user-action-inline label label-info"
                                   href="../admin/advert_manager.php?advert_action=advert_edit_main&amp;advertisment_id=<?= $line['advertisment_id']; ?>"
                                   target="_blank">e</a>
                                <?php
                            }
                            ?>

                                    <div class="wb-card-data">
                                        <i class="fa fa-building-o fa-fw pull-left"></i>
                                        <span class="wb-type"><?=$schema_name;?></span>
                                    </div>
                                    <div class="wb-card-data">
                                        <i class="fa fa-map-marker fa-fw pull-left"></i>
                                        <address class="wb-address">
                                            <?php
                                            echo $schema_address['streetAddress']
                                                . ', ' . $schema_address['addressLocality']
                                                . ', ' . $schema_address['addressRegion']
                                                . ' ' . $schema_address['postalCode']
                                                . ', Cyprus';
                                            ?>
                                        </address>
                                    </div>
                                    <?php
                                    if($oh_status != null && $show_opening_hours) {
                                        //echo '<pre>$oh_g = ', var_export($oh_g, true), '</pre>';
                                        $oh_json = [];
                                        ?>
                                        <div class="wb-card-data">
                                            <i class="fa fa-clock-o fa-fw pull-left"></i>
                                            <span class="wb-oh sr-only"></span>
                                            <?php
                                            $current_status_class = '';
                                            $current_status_text = '';
                                            if(isset($cd_g[strtolower(date("l"))])) {
                                                $current_status_class = 'closed';
                                                $current_status_text = 'CLOSED';
                                            }
                                            ?>
                                            <span id="for-<?=$location['location_id'];?>" class="open-status for-<?=$location['location_id'];?> <?=$current_status_class;?>"><?=$current_status_text;?></span>
                                            <div class="dropdown opening-hours" data-location="<?=$location['location_id'];?>" aria-label="Opening hours">
                                                <button class="btn btn-default btn-xs dropdown-toggle" type="button" id="oh-<?=$location['location_id'];?>" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                                    <div class="oh-status" id="oh-status-<?=$location['location_id'];?>" aria-label="Today opening hours"></div>
                                                    <span class="caret"></span>
                                                </button>
                                                <ul class="dropdown-menu" aria-labelledby="oh-<?=$location['location_id'];?>">
                                                    <?php
                                                    $d_ar = ['monday' => '', 'tuesday' => '', 'wednesday' => '', 'thursday' => '', 'friday' => '', 'saturday' => '', 'sunday' => ''];
                                                    $d_week = ['monday' => '1', 'tuesday' => '2', 'wednesday' => '3', 'thursday' => '4', 'friday' => '5', 'saturday' => '6', 'sunday' => '0'];
                                                    $d_list = [];
                                                    foreach($oh_g as $t=>$t_days) {

                                    if($t !== "closed" && $t !== "allday") {
                                        $se_sets = [];
                                        $start_end = [];
                                        $sets = explode(";", $t);
                                        if(is_array($sets)) {

                                                                foreach($sets as $se) {
                                                                    $se_h = explode("-", $se);

                                                                    $se_h_start = explode(":", $se_h[0]);
                                                                    $se_h_end = explode(":", $se_h[1]);

                                                                    if(intval($se_h_start[0]) < intval($se_h_end[0])) {
                                                                        $r_st = intval($se_h_start[0]) * 60 * 60 + intval($se_h_start[1]) * 60;
                                                                        $r_nd = intval($se_h_end[0]) * 60 * 60 + intval($se_h_end[1]) * 60;
                                                                        $start_end [] = ["str" => $se, "start" => $r_st, "end" => $r_nd];
                                                                    }
                                                                    else {
                                                                        $r_st = intval($se_h_start[0]) * 60 * 60 + intval($se_h_start[1]) * 60;
                                                                        $r_nd = intval($se_h_end[0]) * 60 * 60 + intval($se_h_end[1]) * 60 + 24  * 60 * 60;
                                                                        $start_end [] = ["str" => $se, "start" => $r_st, "end" => $r_nd];
                                                                    }

                                                                    $oh_json_part = [];
                                                                    $oh_json_part ['dayOfWeek'] = array_map('ucfirst', $t_days);
                                                                    $oh_json_part ['opens'] = $se_h[0];
                                                                    $oh_json_part ['closes'] = $se_h[1];
                                                                    $oh_json [] = $oh_json_part;
                                                                }
                                                            }
                                                            else {
                                                                $oh_json_part = [];
                                                                $se_h = explode("-", $t);
                                                                $oh_json_part ['dayOfWeek'] = array_map('ucfirst', $t_days);
                                                                $oh_json_part ['opens'] = $se_h[0];
                                                                $oh_json_part ['closes'] = $se_h[1];
                                                                $oh_json [] = $oh_json_part;
                                                            }

                                        $se_sets [] = $start_end;
                                        $t_str = str_replace(';', ' and ', $t);
                                        foreach ($t_days as $t_day) {
                                            $d_ar[$t_day] = $t_str;
                                            $d_list[$t_day] = $start_end;
                                        }
                                    }
                                    elseif($t === "closed") {

                                        $oh_json_part = [];
                                        $oh_json_part ['dayOfWeek'] = array_map('ucfirst', $t_days);
                                        $oh_json_part ['opens'] = '00:00';
                                        $oh_json_part ['closes'] = '00:00';
                                        $oh_json [] = $oh_json_part;

                                        foreach ($t_days as $t_day) {
                                            $d_ar[$t_day] = 'Closed';
                                        }
                                    }
                                    elseif($t === "allday") {
                                        $oh_json_part = [];
                                        $oh_json_part ['dayOfWeek'] = array_map('ucfirst', $t_days);
                                        $oh_json_part ['opens'] = '00:00:00';
                                        $oh_json_part ['closes'] = '23:59:59';
                                        $oh_json [] = $oh_json_part;

                                        foreach ($t_days as $t_day) {
                                            $d_ar[$t_day] = 'Open (24h)';
                                            $d_list [$t_day][] = [
                                                'str' => 'Open All Day (24h)',
                                                'start' => 0,
                                                'end' => 86400
                                            ];
                                        }
                                    }
                                }
                                                    foreach($d_ar as $day=>$hours) {
                                                        ?>
                                                        <li class="weekday" data-weekday="<?=$d_week[$day];?>">
                                                            <span class="oh-day"><?=substr(ucfirst($day), 0, 3);?>:</span>
                                                            <?php
                                                    if(isset($d_list[$day]) && !isset($cd_g[$day])) {
                                                        foreach ($d_list[$day] as $ind=>$t_interval) {
                                                                    ?>
                                                                    <span class="oh-hours" data-start="<?= $t_interval['start']; ?>"
                                                                          data-end="<?= $t_interval['end']; ?>"><?= $t_interval['str']; ?></span>
                                                                    <?php
                                                                }
                                                            }
                                                            else {
                                                                ?>
                                                                <span class="data-text" aria-label="Closed">-</span>
                                                                <?php
                                                            }
                                                            ?>

                                                </li>
                                                <?php
                                            }

                                            if(count($cd_w) > 0) {
                                                $closed_intervals = '<small>Closed on the following dates:</small><br>' . implode(", ", $cd_w);
                                                ?>
                                                <li class="notice"><?=$closed_intervals;?></li>
                                                <?
                                            }
                                            ?>
                                        </ul>
                                        <?php
                                        //echo '<pre>$oh_json = ', var_export($oh_json, true), '</pre>';

                                        $wb_json ['openingHoursSpecification'] = [];
                                        foreach($oh_json as $oh_spec) {
                                            $wb_json ['openingHoursSpecification'][] = [
                                                "@type" => "openingHoursSpecification",
                                                "dayOfWeek" => count($oh_spec['dayOfWeek']) > 1 ? $oh_spec['dayOfWeek'] : $oh_spec['dayOfWeek'][0],
                                                "opens" => $oh_spec['opens'],
                                                "closes" => $oh_spec['closes'],
                                            ];
                                        }

                                                ?>
                                            </div>
                                        </div>
                                        <?php
                                    }

                                    if($show_schema) {
                                        $jsonld['filter_adverts_list'][] = $wb_json;
                                    }
                                    ?>


                                </div>
                                <?php
                                $wb_card_details = ob_get_clean();
                                ?>
                                <div class="wb-title">
                                    <a href="<?php echo $protocol . $microdata_host . '/' . $shortNameURL; ?>" title="<?php echo stripslashes($line["short_title_en"]); ?>"
                                       class="wb-local-business" target="_blank" rel="noopener"><?php echo stripslashes($line["short_title_en"]); ?></a>
                                </div>
                                <?php
                                echo $wb_card_details;
                                ?>
                                <div class="wb-telephone">
                                    <a href="#" data-href="tel:<?=$schema_address['telephone'];?>" title="<?=$schema_address['telephone'];?>" class="btn btn-call">
                                        <i class="fa fa-phone fa-lg"></i> <?php echo '(+357) ' . substr(str_replace("+357", "", $schema_address['telephone']), 0, 2) . " " . substr(str_replace("+357", "", $schema_address['telephone']), 2, 6);?>
                                    </a>
                                </div>
                            </div>
                        </div>
                        <?php
                    }
                }

                if ($filter_pagination == 1 && $num_pages > 1) {
                    ?>
                    <div class="search-results-pagination text-left">
                        <div class="search-results-num">
                            <?php
                            if ($num_results > $start + $range) {
                                $end = $start + $range;
                            } else {
                                $end = $num_results;
                            }
                            echo "Results <b>", ($start + 1), " - ", $end, "</b> out of <b>", $num_results, "</b>";
                            ?>
                        </div>
                        <nav>
                            <ul class="pagination">
                                <?php
                                $pagesrange = 2;
                                $pages = (($num_results / $range) - intval($num_results / $range) == 0) ? intval($num_results / $range) : (intval($num_results / $range) + 1);
                                $startmsg = '';
                                if (($start / $range) <= $pagesrange) {
                                    $startrange = 0;
                                } else {
                                    $startrange = $start / $range - $pagesrange;
                                    $prev = $current_page - 1;
                                    $startmsg = '<li><a href="' . $filter_friendly_url . '?p=' . $prev . '" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>';
                                    $startmsg .= '<li><a href="' . $filter_friendly_url . '?p=1">1</a></li>';
                                    $startmsg .= '<li><a href="#">...</a></li>';
                                    //$startmsg = "<a href='{$_SERVER['PHP_SELF']}?start=$prev&search=$search&amp;catdom_ids=$catdom_ids&filter_ids=$filter_ids&seri=111&module_page=search_adv' class=\"small10\">Previous</a>  <a href='{$_SERVER['PHP_SELF']}?start=&search=$search&amp;catdom_ids=$catdom_ids&filter_ids=$filter_ids&seri=111&module_page=search_adv' class=\"small10\">1</a> . . .  ";
                                }

                                if (($startrange + (2 * $pagesrange) + 1) >= $pages) {
                                    $endrange = $pages;
                                    //$endmsg = '<li><a href="#" aria-label="Next" class="disabled"><span aria-hidden="true">&raquo;</span></a></li>';
                                    $endmsg = '';
                                } else {
                                    $endrange = $startrange + (2 * $pagesrange) + 1;
                                    //$nex=$start+$range;
                                    $nex = $current_page + 1;
                                    $endpage = ceil($pages);
                                    $end = floor($pages) * $range;
                                    $endmsg = '<li><a href="#">...</a></li>';
                                    $endmsg .= '<li><a href="' . $filter_friendly_url . '?p=' . ($endpage) . '">' . $endpage . '</a></li>';
                                    $endmsg .= '<li><a href="' . $filter_friendly_url . '?p=' . ($nex) . '" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>';
                                    //$endmsg="  . . .  <a href='{$_SERVER['PHP_SELF']}?start=$end&search=$search&amp;catdom_ids=$catdom_ids&filter_ids=$filter_ids&seri=111&module_page=search_adv' class=\"small10\">$endpage</a> <a href='{$_SERVER['PHP_SELF']}?start=$nex&search=$search&amp;catdom_ids=$catdom_ids&filter_ids=$filter_ids&seri=111&module_page=search_adv' class=\"small10\">Next</a>";
                                }

                                echo $startmsg;

                                for ($noofpage = $startrange; $noofpage < $endrange; $noofpage++) {
                                    if ($start != $noofpage * $range) {
                                        $active_link = '';
                                        if ($noofpage + 1 == $current_page) $active_link = 'active';
                                        ?>
                                        <li>
                                            <a href="<?php echo $filter_friendly_url . '?p=' . ($noofpage + 1) . ''; ?>"
                                               class=""><?php echo($noofpage + 1); ?></a></li>
                                        <?php
                                    } else {
                                        echo '<li class="active"><a href="#">' . ($noofpage + 1) . '</a></li>';
                                    }
                                }
                                echo $endmsg;
                                ?>
                            </ul>
                        </nav>
                    </div>
                    <?php
                }

                if(isset($_REQUEST['debug_schema'])) {
                    echo '<pre>', var_export($jsonld['filter_adverts_list'], true), '</pre>';
                }
                ?>

            </div>
            <?php
        }
    }

}



$filter_content = ob_get_contents();
ob_end_clean();

if(isset($_REQUEST['debug_schema'])) {
    echo '<pre>', var_export($jsonld, true), '</pre>';
}

if($filter_content_show == 1) {
	echo $filter_content;
}
if( (isset($send404) && $send404 === true) ) {
    ob_clean();
    $send404 = true;
    require_once(dirname(__FILE__) . "/../404/404.php");
}