<?php

$coordinates = '';

if(isset($hotel_district) && trim($hotel_district) != "") {
	$coordinates = 'district';
}
elseif (isset($nearby_hotels_query) && $nearby_hotels_query != "") {
	$coordinates = 'nearby';
}

if($coordinates != '') {
	ob_start();
	
	$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")));
	
	$is_admin =  (isset($_SESSION['user_id'])) ? 1 : 0;
	
	//echo '<pre>', var_export($_POST, true), '</pre>';

	if($coordinates == 'district') {
		$vhotels = array();
		if(isset($adv_code) && $adv_code != "") $vhotels [] = $adv_code; 
		
		$domain_categs = array();
		$q = "select * from domaincategories where parent_id='0' and domainname like '%$ultra_domainname';";
		$r = @mysql_query($q);
		if($r && mysql_num_rows($r) == 1) {
			$line_domain = mysql_fetch_assoc($r);
			$domain_id = $line_domain['catdom_id'];
			$domain_categs [] = $domain_id;
			
			$qs = "select * from domaincategories where parent_id='$domain_id';";
			$rs = @mysql_query($qs);
			if($rs && mysql_num_rows($rs) > 0) {
				while($s_domain = mysql_fetch_assoc($rs)){
					$domain_categs [] = $s_domain['catdom_id'];
				}
			}
			
			$domain_categs_str = implode(', ', $domain_categs);
		}
		
		$query_categtop = "
		SELECT a.*, d.*
		FROM 
			advertisment a,
			domain_advertisment d, 
			advertisment_locations l,
			wb_categories_adverts w
		WHERE
			a.adv_code=w.wb_advert_uid
			and w.wb_uid='$wb_uid'
			and w.wb_status='1'
			and a.adv_code=l.adv_code
			AND l.dcode='$hotel_district'
			AND l.main_location='1'
			AND a.advertisment_id = d.advertisment_id
			AND d.catdom_id IN ($domain_categs_str)
			AND d.category_top='yes' 
			AND a.active='yes' 
			AND d.advertisment_id=a.advertisment_id
		GROUP BY
			a.adv_code
		ORDER BY 
			d.category_top_order_seq ASC
		";
	}
	
	if($coordinates == 'nearby') {
		$vhotels = array();
		$nearby_adv_codes = array();
		$r = @mysql_query($nearby_hotels_query);
		if($r && mysql_num_rows($r) > 0) {
			while ($row = mysql_fetch_assoc($r)) {
				$nearby_adv_codes [] = $row['adv_code'];
			}
		}
		
		if(count($nearby_adv_codes) > 0) {
			$query_categtop = "SELECT a.* FROM advertisment a where a.adv_code IN ('".implode("','", $nearby_adv_codes)."');";
			if(isset($_REQUEST['nearby'])) echo $query_adverts;
			$result_adverts = @mysql_query($query_categtop);
			if (!$result_adverts || mysql_num_rows($result_adverts) <= 0){
				$coordinates = '';
			}
			
		}
	}
	
	//print_r($domain_categs);
	
	$root_host = $_SERVER['HTTP_HOST'];
	if(str_replace('www.', '', $root_host) != str_replace('www.', '', $ultra_domainname)) {
		$root_host .= "/$ultra_addonname";
		
		require_once(dirname(__FILE__) . "/../../ageneral/functions.php");
		require_once(dirname(__FILE__) . "/../../ageneral/microdata_pool.php");
	}
	else {
		require_once(dirname(__FILE__) . "/../../functions.php");
		require_once(dirname(__FILE__) . "/../../microdata_pool.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"
	);
	
	$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;
	$have_microdata = true;
	
	
	
	//echo $query_categtop;
	
	//AND a.catdom_id LIKE '%$domain_idx2%' 
	
	$result_categtop = mysql_query ($query_categtop) or die(mysql_error());
	if (mysql_num_rows($result_categtop) > 0){
		$have_featured = "yes";
		?>
		<div class="nhotels-grid">
		    <div class="nhotel-grid-sizer"></div>
			<?php
			$count_categtop = 1;
			while($line_categtop = mysql_fetch_assoc($result_categtop)){
				
				if(!in_array($line_categtop['adv_code'], $vhotels)) {
					$vhotels[] = $line_categtop['adv_code'];
				}
				else {
					continue;
				}
				
				$has_thumbshot = false;
				$qth = "select * from advertisment_gallery where adv_code='{$line_categtop['adv_code']}' order by pos asc;";
				$rth = @mysql_query($qth);
				if($rth && mysql_num_rows($rth) >0) {
					while ($rowth = mysql_fetch_assoc($rth)) {
						$th_file_path = $_SERVER['DOCUMENT_ROOT'] . '/images/advertisments/gallery/' . $line_categtop['advertisment_id'] . '/thumbs/' . $rowth['filename'];
						$th_file_url = $path . 'images/advertisments/gallery/' . $line_categtop['advertisment_id'] . '/thumbs/' . $rowth['filename'];
						
						if(file_exists($th_file_path)) {
							$has_thumbshot = true;
							break;
						}
					}
				}
				
				if($has_thumbshot) {
					/**************** TRY TO GET PRICES ********************************************************/
					$th_min_price = 0;
					$qaff = "select a.* from hotel_affiliates_adverts a, hotel_affiliates h where a.aff_code=h.aff_code and a.aff_hotel_status='1' and a.adv_code='{$line_categtop['adv_code']}' and h.aff_status='1';";
					$raff = @mysql_query($qaff);
					if($raff && mysql_num_rows($raff) > 0) {
						while ($rowaff = mysql_fetch_assoc($raff)) {
							if(floatval($rowaff['low_rate']) > 1) {
								if($th_min_price == 0) $th_min_price = floor(floatval($rowaff['low_rate']));
								elseif (floor(floatval($rowaff['low_rate'])) < $th_min_price) $th_min_price = floor(floatval($rowaff['low_rate']));
							}
						}
					}
					/************END - TRY TO GET PRICES ********************************************************/
					
					
					/*************** TRY TO GET STARS **********************************************************/
					// Get the fm_uid
					$q = "select f.*, d.title as category_title from wb_filters_adverts_categs f, wb_filters_mains d  where f.wb_uid='$wb_uid' and f.adv_code='{$line_categtop['adv_code']}' and f.fm_uid=d.fm_uid;";
					$r = @mysql_query($q);
					if($r && mysql_num_rows($r) == 1) {
						$row = mysql_fetch_assoc($r);
						$fm_uid = trim($row['fm_uid']);
						$fm_title = stripslashes($row['category_title']);
					}
					
					if(isset($fm_uid) && $fm_uid != "") {
						// Get the class rating
						$class_vars_classes = array(
							"star_rating" 	=> "rate", 
							"apt_class"		=> "class", 
							"class"			=> "class"
						);
						
						$rating = array(
							'class'			=> '',
							'var'			=> '',
							'uid'			=> '',
							'db'			=> array(),
							'value'			=> '',
							'text'			=> '',
							'display'		=> 1
						);
					
						$q = "select * from wb_filters_elems where wb_uid='$wb_uid' and fm_uid='$fm_uid' order by fc_uid asc, pos asc;";
						$r = @mysql_query($q);
						if($r && mysql_num_rows($r) > 0) {
							while ($row = mysql_fetch_assoc($r)) {
								if(in_array($row['e_name'], array_keys($class_vars_classes))) {
									$rating['var'] = $row['e_name'];
									$rating['class'] = $class_vars_classes[$row['e_name']];
									$rating['uid'] = $row['fe_uid'];
									$rating['db'] = unserialize(base64_decode($row['e_db']));
									break;
								}
							}
						}
						
						
						$star_rating = '';
						$q = "select * from wb_filters_adverts where wb_uid='$wb_uid' and fm_uid='$fm_uid' and adv_code='{$line_categtop['adv_code']}';";
						$r = @mysql_query($q);
						if($r && mysql_num_rows($r) > 0) {
							while ($row = mysql_fetch_assoc($r)) {
								$f_value = stripslashes(trim($row['f_value']));
								
								//echo '<pre>' . var_export($row, true), '</pre>';
								
								if($row['fe_uid'] == $rating['uid']) {
									if($rating['var'] == 'star_rating') {
										$star_rating = 0;
										$star_cnt = 5;
										foreach ($rating['db'] as $r_value=>$r_text) {
											if($f_value == $r_value) {
												$star_rating = $star_cnt;
												$rating['text'] = stripslashes($r_text);
											}
											$star_cnt--;
										}
										
										$rating['class'] .= '-' . $star_rating;
										$rating['display'] = 0;
									}
									else {
										foreach ($rating['db'] as $r_value=>$r_text) {
											if($f_value == $r_value) {
												$rating['text'] = stripslashes($r_text);
											}
										}
									}
									
									break;
								}
								
								
							}
						}
						
					}
					/*************************************************************************************/
					
					//Theodosis modification
					$display_name = str_replace('"','',$line_categtop["short_title_en"]);
					$shortNameURL = $line_categtop["title_tr"];
					$shortNameALT = str_replace('"','',$line_categtop["short_title_en"]);
					
					$website = trim($line_categtop['website']);
					$w_protocol = "http://";
					if(strpos($website, "https://") !== false) $w_protocol = "https://";
					$website = str_replace("$w_protocol", "", $website);
					if($website != "") {
						$website = $w_protocol . $website;
					}
					
					
					
					
					?>
					<div class="nhotel_unit">
					    <div class="nhotel-unit-content">
                            <?php
                            if($th_min_price > 0) {
                                ?>
                                <div class="vhotels-rates">
                                    <a href="<?php echo $protocol . $microdata_host . '/' .  $shortNameURL;?>" class="vaff_rate_price" target="_blank">
                                    From <span class="vaff_rate"><?php echo '&euro; ' . number_format($th_min_price, 0);?></span>
                                    </a>
                                </div>
                                <?php
                            }
                            else {
                                ?>
                                <div class="vhotels-rates">
                                    <a href="<?php echo $protocol . $microdata_host . '/' .  $shortNameURL;?>" class="vaff_rate_find" target="_blank">
                                    Check Availability
                                    </a>
                                </div>
                                <?php
                            }

                            if (!isset($_SESSION['user_id']) && $is_admin == 0){
                                //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');

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

                            }
                            // top = category top
                            ?>
                            <a href="<?php echo $protocol.$microdata_host . '/' . $shortNameURL; ?>" target="_blank" class="vhotel-link">
                                <img src="<?php echo $th_file_url;?>" width="120" height="90" border="0" alt=""/>
                                <?php echo $shortNameALT; ?>
                            </a>

                            <?php
                            if(isset($rating) && $rating['uid'] != '') {

                                if($rating['var'] == 'star_rating') {
                                    echo '<span class="vh_business_rating vh_stars_rating_bk">';
                                    echo '<span class="vh_business_', $rating['var'] ,' ', $rating['class'], '" title="'.$rating['text'].'">', (intval($rating['display']) == 1) ? $rating['text'] : '', '</span>';
                                    echo '</span>';
                                }
                                else {
                                    echo '<span  class="vh_business_rating vh_business_', $rating['var'] ,' ', $rating['class'], '" title="'.$rating['text'].'">', (intval($rating['display']) == 1) ? $rating['text'] : '';
                                    echo '</span>';
                                }
                            }


                            if ( ((isset($_SESSION['user_id']) || $is_admin == 1)) && 1==2){
                                ?>
                                <div class="advert_sv">
                                    <?php
                                    $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&advertisment_id=',$line_categtop['advertisment_id'],'" target="_blank">Edit</a>';
                                    ?>
                                    <div style="margin: 3px 0px;clear:both;">
                                    <?php
                                    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 != "") {
                                            $inv_details = "Invoice Note ::: &raquo; " . $inv_details;
                                            ?>
                                            <a href="javascript:;" class="tooltip_views" rel="<?php echo $inv_details;?>"><img src="/images/class_info_red.gif" border="0" align="middle"/></a>
                                            <?php
                                        }

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

                                    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>';
                                    }
                                    ?>
                                    </div>
                                </div>
                                <?php
                            }


                            ?>
                        </div>
					</div>
					<?php
					
				}
				
			}
		?>
		</div>
		<?php 
	}
	
	$vhotels_content = ob_get_contents();
	ob_end_clean();
	
	if($vhotels_content != "") {
        echo '<div class="box box-danger">';
        if(isset($module_vhots_title) && trim($module_vhots_title) != "") {
            ?>
            <div class="box-header with-border">
                <b><?php echo $module_vhots_title;?></b>
            </div>
            <?php
        }
        echo $vhotels_content;
        echo '</div>';




        $optres['js'][] = $path . 'assets/js/masonry.pkgd.min.js';
        $optres['css'][] = $module_css_path . 'amodules/nearby_hotels/css/nearby_hotels_inline_catdom.css';
        $optres['js'][] = $path . 'amodules/nearby_hotels/js/nearby_hotels_inline_catdom.js';
	}
	
	//echo print_r($vhotels);
}
?>