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


/* furniture - noindex/follow*/
if((in_array(str_replace('www.', '', $ultra_domainname), $special_domains))) {
    $meta_robots = "noindex, follow";
}

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

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;
    }
}


//echo '<pre>', var_export($_POST, true), '</pre>';
$catdom_id = $domain_id;
$microdata_domain = str_replace("www.", "", $ultra_domainname);
$microdata_host = $_SERVER['HTTP_HOST'];
if(str_replace('www.', '', $microdata_host) != str_replace('www.', '', $ultra_domainname)) $microdata_host .= "/" . $ultra_addonname;
$have_microdata = (isset($microdata_domains) && in_array($microdata_domain, $microdata_domains));

$canonical_base = $protocol . $microdata_host . "/cyprus";
$canonical_link = $protocol . $microdata_host . "/cyprus";

$range = 10;
$start = isset($search['start']) ? intval($search['start']) : 0;
$current_page = 1;
if ($start > 0) $start = 0;

$all_advs = $pfcache->get('all_bound_advers_ordered');
//$all_advs = null;
if($all_advs == null) {

    $all_advs = array();
    $all_catdoms = array($domain_id);
    $q = "SELECT * FROM advertisment WHERE active='yes' ";
    if($domain_id != 611) {
        $domain_idx2 = sprintf("%04.0f", $domain_id);
        $q .= " AND ( catdom_id LIKE '%$domain_idx2%'";
        $result_sub = mysql_query("SELECT * FROM  domaincategories WHERE parent_id='$domain_id'");
        if ($result_sub && mysql_num_rows($result_sub) > 0) {
            while ($line_sub = mysql_fetch_array($result_sub)) {
                $all_catdoms[] = $line_sub['catdom_id'];
                $domain_idx2 = sprintf("%04.0f", $line_sub["catdom_id"]);
                $q .= " OR catdom_id LIKE '%$domain_idx2%'";
            }
        }
        $q .= ")";
    }
    else {
        $q .= " ORDER BY short_title_en ASC";
    }
    //echo '<br>'. $q;
    $r = @mysql_query($q);
    if ($r && mysql_num_rows($r) > 0) {
        while ($row = mysql_fetch_assoc($r)) {
            $row['order'] = 0;
            $row['categ_order'] = 0;
            $row['paying'] = 0;
            $row['main_location'] = array();
            $all_advs[$row['advertisment_id']] = $row;
        }
        $all_catdoms_ids = implode(", ", $all_catdoms);
        $all_advs_ids = implode(", ", array_keys($all_advs));

        // Get Main Location
        $ql = "SELECT * FROM advertisment_locations WHERE advertisment_id IN ($all_advs_ids) AND main_location='1';";
        $rl = @mysql_query($ql);
        if($rl && mysql_num_rows($rl) > 0) {
            while($row = mysql_fetch_assoc($rl)) {
               $all_advs[$row['advertisment_id']]['main_location'] = $row;
            }
        }


        // Get Domain & Category level bindings
        if($domain_id != 611) {
            $qda = "SELECT * FROM domain_advertisment WHERE catdom_id IN ($all_catdoms_ids) AND advertisment_id IN ($all_advs_ids);";
        }
        else {
            $qda = "SELECT d.* FROM domain_advertisment d, advertisment a WHERE d.advertisment_id=a.advertisment_id AND a.active='yes' ORDER BY a.short_title_en ASC";
        }
        //echo '<br>'. $qda;
        $rda = @mysql_query($qda);
        if ($rda && mysql_num_rows($rda) > 0) {
            while ($row = mysql_fetch_assoc($rda)) {
                $bound_advertisment_id = intval($row['advertisment_id']);
                $bound_catdom_id = intval($row['catdom_id']);

                $category_top = $row['category_top'];
                $category_top_order_seq = intval($row['category_top_order_seq']);

                $active = $row['active'];
                $order_seq = intval($row['order_seq']);

                if ($bound_catdom_id == $domain_id && $domain_id != 611) {
                    // We are on homepage
                    $order = 0;
                    $categ_order = 0;
                    $paying = 0;
                    if ($category_top == "yes") {
                        $order = 10;
                        $categ_order = $category_top_order_seq;
                        $paying = 1;
                    } elseif ($active == "yes") {
                        $order = 8;
                        $categ_order = $order_seq;
                        $paying = 1;
                    }
                    if ($all_advs[$bound_advertisment_id]['order'] < $order) {
                        $all_advs[$bound_advertisment_id]['order'] = $order;
                        $all_advs[$bound_advertisment_id]['categ_order'] = $categ_order;
                    }

                    if($paying > 0) $all_advs[$bound_advertisment_id]['paying'] = $paying;

                } else {
                    // We are in a town/category page
                    $order = 0;
                    $categ_order = 0;
                    $paying = 0;
                    if ($category_top == "yes") {
                        $order = 6;
                        $categ_order = $category_top_order_seq;
                        $paying = 1;
                    } elseif ($active == "yes") {
                        $order = 4;
                        $categ_order = $order_seq;
                        $paying = 1;
                    }
                    if ($all_advs[$bound_advertisment_id]['order'] < $order) {
                        $all_advs[$bound_advertisment_id]['order'] = $order;
                        $all_advs[$bound_advertisment_id]['categ_order'] = $categ_order;
                    }

                    if($paying > 0) $all_advs[$bound_advertisment_id]['paying'] = $paying;
                }

            }
        }


        if($domain_id != 611) {
            uasort($all_advs, function ($a, $b) {
                if ($a['order'] == $b['order']) {
                    if ($a['categ_order'] < $b['categ_order']) return 1;
                    if ($a['categ_order'] == $b['categ_order']) return 0;
                    if ($a['categ_order'] > $b['categ_order']) return -1;
                }
                return $a['order'] - $b['order'];
            });

            $all_advs = array_reverse($all_advs, true);
        }

    }

    $pfcache->set('all_bound_advers_ordered', $all_advs, $pfcache_ttl);
}




if(isset($search['now']) && $search['now']=="yes"){

	// Get the searched catdom
	$catdom_id_adv = $domain_id;
	if(isset($search['catdom_id']) && intval($search['catdom_id']) > 0) {
		$catdom_id_adv = intval($search['catdom_id']);
	}

	if (isset($start) && strlen($start) < 1 ){
		$start = 0;
	}

	$catdom_idx = sprintf("%04.0f", $catdom_id);

    if(isset($filter) && $filter != null) {
        $query = "SELECT a.* 
                  FROM 
                    advertisment a
                    LEFT JOIN advertisment_versions v
                    ON (a.advertisment_id=v.advertisment_id AND v.domainname='$ultra_domainname')
                  WHERE 
                    a.active='yes' ";
        $search_keyword = '';
        if (isset($search['keyword'])) $search_keyword = mysql_real_escape_string(stripslashes(trim($search['keyword'])));
        if ($search_keyword != "") {
            $query .= " AND (
            a.short_title_en LIKE '%{$search_keyword}%' 
            OR a.website like '%{$search_keyword}%'
            OR a.MemberOf like '%{$search_keyword}%'
            OR a.Directors like '%{$search_keyword}%'
            OR a.title_el LIKE '%{$search_keyword}%' 
            OR a.title_tr LIKE '%{$search_keyword}%'
            OR ( CASE WHEN v.description_en IS NOT NULL THEN v.description_en like '%{$search_keyword}%' ELSE a.description_en like '%{$search_keyword}%' END ) 
            OR a.advertisment_id IN (SELECT l.advertisment_id FROM advertisment_locations l WHERE l.advertisment_id=a.advertisment_id AND l.active='1' AND (
                l.street like '%{$search_keyword}%'
                    OR l.postalcode like '%{$search_keyword}%'
                    OR l.city like '%{$search_keyword}%'
                    OR l.district like '%{$search_keyword}%'
                    OR l.contact_name like '%{$search_keyword}%'
                    OR l.tel1 like '%{$search_keyword}%'
                    OR l.tel2 like '%{$search_keyword}%'
                    OR l.mobile1 like '%{$search_keyword}%'
                    OR l.mobile2 like '%{$search_keyword}%'
                    OR l.fax like '%{$search_keyword}%'
                    OR l.email like '%{$search_keyword}%'
                )
                )   
            ) ";
        }
        if ($domain_id != 611) {
            if ($domain_id <> "" && $domain_id > 0) {
                // echo $domain_id;
                $query .= " AND";
                if (isset($search["catdom_id"]) && $search["catdom_id"] <> "") {
                    $catdom_idx2 = sprintf("%04.0f", $search["catdom_id"]);
                    $query .= " a.catdom_id LIKE '%$catdom_idx2%'";
                } elseif (isset($catdom_ids) && is_array($catdom_ids) && count($catdom_ids) > 0) {
                    $query .= " (";
                    while (list($key, $val) = each($catdom_ids)) {
                        if ($val > 0) {
                            $countval++;
                            if ($countval > 1 && isset($search['andor'])) {
                                $query .= " {$search['andor']} ";
                            }
                            $catdom_idx = sprintf("%04.0f", $val);
                            $query .= " a.catdom_id LIKE '%$catdom_idx%' ";
                        }
                    }
                    $query .= ") ";
                } else {
                    $domain_idx2 = sprintf("%04.0f", $domain_id);
                    $query .= " (a.catdom_id LIKE '%$domain_idx2%'";
                    $result_sub = mysql_query("SELECT * FROM  domaincategories WHERE parent_id='$domain_id'");
                    if (mysql_num_rows($result_sub) <> 0) {
                        while ($line_sub = mysql_fetch_array($result_sub)) {
                            $domain_idx2 = sprintf("%04.0f", $line_sub["catdom_id"]);
                            $query .= " OR a.catdom_id LIKE '%$domain_idx2%'";
                        }
                    }
                    $query .= ")";
                }
            }
        }
        if (isset($search['filter_ids']) && is_array($search['filter_ids']) && count($search['filter_ids']) > 0) {
            $where_filters = array();
            while (list($key, $val) = each($search['filter_ids'])) {
                if ($val > 0) {
                    $filter_idx = sprintf("%04.0f", $val);
                    $where_filters [] = "filter_id LIKE '%$filter_idx%'";
                }
            }
            if (count($where_filters) > 0) {
                $where_filters_str = implode(" AND ", $where_filters);
                $query .= " AND ($where_filters_str)";
            }
        }
        //			  if($catdom_idS<>"" && $catdom_idS=="0"){$query .=" AND (catdom_id='' OR catdom_id=0)";}
        if (isset($date_before) && $date_before <> "") {
            $query .= " AND a.added_on >= '$date_before'";
        }
        if (isset($date_after) && $date_after <> "") {
            $query .= " AND a.added_on <= '$date_after'";
        }

        $query .= " ORDER BY a.short_title_en ASC";

        //echo $query;
        $result = @mysql_query($query);
        $adverts = array();

        if ($result && mysql_num_rows($result) > 0) {
            $NumberOfFields = mysql_num_rows($result);
            while ($row = mysql_fetch_assoc($result)) {
                $adverts[] = $row['advertisment_id'];
            }
        }

        $results = array();
        $cnt = 0;
        foreach($all_advs as $adv_id=>$adv) {
            if(in_array($adv_id, $adverts)) {
                $results [$cnt] = $adv;
                $cnt++;
            }

        }


    }
    else {
        $results = array();
        $cnt = 0;
        foreach($all_advs as $adv_id=>$adv) {
            $results [$cnt] = $adv;
            $cnt++;
        }
    }

	?>
    <section class="search-results">
        <header>
            <?php
            $search_title = 'Advanced Search - ' . stripslashes(trim($line_catdom_id["title_en"]));
            $webpage_title_en = $search_title;
            $meta['description'] = '';


            ?>

            <h1><?php echo $search_title;?></h1>
            <!--[/SocialShareButtons/]-->
        </header>
        <div class="content-body">
            <?php
            require_once(dirname(__FILE__) . "/../advanced_search/advanced_search.php");


            if (isset($results) && count($results) > 0){
                $NumberOfFields = count($results);
                ?>

                <div>
                    <?php
                    $NumberOfFields = count($results);


                    $meta_keywords = array();
                    $meta_strip_array = array(
                        "cyprus", "limassol", "paphos", "larnaca", "famagusta", "ayia napa"
                    );
                    //$meta_keywords [] = trim(str_ireplace($meta_strip_array, '', stripslashes(trim($line_catdom_id["title_en"]))));
                    //$_REQUEST['debugx'] = 1;

                    $click_count_paths = array();

                    foreach($results as $i => $line) {
                        $website = fix_url(trim($line['website']));
                        $nofollow_domains = $line['nofollow_domains'];

                        $paying_advert = $line['paying'] == 1;
                        $use_town_dir = false;

                        $show_website = intval($line['show_website']);
                        $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));

                        $meta_keywords [] = $line["short_title_en"];

                        if((in_array(str_replace('www.', '', $ultra_domainname), $special_domains))) {
                            $meta['description'] = '';
                        }
                        else {
                            if ($i == $start) {
                                $meta['description'] .= $line["short_title_en"];
                            } else {
                                $meta['description'] .= ', ' . $line["short_title_en"];
                            }
                        }
                        $rec_locations = array();
                        $location = array();
                        $phones_array = array();
                        $q = "select * from advertisment_locations where advertisment_id='{$line['advertisment_id']}' 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']);
                                }
                                $rec_locations [] = $row;

                                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];

                        }



                        //print_r($app_conf);
                        $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=' .'' . '&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=' .'' . '&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=' .'' . '&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=' .'' . '&amp;type=www&amp;id=' . $line['advertisment_id'] . '&amp;domain=' . $line_domain["domainname"] .'&amp;domain_id=' . $domain_id. '&amp;click_from=s';
                        }

                        $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
                                /*if (!in_array($protocol . $microdata_host . "/$shortNameURL", $jsonld['links'])) {
                                    $jsonld['links'][] = $protocol . $microdata_host . "/$shortNameURL";
                                }*/
                                // Title



                                ob_start();
                                ?>
                                <div class="wb-card-details">


                                    <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 = [];
                                        $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 = [];

                                        //echo '<pre>' . var_export($oh_g, true) . '</pre>';
                                        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
                                                    ];
                                                }
                                            }
                                        }

                                        //echo '<pre>' . var_export($d_list, true) . '</pre>';
                                        ?>
                                        <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">
                                                    <span class="oh-status" id="oh-status-<?=$location['location_id'];?>" aria-label="Today opening hours"></span>
                                                    <span class="caret"></span>
                                                </button>
                                                <ul class="dropdown-menu" aria-labelledby="oh-<?=$location['location_id'];?>">
                                                    <?php

                                                    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['search_adv'][] = $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>
                                <?php

                                ?>
                            </div>
                            <?php
                            /*<div class="wb-index"><?=($i + 1);?></div>*/
                            ?>
                        </div>

                        <?php


                    }
                    ?>
                </div>


            <?php



            if (isset($meta_keywords) && count($meta_keywords) > 0) {
                $meta['keywords'] = implode(", ", $meta_keywords) . ", " . $meta['keywords'];
            }


            ?>

            <?php

        }
        else{
            ?>
            <div class="alert alert-danger">
                <p>There are no listings in database with these criteria.</p>
            </div>
            <?php
        }

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