<?php
//assets/themes/bootstrap4/amodules/adverts/adverts_f_noinfo.css
$module_css_path = ($line_domain['theme'] != "" && $line_domain['theme'] != "default") ? ($path . ('assets/themes/' . $line_domain['theme'] . '/')) : $path;
$optres['css'][] = $module_css_path  . 'amodules/adverts/css/adverts_f_noinfo.css';
$optres['css'][] = $module_css_path  . 'amodules/adverts/css/click_shout.css';


// Start/ Append a json-ld file
if(!isset($jsonld['links'])) {
    $jsonld['links'] = [];
}


$f_top_css = null;
$st = microtime(true);

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(!function_exists("getDataURI")) {
	function getDataURI($image,$mime='') {
        $type = pathinfo($image, PATHINFO_EXTENSION);
        $stream_opts = [
            "ssl" => [
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ]
        ];
        $data = file_get_contents($image, false, stream_context_create($stream_opts));
        $dataUri = 'data:image/' . $type . ';base64,' . base64_encode($data);
		return $dataUri;
	}
}

$remotehost = $_SERVER['REMOTE_ADDR'];
$date_now = date("Y-m-d", time());
$after1month  = date("Y-m-d",mktime(0, 0, 0, date("m")+1 ,date("d"), date("Y")));
$after3months  = date("Y-m-d",mktime(0, 0, 0, date("m")+3 ,date("d"), date("Y")));
$catdom_id_adv = 0;
if(isset($catdom_id) && intval($catdom_id)>0){
	$catdom_id_adv = $catdom_id;
}
else {
	$catdom_id_adv = $domain_id;
	$catdom_id = $domain_id;
}


$is_promo_cat = 0;
if(isset($_SESSION['user_id'])) {
// Find if current page is promo_cat
    if ($catdom_id_adv != $domain_id) {
        $qpp = "SELECT * FROM domaincategories WHERE catdom_id='$catdom_id_adv'";
        $rpp = @mysql_query($qpp);
        if ($rpp && mysql_num_rows($rpp) == 1) {
            $rowpp = mysql_fetch_assoc($rpp);
            $is_promo_cat = intval($rowpp['is_promo_cat']);


        }
    }
}

if(!isset($rel_nofollow)) {
    $rel_nofollow = 0;
}


// Get town friendly url
$town_friendly_url = "";
if($catdom_id_adv != $domain_id) {
	$q = "select * from domaincategories where catdom_id='$catdom_id_adv';";
	$r = @mysql_query($q);
	if($r && mysql_num_rows($r) > 0) {
		$row = mysql_fetch_assoc($r);
		$town_friendly_url = trim($row['friendly_url']) . "/";
	}
}

$domain_idx2 = sprintf("%04.0f", $catdom_id_adv);

$root_host = $_SERVER['HTTP_HOST'];
if(str_replace('www.', '', $root_host) != str_replace('www.', '', $ultra_domainname)) {
	$root_host .= "/$ultra_addonname";
}


include($general_path . "queries.php");


$short_invoice_types = array(
	"999999"		=> array("short_name"=>"Complim.", "color"=>"#F02FFF"),
	"888888"		=> array("short_name"=>"Filler", "color"=>"#09AF00"),
	"777777"		=> array("short_name"=>"Featured", "color"=>"#FFD100"),
	"555555"		=> array("short_name"=>"Friends", "color"=>"#39424B"),
	"444444"		=> array("short_name"=>"Link Exch.", "color"=>"#800000")
);

$bind_types =  array(
	//"invoice"		=> "Payable",
	"t_upgrade"			=> "Temp.Upgrade",
	"t_complimentary"	=> "Temp.Complim",
	"t_filler"			=> "Temp.Filler"
);

//$optres['css'][] = $path . "css/company_dialog/jquery-ui-1.8.23.custom.css";
//$optres['js'][] = $path . "js/jquery-ui-1.8.23.custom.min.js";

//$optres ['css'][] = $path . "client_stand.css";
//$optres ['css'][] = $path . "css/prettyPhoto.css";
//$optres ['js'][] = $path . "js/jquery.prettyPhoto.js";

$have_featured = "no";
$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;

$featured_key = 'featured_adverts_' . $catdom_id_adv;
$featured_actions = array();
$non_featured_key = 'non_featured_adverts_' . $catdom_id_adv;
$non_featured_actions = array();

echo '<div class="lbs">';
if(!isset($module_show_featured_section) || intval($module_show_featured_section) == 1) {

    /*$have_top_adverts_css = false;
    $all_cache_folder = dirname(__FILE__) . "/../../all_cache/" . $app_conf["addonname"];
    if(!is_dir($all_cache_folder . "/adverts/css")) {
        mkdir($all_cache_folder . "/adverts/css", 0755, true);
    }
    $css_filename = $all_cache_folder . "/adverts/css/top_adverts_" . $domain_id . "_" . $catdom_id_adv . ".min.css";
    if(file_exists($css_filename)) {
        $have_top_adverts_css = true;
        if(filemtime($css_filename) < time() - 3600*24) $have_top_adverts_css = false;
        //echo '<br/>' . $css_filename . ' exists';
    }
    if(!$have_top_adverts_css || isset($_REQUEST['clean_cache'])  || isset($_REQUEST['remove_cache'])) {
        $have_top_adverts_css = false;
        $f_top_css = fopen($css_filename, "wb");

        $no_image_advert = $path . "images/navigation/no_pic.gif";
        $css_line = ".logo-nopic:before {background-image:url(".getDataURI($no_image_advert).");}" . "\n";
        fwrite($f_top_css, $css_line, strlen($css_line));
    }*/


    //$featured_code = $pfcache->get($featured_key);
    //$featured_actions = $pfcache->get($featured_key . '_actions');

    if (isset($_REQUEST['debug_cache'])) {
        echo '<br>$domain_id = ' . $domain_id;
        echo '<br>$catdom_id = ' . $catdom_id;
        echo '<br>$catdom_id_adv = ' . $catdom_id_adv;
        echo '<br>$featured_key = ' . $featured_key;
    }

    //echo $query_categtop;

    $featured_code = null;
    if ($featured_code == null || isset($_SESSION['user_id'])) {
        ob_start();
        $result_categtop = mysql_query($query_categtop) or die(mysql_error());
        if (mysql_num_rows($result_categtop) > 0) {
            $have_featured = "yes";

            $adverts = array();
            while ($row_top = mysql_fetch_assoc($result_categtop)) {
                $advertisment_id = $row_top['advertisment_id'];

                $adverts[$advertisment_id] = array(
                    "adv_code" => $row_top['adv_code'],
                    "advertisment_id" => $row_top['advertisment_id'],
                    "member_id" => intval($row_top['member_id']),
                    "invoice_no" => trim($row_top['invoice_no']),
                    "bind_type" => trim($row_top['bind_type']),
                    "active_from" => trim($row_top['active_from']),
                    "active_to" => trim($row_top['active_to']),
                    "short_title_en" => stripslashes($row_top['short_title_en']),
                    "title_tr" => $row_top['title_tr'],
                    "advertisment" => $row_top['advertisment'],
                    "logo" => $row_top['logo'],
                    "display_name" => str_replace('"', '', stripslashes($row_top["short_title_en"])),
                    "friendly_url" => $row_top["title_tr"],
                    "open_window" => $row_top["open_window"],
                    "website" => $row_top["website"],
                    "show_website" => intval($row_top["show_website"]),
                    "nofollow" => intval($row_top["nofollow"]),
                    "lb-logo_file" => dirname(__FILE__) . "/../../images/advertisments/" . $row_top['advertisment'],
                    "lb-logo_url" => $protocol . $microdata_host . "/images/advertisments/" . $row_top['advertisment'],
                    "lb-logo_class" => "logo-" . $advertisment_id,
                    "nofollow_domains" => $row_top['nofollow_domains']
                );
            }

            /*if (!$have_top_adverts_css) {
                foreach ($adverts as $advertisment_id => $a) {
                    if (file_exists($a['lb-logo_file'])) {
                        //$css_line = "." . $a['lb-logo_class'] . ":before {content:url(" . getDataURI($a['lb-logo_file']) . ");}" . "\n";
                        $css_line = "." . $a['lb-logo_class'] . ":before {background-image:url(" . getDataURI($a['lb-logo_file']) . ");}" . "\n";
                        fwrite($f_top_css, $css_line, strlen($css_line));
                    } else {
                        $adverts[$advertisment_id]['lb-logo_class'] = "logo-nopic";
                    }
                }
            } else {
                foreach ($adverts as $advertisment_id => $a) {
                    if (!file_exists($a['lb-logo_file'])) {
                        $adverts[$advertisment_id]['lb-logo_class'] = "logo-nopic";
                    }
                }
            }*/


            ?>
            <section aria-label="<?php echo $recomented_value_en; ?>">
                <?php
                $show_click_shout = 1;
                if(isset($module_params['show_click_shout'])) {
                    $show_click_shout = intval($module_params['show_click_shout']);
                }
                if (isset($module_show_featured_title) && intval($module_show_featured_title) == 1) {
                    ?>
                    <header class="featured-title">
                        <?php
                        if(isset($hide_adverts_title) && $hide_adverts_title == 1) {
                            // not title
                        }
                        else {
                            ?>
                            <strong><?php echo $recomented_value_en; ?></strong>
                            <?php
                        }
                        ?>

                        <?php
                        if($show_click_shout == 1) {
                            ?>
                            <div class="click-shout">
                                <i class="fa fa-hand-pointer-o fa-rotate-180 fa-lg"></i> Click on logos to visit the websites
                            </div>
                            <?php
                        }
                        ?>
                    </header>

                    <?php
                }

                ?>
                <div class="lbs-top-list primary container-fluid clearfix">

                    <?php
                    $count_categtop = 1;
                    $total_adverts = mysql_num_rows($result_categtop);
                    $num_adverts = 0;
                    //while($line_categtop = mysql_fetch_assoc($result_categtop)){
                    foreach ($adverts as $advertisment_id => $line_categtop) {
                        $display_name = str_replace('"', '', $line_categtop["short_title_en"]);
                        $shortNameURL = $line_categtop["title_tr"];

                        if(!in_array($protocol . $microdata_host . "/$shortNameURL", $jsonld['links'])) {
                            $jsonld['links'][] = $protocol . $microdata_host . "/$shortNameURL";
                        }

                        $shortNameALT = str_replace('"', '', $line_categtop["short_title_en"]);
                        $adv_unit_salesview_class = "hidden";
                        if (isset($_SESSION['user_id'])) {
                            $adv_unit_salesview_class = "adv-unit-salesview";
                        }

                        // Generate Logo URL
                        $show_website = intval($line_categtop['show_website']);
                        $logo_url = "";
                        $logo_onclick = "";
                        $logo_target = "_blank";
                        if ($line_categtop['open_window'] == "yes" && $line_categtop['website'] != "") {
                            $logo_url = fix_url($line_categtop['website']);
                        } elseif ($line_categtop['open_window'] == "relative" && $line_categtop['website'] != "") {
                            $logo_url = fix_url($line_categtop['website']);
                        } else {
                            $logo_url = "$base_url/click_count.php?link=" . $shortNameURL
                                . "&amp;type=www"
                                . "&amp;id=" . $line_categtop['advertisment_id']
                                . "&amp;domain=" . $line_domain["domainname"]
                                . "&amp;domain_id=" . $domain_id
                                . "&amp;click_from=top"
                                . "&amp;catdom_id=" . $catdom_id;
                        }

                        if ($line_categtop['open_window'] == "yes" && $line_categtop['website'] != "") {
                            $logo_onclick = "onclick=\"window.open('$base_url/click_count.php?link=" . $shortNameURL
                                . "&amp;type=adv"
                                . "&amp;id=" . $line_categtop['advertisment_id']
                                . "&amp;domain=" . $line_domain["domainname"]
                                . "&amp;domain_id=" . $domain_id
                                . "&amp;click_from=top"
                                . "&amp;catdom_id=" . $catdom_id . "','',''); return false;\"";
                        }

                        $rel_tag = $logo_target == "_blank" ? "noopener" : "";
                        $rel_tag .= (is_nofollow($line_categtop['nofollow_domains']) || $rel_nofollow == 1) ? " nofollow" : ""; 
                        

                        //if (!isset($_SESSION['user_id'])) {
                            //mysql_query("UPDATE advertisment SET views=views+1 WHERE advertisment_id='{$line_categtop['advertisment_id']}'") or die (mysql_error());
                            //count_views('adverts_stats_views', 'advertisment_id', $line_categtop['advertisment_id'], $domain_id, $catdom_id, 'top');

                            $featured_actions ['adverts'][] = $line_categtop['advertisment_id'];

                            $_adverts_views [] = array(
                                "adv_code" => $line_categtop['adv_code'],
                                "advertisment_id" => $line_categtop['advertisment_id'],
                                "domain_id" => $domain_id,
                                "catdom_id" => $catdom_id_adv,
                                "domainname" => $ultra_domainname,
                                "date_short" => date("Y-m-d"),
                                "date_long" => date("Y-m-d H:i:s"),
                                "views" => 1,
                                "view_from" => 'sel'
                            );
                        //}

                        if ($num_adverts % 5 == 0) {
                            echo '<div class="row">';
                        }
                        ?>
                        <div class="adv_unit adv-unit-top col-xs-2" data-mh="lb-primary">

                            <div class="lb-logo-container">
                                <?php
                                $adv_logo = $path . "images/navigation/no_pic.gif";
                                $adv_logo_mobile = $path . "images/navigation/no_pic.gif";

                                $img_data = '';
                                ob_start();
                                ?>
                                data-src="<?=$adv_logo;?>"

                                <?php
                                $img_data = ob_get_clean();

                                if ($line_categtop['advertisment'] != "") {
                                    $adv_lazy = $path . "images/advertisments/85x74-lazy-placeholder.png";
                                    $adv_logo = $path . "images/advertisments/{$line_categtop["advertisment"]}";
                                    $adv_logo_mobile = $path . "images/advertisments/{$line_categtop["advertisment"]}";
                                    ob_start();
                                    ?>
                                    src="<?=$adv_lazy;?>" data-src="<?=$adv_logo;?>" width="85" height="74"

                                    <?php
                                    $img_data = ob_get_clean();
                                }
                                if ($line_categtop['logo'] != "") {
                                    $adv_lazy = $path . "images/advertisments/85x85-lazy-placeholder.png";
                                    $adv_logo = $path . "images/advertisments/{$line_categtop["advertisment_id"]}/md/{$line_categtop["logo"]}";
                                    $adv_logo_mobile = $path . "images/advertisments/{$line_categtop["advertisment_id"]}/{$line_categtop["logo"]}";
                                    ob_start();
                                    ?>
                                    src="<?=$adv_lazy;?>" data-src="<?=$adv_logo;?>" width="85" height="85"

                                    <?php
                                    $img_data = ob_get_clean();
                                }
                                if ($show_website == 1) {
                                    echo '<a title="' . $shortNameALT . '" href="' . $logo_url . '" rel="' . $rel_tag . '" target="' . $logo_target . '" ' . $logo_onclick . ' class="lb-logo">';

                                    ?>
                                    <img <?=$img_data;?> alt="<?php echo $shortNameALT; ?>" title="<?php echo $shortNameALT; ?>" class="lazy"/>
                                    <noscript>
                                        <img src="<?=$adv_logo;?>" alt="<?php echo $shortNameALT; ?>" title="<?php echo $shortNameALT; ?>" />
                                    </noscript>


                                    <?php
                                    echo '</a>';
                                }
                                else {
                                    ?>
                                    <img <?=$img_data;?> alt="<?php echo $shortNameALT; ?>" title="<?php echo $shortNameALT; ?>" class="lazy"/>
                                    <noscript>
                                        <img src="<?=$adv_logo;?>" alt="<?php echo $shortNameALT; ?>" title="<?php echo $shortNameALT; ?>" />
                                    </noscript>
                                    <?php
                                }


                                ?>

                            </div>
                            <?php
                            /*
                            ?>
                            <div class="lb-info hidden-xs">
                                <?php
                                if ($show_website == 1) {

                                    ?>
                                    <a href="<?php echo $logo_url; ?>" <?php echo((is_nofollow($line_categtop['nofollow_domains']) || $rel_nofollow == 1) ? 'rel="nofollow"' : ''); ?>
                                       target="<?php echo $logo_target; ?>" class="lb"
                                       title="<?php echo $shortNameALT; ?>">
                                    <?php
                                }
                                ?>
                                <div class="lb-details">
                                    <div class="lb-heading" aria-level="3" role="heading"><span><?=$shortNameALT;?></span></div>

                                </div>
                                <?php
                                if ($show_website == 1) {
                                    ?>
                                    </a>
                                    <?php
                                }
                                ?>
                            </div>

                            <?php
                            */

                            if ($line_categtop['open_window'] != "yes" && $line_categtop['open_window'] != "relative") {
                                if(!isset($module_params['use_defaults'])) {
                                    ?>
                                    <div class="advcont hidden-xs">
                                        <a href="<?php echo $shortNameURL; ?>"
                                           title="<?php echo $shortNameALT; ?>" target="_blank" rel="noopener"
                                           class="featured_adv_linkage">
                                            <i class="fa fa-info-circle"></i>
                                            <span class="sr-only"><?= $shortNameALT; ?></span>
                                        </a>
                                    </div>
                                    <?php
                                }
                            }
                            if (isset($_SESSION['user_id']) && $_SESSION['design_view'] == "on") {
                                ?>
                                <div class="<?php echo $adv_unit_salesview_class; ?> hidden-xs">
                                    <?php
                                    //echo 'open_window=',$line_categtop['open_window'] , " / ", $line_categtop['website'], "<br/>";


                                    $invoice_no = trim($line_categtop["invoice_no"]);
                                    $bind_type = trim($line_categtop["bind_type"]);
                                    $t_active_from = (trim($line_categtop["active_from"]) != "" && trim($line_categtop["active_from"]) != "0000-00-00") ? strtotime(trim($line_categtop["active_from"])) : "null";
                                    $t_active_to = (trim($line_categtop["active_to"]) != "" && trim($line_categtop["active_to"]) != "0000-00-00") ? strtotime(trim($line_categtop["active_to"])) : "null";
                                    $cur_timestamp = time();
                                    echo '<br/><a href="../admin/advert_manager.php?advert_action=advert_edit_main&amp;advertisment_id=', $line_categtop['advertisment_id'], '" target="_blank">Edit</a>';
                                    echo '<div class="info-salesview">';
                                    if ($invoice_no != "") {
                                        $inv_details = "";
                                        $qinv = "select i.details from advertisment_invoice i where i.adv_code='{$line_categtop["adv_code"]}' and i.in_use='1' and i.invoice='{$line_categtop["invoice_no"]}';";
                                        $rinv = mysql_query($qinv);
                                        if ($rinv && mysql_num_rows($rinv) > 0) {
                                            $rowinv = mysql_fetch_assoc($rinv);
                                            $inv_details = stripslashes($rowinv['details']);
                                        }

                                        if (array_key_exists($invoice_no, $short_invoice_types)) {
                                            echo '<span style="color:' . $short_invoice_types[$invoice_no]['color'] . ';">' . $short_invoice_types[$invoice_no]['short_name'] . '</span>';
                                        } else {
                                            echo '<span style="color: #0000EE; font-weight: bold; text-decoration: none; ">' . $invoice_no . '</span>';
                                        }

                                        if ($inv_details != "") {
                                            ?>
                                            <a href="javascript:;" data-toggle="tooltip" data-container="body"
                                               data-original-title="<?php echo $inv_details; ?>" class="tooltip_views"
                                               title="<?php echo $inv_details; ?>"><i
                                                    class="fa fa-info-circle text-danger"></i></a>
                                            <?php
                                        }

                                    } else {
                                        echo '<span style="color:#ff0000;">[ <strong>NO_INVOICE</strong> ]</span>';
                                    }

                                    if ($is_promo_cat == 1) {
                                        $qpg = "SELECT * FROM promos WHERE advertisment_id='{$line_categtop['advertisment_id']}' AND promo_cat_id='$catdom_id_adv';";
                                        $rpg = @mysql_query($qpg);
                                        if($rpg && mysql_num_rows($rpg) > 0) {
                                            $num_pg = mysql_num_rows($rpg);
                                            $text_pg = $num_pg > 1 ? $num_pg . ' promos.' : '1 promo.';
                                            $active_pg = 0;
                                            $inactive_pg = 0;
                                            while($rowpg = mysql_fetch_assoc($rpg)) {
                                                if($rowpg['status'] == 1) $active_pg += 1;
                                                else $inactive_pg += 1;
                                            }
                                            $text_pg .= $active_pg > 0 ? $active_pg . ' active.' : '';
                                            $text_pg .= $inactive_pg > 0 ? $inactive_pg . ' inactive.' : '';

                                            echo '<a href="/admin/index.php?plugin=promo&action=promos&catdom_id='.$domain_id.'&promo_cat_id='.$catdom_id_adv.'" target="_blank" title="'.$text_pg.'" style="font-size:9px; color: #fff; background-color: #0A246A; padding:3px; margin: 0 4px; border-radius: 10px; text-decoration: none;">' . $num_pg . 'P</a>';
                                        }
                                        else {
                                            echo '<a href="/admin/index.php?plugin=promo&action=promos&catdom_id='.$domain_id.'&promo_cat_id='.$catdom_id_adv.'" target="_blank" title="NO PROMO" style="font-size:9px; color: #333; background-color: #ccc; padding:3px; margin: 0 4px; border-radius: 10px; text-decoration: none;">0P</a>';
                                        }
                                    }

                                    if ($t_active_to != "null") {
                                        $active_from = $t_active_from != "null" ? date("d/m/Y", intval($t_active_from)) : 'Null';
                                        $active_to = $t_active_to != "null" ? date("d/m/Y", intval($t_active_to)) : 'Null';

                                        if ($cur_timestamp > intval($t_active_to)) {
                                            echo '<br style="clear:both;"/><div style="color:#ff0000;" title="EXPIRED!!!">', $active_from, ' - ', $active_to, '</div>';
                                        } elseif (intval($t_active_to) < (strtotime("+2 month", $cur_timestamp))) {
                                            echo '<br style="clear:both;"/><div style="color:#0000EE;" title="EXPIRES IN LESS THAN 2 MONTHS!">', $active_from, ' - ', $active_to, '</div>';
                                        } else {
                                            echo '<br style="clear:both;"/><div style="color:#000000;" title="EXPIRES IN MORE THAN 2 MONTHS!">', $active_from, ' - ', $active_to, '</div>';
                                        }
                                    } else {
                                        $active_from = trim($t_active_from) != "null" ? date("d/m/Y", intval($t_active_from)) : 'Null';
                                        $active_to = trim($t_active_to) != "null" ? date("d/m/Y", intval($t_active_to)) : 'Null';
                                        echo '<br style="clear:both;"/><div style="color:#ff0000;" title="No Expiration Date">', $active_from, ' - ', $active_to, '</div>';
                                    }
                                    if ($bind_type != "") {
                                        echo '<div style="clear: both; height: 16px; color:#ff0000; background-color: #FFE900;">', ($bind_types[$bind_type]), '</div>';
                                    }


                                    if ($line_categtop["member_id"] > 0) {
                                        $qha = "SELECT a.name, a.surname, a.user_id FROM auth a, members m WHERE m.member_id='{$line_categtop['member_id']}' AND a.user_id=m.salesman_id";
                                        $rha = @mysql_query($qha);
                                        if ($rha && mysql_num_rows($rha) > 0) {
                                            $line_member = mysql_fetch_assoc($rha);
                                            echo '<div style="clear: both; height: 16px;">';
                                            echo '<strong>SP:</strong> ' . $line_member["name"] . ' ' . $line_member["surname"];
                                            echo '</div>';
                                        } else {
                                            echo '<div style="clear: both; height: 16px;">NO_SALESMAN</div>';
                                        }
                                    } else {
                                        echo '<div style="clear: both; height: 16px;">NO_CUSTOMER</div>';
                                    }
                                    echo '</div>';

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

                        </div>


                        <?php
                        if ($num_adverts > 0) {
                            if (($num_adverts + 1) % 5 == 0) echo '</div>';
                            elseif ($num_adverts + 1 == $total_adverts) echo '</div>';
                        }


                        $count_categtop++;
                        $num_adverts++;
                    }
                    ?>
                </div>
            </section>
            <?php
        }

        $featured_code = ob_get_clean();
        //$pfcache->set($featured_key, $featured_code, 3600);
        //$pfcache->set($featured_key . '_actions', $featured_actions, 3600);

    }


    //if (!isset($_SESSION['user_id'])) {
    if ($featured_actions != null && is_array($featured_actions)) {

        $have_featured = "yes";

        if(!isset($cached_actions ['update_advert_views']['top'])) {
            $cached_actions ['update_advert_views']['top'] = array();
        }
        $cached_actions ['update_advert_views']['top'] = array_merge($cached_actions ['update_advert_views']['top'], $featured_actions['adverts']);
        $cached_actions ['update_advert_views']['top_catdom_id'] = $catdom_id_adv;

        /*$have_featured = "yes";
        // Update Adverts Count
        $f_adv_ids = implode(", ", $featured_actions['adverts']);
        $f_adv_update = "UPDATE advertisment SET views=views+1 WHERE advertisment_id IN '$f_adv_ids';";
        $f_r_update = mysql_query($f_adv_update);

        // Insert Adverts Stats Views
        $f_adv_tmp = array();
        foreach ($featured_actions['adverts'] as $f_adv_id) {
            $f_adv_tmp [] = "('$f_adv_id', '$domain_id', NOW(), '$ipfrom', 1, 'top' )";
        }
        $f_adv_tmp_str = implode(", ", $f_adv_tmp);
        $f_adv_count_views = "INSERT INTO adverts_stats_views (advertisment_id, domain_id, added_on, ipfrom, views, view_from) VALUES $f_adv_tmp_str;";
        $f_r_count_views = mysql_query($f_adv_count_views);*/
    }
   // }
    echo $featured_code;


}


 //$query_adverts - loaded from ../general/queries.php

/*if (isset($_SESSION['user_id'])){
	echo $query_adverts;
}*/

function shuffle_assoc($list) {
    if (!is_array($list)) return $list;

    $keys = array_keys($list);
    shuffle($keys);
    $random = array();
    foreach ($keys as $key) {
        $random[$key] = $list[$key];
    }
    return $random;
}


if(isset($module_show_secondary_section) && intval($module_show_secondary_section) == 1) {


    $f_sel_css = null;
    //$non_featured_code = $pfcache->get($non_featured_key);
    //$non_featured_actions = $pfcache->get($non_featured_key . '_actions');

    $non_featured_code = null;
    if($non_featured_code == null || !$have_sel_adverts_css || isset($_SESSION['user_id']) ) {

        ob_start();
        $result_adverts = @mysql_query($query_adverts);
        if ($result_adverts && mysql_num_rows($result_adverts) > 0) {
            $sel_adverts = array();
            while ($row_top = mysql_fetch_assoc($result_adverts)) {
                $advertisment_id = $row_top['advertisment_id'];

                $sel_adverts[$advertisment_id] = array(
                    "adv_code" => $row_top['adv_code'],
                    "advertisment_id" => $row_top['advertisment_id'],
                    "member_id" => intval($row_top['member_id']),
                    "invoice_no" => trim($row_top['invoice_no']),
                    "bind_type" => trim($row_top['bind_type']),
                    "active_from" => trim($row_top['active_from']),
                    "active_to" => trim($row_top['active_to']),
                    "short_title_en" => stripslashes($row_top['short_title_en']),
                    "title_tr" => $row_top['title_tr'],
                    "advertisment" => $row_top['advertisment'],
                    "logo" => $row_top['logo'],
                    "display_name" => str_replace('"', '', stripslashes($row_top["short_title_en"])),
                    "friendly_url" => $row_top["title_tr"],
                    "open_window" => $row_top["open_window"],
                    "website" => $row_top["website"],
                    "show_website" => intval($row_top["show_website"]),
                    "nofollow" => intval($row_top["nofollow"]),
                    "lb-logo_file" => dirname(__FILE__) . "/../../images/advertisments/" . $row_top['advertisment'],
                    "lb-logo_url" => $protocol . $microdata_host . "/images/advertisments/" . $row_top['advertisment'],
                    "lb-logo_class" => "logo-" . $advertisment_id,
                    "nofollow_domains" => $row_top['nofollow_domains']
                );
            }


            if(is_array($sel_adverts) && count($sel_adverts) > 0) {
                if($catdom_id_adv != 611) {
                    $sel_adverts = shuffle_assoc($sel_adverts);
                }

                $subfeatured_title = "More Featured $recomented_value_en";

                ?>
                <section aria-label="<?=$subfeatured_title;?>">
                    <?php
                    $show_separator = $have_featured == "yes";
                    //if ($catdom_id_adv != $domain_id && $have_featured == "no") {
                    if ($have_featured == "no") {
                        ?>
                        <header class="featured-title">
                            <?php
                            if(isset($hide_adverts_title) && $hide_adverts_title == 1) {
                                // not title
                            }
                            else {
                                ?>
                                <strong><?php echo $recomented_value_en; ?></strong>
                                <?php
                            }
                            ?>

                            <div class="click-shout">
                                <i class="fa fa-hand-pointer-o fa-rotate-180 fa-lg"></i> Click on logos to visit the websites
                            </div>
                        </header>
                        <?php
                    }

                    ?>
                    <div class="lbs-top-list secondary <?php echo ($show_separator) ? 'with-border' : 'no-border'; ?> container-fluid clearfix">
                        <?php
                        $count_categtop = 1;
                        $total_adverts = mysql_num_rows($result_adverts);
                        $num_adverts = 0;
                        //echo '<div class="row shuffle-this">';
                        foreach ($sel_adverts as $advertisment_id => $line_categtop) {
                            $display_name = str_replace('"', '', $line_categtop["short_title_en"]);
                            $shortNameURL = $line_categtop["title_tr"];

                            if(!in_array($protocol . $microdata_host . "/$shortNameURL", $jsonld['links'])) {
                                $jsonld['links'][] = $protocol . $microdata_host . "/$shortNameURL";
                            }

                            $shortNameALT = str_replace('"', '', $line_categtop["short_title_en"]);
                            $adv_unit_salesview_class = "hidden";
                            if (isset($_SESSION['user_id'])) {
                                $adv_unit_salesview_class = "adv-unit-salesview";
                            }

                            // Generate Logo URL
                            $show_website = intval($line_categtop['show_website']);
                            $logo_url = "";
                            $logo_onclick = "";
                            $logo_target = "_blank";
                            if ($line_categtop['open_window'] == "yes" && $line_categtop['website'] != "") {
                                $logo_url = fix_url($line_categtop['website']);
                            } elseif ($line_categtop['open_window'] == "relative" && $line_categtop['website'] != "") {
                                $logo_url = fix_url($line_categtop['website']);
                            } else {
                                $logo_url = "$base_url/click_count.php?link=" . $shortNameURL
                                    . "&amp;type=www"
                                    . "&amp;id=" . $line_categtop['advertisment_id']
                                    . "&amp;domain=" . $line_domain["domainname"]
                                    . "&amp;domain_id=" . $domain_id
                                    . "&amp;click_from=top"
                                    . "&amp;catdom_id=" . $catdom_id;
                            }

                            if ($line_categtop['open_window'] == "yes" && $line_categtop['website'] != "") {
                                $logo_onclick = "onclick=\"window.open('$base_url/click_count.php?link=" . $shortNameURL
                                    . "&amp;type=adv"
                                    . "&amp;id=" . $line_categtop['advertisment_id']
                                    . "&amp;domain=" . $line_domain["domainname"]
                                    . "&amp;domain_id=" . $domain_id
                                    . "&amp;click_from=top"
                                    . "&amp;catdom_id=" . $catdom_id . "','',''); return false;\"";
                            }

                            //if (!isset($_SESSION['user_id'])) {
                                //mysql_query("UPDATE advertisment SET views=views+1 WHERE advertisment_id='{$line_categtop['advertisment_id']}'") or die (mysql_error());
                                //count_views('adverts_stats_views', 'advertisment_id', $line_categtop['advertisment_id'], $domain_id, $catdom_id, 'top');

                                $non_featured_actions['adverts'][] = $line_categtop['advertisment_id'];

                                $_adverts_views [] = array(
                                    "adv_code" => $line_categtop['adv_code'],
                                    "advertisment_id" => $line_categtop['advertisment_id'],
                                    "domain_id" => $domain_id,
                                    "catdom_id" => $catdom_id_adv,
                                    "domainname" => $ultra_domainname,
                                    "date_short" => date("Y-m-d"),
                                    "date_long" => date("Y-m-d H:i:s"),
                                    "views" => 1,
                                    "view_from" => 'sel'
                                );
                            //}

                            $rel_tag = $logo_target == "_blank" ? "noopener" : "";
                            $rel_tag .= (is_nofollow($line_categtop['nofollow_domains']) || $rel_nofollow == 1) ? " nofollow" : "";


                            if ($num_adverts % 5 == 0) {
                                if($catdom_id_adv != 611) {
                                    echo '<div class="row shuffle-this">';
                                }
                                else {
                                    echo '<div class="row">';
                                }
                            }
                            ?>
                            <div class="adv_unit adv-unit-top col-xs-2" data-mh="lb-secondary">

                                <div class="lb-logo-container">
                                    <?php
                                    $adv_logo = $path . "images/navigation/no_pic.gif";
                                    $adv_logo_mobile = $path . "images/navigation/no_pic.gif";

                                    $img_data = '';
                                    ob_start();
                                    ?>
                                    data-src="<?=$adv_logo;?>"
                                    <?php
                                    $img_data = ob_get_clean();

                                    if ($line_categtop['advertisment'] != "") {

                                        $adv_lazy = $path . "images/advertisments/85x74-lazy-placeholder.png";
                                        $adv_logo = $path . "images/advertisments/{$line_categtop["advertisment"]}";
                                        $adv_logo_mobile = $path . "images/advertisments/{$line_categtop["advertisment"]}";
                                        ob_start();
                                        ?>
                                        src="<?=$adv_lazy;?>" data-src="<?=$adv_logo;?>" width="85" height="74"

                                        <?php
                                        $img_data = ob_get_clean();

                                    }
                                    if ($line_categtop['logo'] != "") {
                                        $adv_lazy = $path . "images/advertisments/85x85-lazy-placeholder.png";
                                        $adv_logo = $path . "images/advertisments/{$line_categtop["advertisment_id"]}/md/{$line_categtop["logo"]}";
                                        $adv_logo_mobile = $path . "images/advertisments/{$line_categtop["advertisment_id"]}/{$line_categtop["logo"]}";
                                        ob_start();
                                        ?>
                                        src="<?=$adv_lazy;?>" data-src="<?=$adv_logo;?>" width="85" height="85"
                                        <?php
                                        $img_data = ob_get_clean();
                                    }



                                    if ($show_website == 1) {
                                        echo '<a title="'.$shortNameALT.'" href="' . $logo_url . '" rel="' . $rel_tag . '" target="' . $logo_target . '" ' . $logo_onclick . ' class="lb-logo">';

                                        ?>
                                        <img <?=$img_data;?> alt="<?php echo $shortNameALT; ?>" title="<?php echo $shortNameALT; ?>" class="lazy"/>
                                        <noscript>
                                            <img src="<?=$adv_logo;?>" alt="<?php echo $shortNameALT; ?>" title="<?php echo $shortNameALT; ?>" />
                                        </noscript>


                                        <?php
                                        echo '</a>';
                                    }
                                    else {
                                        ?>
                                        <img <?=$img_data;?> alt="<?php echo $shortNameALT; ?>" title="<?php echo $shortNameALT; ?>" class="lazy"/>
                                        <noscript>
                                            <img src="<?=$adv_logo;?>" alt="<?php echo $shortNameALT; ?>" title="<?php echo $shortNameALT; ?>" />
                                        </noscript>
                                        <?php
                                    }


                                    ?>

                                </div>
                                <?php
                                /*
                                ?>
                                <div class="lb-info">
                                    <?php
                                    if ($show_website == 1) {
                                        ?>
                                        <a href="<?php echo $logo_url; ?>" <?php echo((is_nofollow($line_categtop['nofollow_domains']) || $rel_nofollow == 1) ? 'rel="nofollow"' : ''); ?>
                                           target="<?php echo $logo_target; ?>" class="lb"
                                           title="<?php echo $shortNameALT; ?>">
                                        <?php
                                    }
                                    ?>
                                    <div class="lb-details">
                                        <div class="lb-heading" aria-level="3" role="heading"><span><?=$shortNameALT;?></span></div>
                                    </div>
                                    <?php
                                    if ($show_website == 1) {
                                        ?>
                                        </a>
                                        <?php
                                    }
                                    ?>
                                </div>

                                <?php
                                */

                                if ($line_categtop['open_window'] != "yes" && $line_categtop['open_window'] != "relative") {
                                    if(!isset($module_params['use_defaults'])) {
                                        ?>
                                        <div class="advcont hidden-xs">
                                            <a href="<?php echo $shortNameURL; ?>"
                                               title="<?php echo $shortNameALT; ?>" target="_blank" rel="noopener"
                                               class="featured_adv_linkage">
                                                <i class="fa fa-info-circle"></i>
                                                <span class="sr-only"><?php echo $shortNameALT; ?></span>
                                            </a>
                                        </div>
                                        <?php
                                    }
                                }
                                ?>

                                <div class="<?php echo $adv_unit_salesview_class; ?> hidden-xs">
                                    <?php
                                    //echo 'open_window=',$line_categtop['open_window'] , " / ", $line_categtop['website'], "<br/>";


                                    if (isset($_SESSION['user_id']) && $_SESSION['design_view'] == "on") {

                                        $invoice_no = trim($line_categtop["invoice_no"]);
                                        $bind_type = trim($line_categtop["bind_type"]);
                                        $t_active_from = (trim($line_categtop["active_from"]) != "" && trim($line_categtop["active_from"]) != "0000-00-00") ? strtotime(trim($line_categtop["active_from"])) : "null";
                                        $t_active_to = (trim($line_categtop["active_to"]) != "" && trim($line_categtop["active_to"]) != "0000-00-00") ? strtotime(trim($line_categtop["active_to"])) : "null";
                                        $cur_timestamp = time();
                                        echo '<br/><a href="../admin/advert_manager.php?advert_action=advert_edit_main&amp;advertisment_id=', $line_categtop['advertisment_id'], '" target="_blank">Edit</a>';
                                        echo '<div class="info-salesview">';
                                        if ($invoice_no != "") {
                                            $inv_details = "";
                                            $qinv = "select i.details from advertisment_invoice i where i.adv_code='{$line_categtop["adv_code"]}' and i.in_use='1' and i.invoice='{$line_categtop["invoice_no"]}';";
                                            $rinv = mysql_query($qinv);
                                            if ($rinv && mysql_num_rows($rinv) > 0) {
                                                $rowinv = mysql_fetch_assoc($rinv);
                                                $inv_details = stripslashes($rowinv['details']);
                                            }

                                            if (array_key_exists($invoice_no, $short_invoice_types)) {
                                                echo '<span style="color:' . $short_invoice_types[$invoice_no]['color'] . ';">' . $short_invoice_types[$invoice_no]['short_name'] . '</span>';
                                            } else {
                                                echo '<span style="color: #0000EE; font-weight: bold; text-decoration: none; ">' . $invoice_no . '</span>';
                                            }

                                            if ($inv_details != "") {
                                                ?>
                                                <a href="javascript:;" data-toggle="tooltip" data-container="body"
                                                   data-original-title="<?php echo $inv_details; ?>" class="tooltip_views"
                                                   title="<?php echo $inv_details; ?>"><i
                                                        class="fa fa-info-circle text-danger"></i></a>
                                                <?php
                                            }

                                        } else {
                                            echo '<span style="color:#ff0000;">[ <strong>NO_INVOICE</strong> ]</span>';
                                        }

                                        if ($is_promo_cat == 1) {
                                            $qpg = "SELECT * FROM promos WHERE advertisment_id='{$line_categtop['advertisment_id']}' AND promo_cat_id='$catdom_id_adv';";
                                            $rpg = @mysql_query($qpg);
                                            if($rpg && mysql_num_rows($rpg) > 0) {
                                                $num_pg = mysql_num_rows($rpg);
                                                $text_pg = $num_pg > 1 ? $num_pg . ' promos.' : '1 promo.';
                                                $active_pg = 0;
                                                $inactive_pg = 0;
                                                while($rowpg = mysql_fetch_assoc($rpg)) {
                                                    if($rowpg['status'] == 1) $active_pg += 1;
                                                    else $inactive_pg += 1;
                                                }
                                                $text_pg .= $active_pg > 0 ? $active_pg . ' active.' : '';
                                                $text_pg .= $inactive_pg > 0 ? $inactive_pg . ' inactive.' : '';

                                                echo '<a href="/admin/index.php?plugin=promo&action=promos&catdom_id='.$domain_id.'&promo_cat_id='.$catdom_id_adv.'" target="_blank" title="'.$text_pg.'" style="font-size:9px; color: #fff; background-color: #0A246A; padding:3px; margin: 0 4px; border-radius: 10px; text-decoration: none;">' . $num_pg . 'P</a>';
                                            }
                                            else {
                                                echo '<a href="/admin/index.php?plugin=promo&action=promos&catdom_id='.$domain_id.'&promo_cat_id='.$catdom_id_adv.'" target="_blank" title="NO PROMO" style="font-size:9px; color: #333; background-color: #ccc; padding:3px; margin: 0 4px; border-radius: 10px; text-decoration: none;">0P</a>';
                                            }
                                        }

                                        if ($t_active_to != "null") {
                                            $active_from = $t_active_from != "null" ? date("d/m/Y", intval($t_active_from)) : 'Null';
                                            $active_to = $t_active_to != "null" ? date("d/m/Y", intval($t_active_to)) : 'Null';

                                            if ($cur_timestamp > intval($t_active_to)) {
                                                echo '<br style="clear:both;"/><div style="color:#ff0000;" title="EXPIRED!!!">', $active_from, ' - ', $active_to, '</div>';
                                            } elseif (intval($t_active_to) < (strtotime("+2 month", $cur_timestamp))) {
                                                echo '<br style="clear:both;"/><div style="color:#0000EE;" title="EXPIRES IN LESS THAN 2 MONTHS!">', $active_from, ' - ', $active_to, '</div>';
                                            } else {
                                                echo '<br style="clear:both;"/><div style="color:#000000;" title="EXPIRES IN MORE THAN 2 MONTHS!">', $active_from, ' - ', $active_to, '</div>';
                                            }
                                        } else {
                                            $active_from = trim($t_active_from) != "null" ? date("d/m/Y", intval($t_active_from)) : 'Null';
                                            $active_to = trim($t_active_to) != "null" ? date("d/m/Y", intval($t_active_to)) : 'Null';
                                            echo '<br style="clear:both;"/><div style="color:#ff0000;" title="No Expiration Date">', $active_from, ' - ', $active_to, '</div>';
                                        }
                                        if ($bind_type != "") {
                                            echo '<div style="clear: both; height: 16px; color:#ff0000; background-color: #FFE900;">', ($bind_types[$bind_type]), '</div>';
                                        }


                                        if ($line_categtop["member_id"] > 0) {
                                            $qha = "SELECT a.name, a.surname, a.user_id FROM auth a, members m WHERE m.member_id='{$line_categtop['member_id']}' AND a.user_id=m.salesman_id";
                                            $rha = @mysql_query($qha);
                                            if ($rha && mysql_num_rows($rha) > 0) {
                                                $line_member = mysql_fetch_assoc($rha);
                                                echo '<div style="clear: both; height: 16px;">';
                                                echo '<strong>SP:</strong> ' . $line_member["name"] . ' ' . $line_member["surname"];
                                                echo '</div>';
                                            } else {
                                                echo '<div style="clear: both; height: 16px;">NO_SALESMAN</div>';
                                            }
                                        } else {
                                            echo '<div style="clear: both; height: 16px;">NO_CUSTOMER</div>';
                                        }
                                        echo '</div>';
                                    }
                                    ?>
                                </div>

                            </div>
                            <?php
                            if ($num_adverts > 0) {
                                if (($num_adverts + 1) % 5 == 0) echo '</div>';
                                elseif ($num_adverts + 1 == $total_adverts) echo '</div>';
                            }
                            $count_categtop++;
                            $num_adverts++;
                        }

                        //echo '</div>';

                        /*if($get_non_featured_actions) {
                            $pfcache->set($non_featured_key . '_actions', $non_featured_actions, 600);
                        }*/
                        ?>
                    </div>
                </section>
                <?php



            }


        }

        $non_featured_code = ob_get_clean();
        //$pfcache->set($non_featured_key, $non_featured_code, 3600);
        //$pfcache->set($non_featured_key . '_actions', $non_featured_actions, 3600);



    }



    //if(!isset($_SESSION['user_id']) || 1==1) {
    if ($non_featured_actions != null && is_array($non_featured_actions)) {

        if(!isset($cached_actions ['update_advert_views']['sel'])) {
            $cached_actions ['update_advert_views']['sel'] = array();
        }
        $cached_actions ['update_advert_views']['sel'] = array_merge($cached_actions ['update_advert_views']['sel'], $non_featured_actions['adverts']);
        $cached_actions ['update_advert_views']['sel_catdom_id'] = $catdom_id_adv;
        /*// Update Adverts Count
        $nf_adv_ids = implode(", ", $non_featured_actions['adverts']);
        $nf_adv_update = "UPDATE advertisment SET views=views+1 WHERE advertisment_id IN '$nf_adv_ids';";
        $nf_r_update = mysql_query($nf_adv_update);

        // Insert Adverts Stats Views
        $nf_adv_tmp = array();
        foreach ($non_featured_actions['adverts'] as $nf_adv_id) {
            $nf_adv_tmp [] = "('$nf_adv_id', '$domain_id', NOW(), '$ipfrom', 1, 'top' )";
        }
        $nf_adv_tmp_str = implode(", ", $nf_adv_tmp);
        $nf_adv_count_views = "INSERT INTO adverts_stats_views (advertisment_id, domain_id, added_on, ipfrom, views, view_from) VALUES $nf_adv_tmp_str;";
        $nf_r_count_views = mysql_query($nf_adv_count_views);*/
    }


    //}

    echo $non_featured_code;

}

echo '</div>'; /*End the <div class=lbs*/


$nd = microtime(true);
if(isset($_REQUEST['finished'])) echo '<br>Finished in ' . ($nd-$st);


// Add shuffle.js
$optres['js'][] = $path . "assets/js/jquery.matchHeight-min.js";
$optres['js'][] = $path . "amodules/adverts/js/shuffle_adverts.v5.js";


if(isset($_SESSION['user_id'])) {
    $optres['js'][] = $path . "amodules/adverts/js/adverts_o.js";
}