<?php
defined('_VALID') or die('Restricted Access!');

require $config['BASE_DIR']. '/classes/filter.class.php';
require $config['BASE_DIR']. '/include/adodb/adodb.inc.php';
require $config['BASE_DIR']. '/classes/pagination.class.php';
require $config['BASE_DIR']. '/include/compat/json.php';
require $config['BASE_DIR']. '/include/dbconn.php';

disableRegisterGlobals();

function clean( $string )
{
    $string = ereg_replace('[^ 0-9a-zA-Z]', ' ', $string);
    $string = preg_replace('/\s\s+/', ' ', $string);
    $string = trim($string);
    $string = str_replace(' ', '-', $string);
    
    return strtolower($string);
}

function truncate( $string, $length=80)
{
    if ( $length == 0 ) {
        return '';
    }
    
    if (strlen($string) > $length) {
        $etc     = ' ...';
        $length -= min($length, strlen($etc));
        return substr($string, 0, $length) . $etc;
    } else {
        return $string;
    }
}

function time_range( $time )
{
    $range          = NULL;
    $current_time   = time();
    $interval       = $current_time-$time;
    if ( $interval > 0 ) {
        $day    = $interval/(60*60*24);
        if ( $day >= 1 ) {
            $word       = ( $range == 1 ) ? ' day' : ' days';
            $range      = floor($day) . $word;
            $interval   = $interval-(60*60*24*floor($day));
        }
        if( $interval > 0 && $range == '' ) {
            $hour       = $interval/(60*60);
            if ( $hour >=1 ) {
                $range      = floor($hour). ' hours';
                $interval   = $interval-(60*60*floor($hour));
            }
        }
        if ( $interval > 0 && $range == '' ) {
            $min        = $interval/(60);
            if ( $min >= 1 ) {
                $range=floor($min). ' minutes';
                $interval=$interval-(60*floor($min));
            }
        }
        if ( $interval > 0 && $range == '' ) {
            $scn        = $interval;
            if ( $scn >= 1 ) {
                $range  = $scn. ' seconds';
            }
        }
        return ( $range != '' ) ? $range. ' ago' : 'just now';                                                                                                                                                                                                                                                                                           
    }
}

function video_rating_small( $rate )
{
    $class_1    = '';
    $class_2    = '';
    $class_3    = '';
    $class_4    = '';
    $class_5    = '';
    if ( $rate > 0.5 ) {
        $class_1 = ' class="half"';
        if ( $rate >= 1 ) {
            $class_1 = ' class="full"';
        }
        if ( $rate >= 2 ) {
            $class_2 = ' class="full"';
        } elseif ( $rate >= 1.5 ) {
            $class_2 = ' class="half"';
        }
        if ( $rate >= 3 ) {
            $class_3 = ' class="full"';
        } elseif ( $rate >= 2.5 ) {
            $class_3 = ' class="half"';
        }
        if ( $rate >= 4 ) {
            $class_4 = ' class="full"';
        } elseif ( $rate >= 3.5 ) {
            $class_4 = ' class="half"';
        }
        if ( $rate >= 5 ) {
            $class_5 = ' class="full"';
        } elseif ( $rate >= 4.5 ) {
            $class_5 = ' class="half"';
        }                                                                                                                                                                                                                                        
    } 
    
    $output     = array();
    $output[]   = '<ul class="rating_small">';
    $output[]   = '<li><span' .$class_5. '>&nbsp;</span></li>';
    $output[]   = '<li><span' .$class_4. '>&nbsp;</span></li>';
    $output[]   = '<li><span' .$class_3. '>&nbsp;</span></li>';
    $output[]   = '<li><span' .$class_2. '>&nbsp;</span></li>';
    $output[]   = '<li><span' .$class_1. '>&nbsp;</span></li>';
    $output[]   = '</ul>';
    
    return implode("\n", $output);                                                           
}                                                                            

$data   = array('status' => 0, 'games' => '', 'page' => 0, 'pages' => 0);
if ( isset($_POST['game_id']) && isset($_POST['move']) && isset($_POST['page']) ) {
    $filter         = new VFilter();
    $gid            = $filter->get('game_id', 'INTEGER');
    $page           = $filter->get('page', 'INTEGER');
    $move           = ( $_POST['move'] == 'next' ) ? 'next' : 'prev';
    if ( $move == 'prev' ) {
        $page   = ( $page < 1 ) ? 1 : $page-1;
    } else {
        $page   = $page+1;
    }
    
    $sql            = "SELECT title, category, tags FROM game WHERE GID = " .$gid. " LIMIT 1";
    $rs             = $conn->execute($sql);
    $game           = $rs->getrows();
    $game           = $game['0'];
    
    $sql_add        = NULL;
    if ( $game['tags'] ) {
        $keywords   = explode(' ', $game['tags']);
        $sql_add   .= " OR (";
        $sql_or     = NULL;
        foreach ( $keywords as $keyword ) {
            $sql_add .= $sql_or. " tags LIKE '%" .mysql_real_escape_string($keyword). "%'";
            $sql_or   = " OR ";
        }
        $sql_add   .= ")";
    }
    
	$type			= ($config['show_private_games'] == '1') ? '' : " AND type = 'public'";
    $sql            = "SELECT COUNT(GID) AS total_games FROM game WHERE status = '1' AND category = '" .$game['category']. "'" .$type. " AND GID != " .$gid. "
					   AND status = '1' AND ( title LIKE '%" .mysql_real_escape_string($game['title']). "%' " .$sql_add. ")";
    $rs             = $conn->execute($sql);
    $total          = $rs->fields['total_games'];
    $total          = ( $total > 100 ) ? 100 : $total;
    $pagination     = new Pagination(10, $page);
    $limit          = $pagination->getLimit($total);
    $sql            = "SELECT GID, title, addtime, rate, total_plays FROM game 
                       WHERE status = '1' AND category = '" .intval($game['category']). "'" .$type. " AND GID != " .$gid. "
                       AND ( title LIKE '%" .mysql_real_escape_string($game['title']). "%' " .$sql_add. ") 
                       ORDER BY addtime DESC LIMIT " .$limit;
    $rs             = $conn->execute($sql);
    $games          = $rs->getrows();
    $code           = array();
    $total_pages    = $pagination->getTotalPages();
    $page           = ( $page >= $total_pages ) ? $total_pages : $page;
	$private_img	= '<img alt="" style="position: absolute; left: 0px; top: +0px; width: 160px; height: 120px;" src="'.$config['BASE_URL'].'/templates/frontend/' .$config['template']. '/images/private-game.png" />';
    foreach ( $games as $game ) {
        $code[]     = '<div class="video_box_related">';
        $code[]     = '<a href="' .$config['BASE_URL']. '/game/' .$game['GID']. '/' .clean($game['title']). '">';
        $code[]     = '<span class="font-13 font-bold">' .htmlspecialchars(truncate($game['title'], 20), ENT_QUOTES, 'UTF-8'). '</span><br />';
        $code[]     = '<img src="' .$config['BASE_URL']. '/media/games/tmb/' .$game['GID']. '.jpg" title="' .htmlspecialchars($game['title'], ENT_QUOTES, 'UTF-8'). '" alt="' .htmlspecialchars($game['title'], ENT_QUOTES, 'UTF-8'). '" width="160" height="120" /><br />';
		if ($game['type'] = 'private') {
			$code[] = $private_img;
		}
        $code[]     = '</a>';
        $code[]     = '<div class="vbox_rel_left">';
        $code[]     = time_range($game['addtime']);
        $code[]     = '</div>';
        $code[]     = '<div class="vbox_rel_right">';
        $code[]     = video_rating_small($game['rate']);
        $code[]     = '<div class="clear_right"></div>';
        $code[]     = $game['total_plays']. ' plays';
        $code[]     = '</div>';
        $code[]     = '<div class="clear"></div>';
        $code[]     = '</div>';
    }
    
    $data['page']   = $page;
    $data['status'] = ( $total_pages > 1 ) ? 1 : 0;
    $data['games']  = implode("\n", $code);
    $data['pages']  = $total_pages;
}

echo json_encode($data);
die();
?>
