<?php

function get_game($cate_id = 0, $top_num = 10, $is_best = false, $field = 'ctime', $order = 'desc') {
	global $DB;
	
	$where = "a.status=3 AND c.cate_mod='game'";
	if (!in_array($field, array('views', 'ctime'))) $field = 'ctime';
	if ($cate_id > 0) {
		$cate = get_one_category($cate_id);
		if (!empty($cate)) $where .= " AND a.cate_id IN ('".$cate['cate_arrchildid']."')";
	}
	if ($is_best == true) $where .= " AND a.isbest=1";
	switch ($field) {
		case 'views' :
			$sortby = "a.views";
			break;
		case 'ctime' :
			$sortby = "a.ctime";
			break;
		default :
			$sortby = "a.ctime";
			break;
	}
	$order = strtoupper($order);
	
	$sql = "SELECT a.id, a.title,a.cover,a.ishot,a.isbest,a.url,a.status, a.ctime, c.cate_id, c.cate_mod, c.cate_name, c.cate_dir FROM ".$DB->table('games')." a LEFT JOIN ".$DB->table('categories')." c ON a.cate_id=c.cate_id WHERE $where ORDER BY $sortby $order LIMIT $top_num";
	$query = $DB->query($sql);
	$results = array();
	while ($row = $DB->fetch_array($query)) {
		$row['ctime'] = date('Y-m-d', $row['ctime']);
		$row['utime'] = date('Y-m-d', $row['utime']);
		$row['cate_link'] = get_category_url($row['cate_mod'], $row['cate_id']);
		$results[] = $row;
	}
	unset($row);
	$DB->free_result($query);
	
	return $results;
}

/** game list */
function get_game_list($where = '', $field = 'ctime', $order = 'DESC', $start = 0, $pagesize = 10) {
	global $DB;
	
	if(!empty($where)){
       $where =" WHERE $where";
	}
	if (!in_array($field, array('views', 'ctime'))) $field = 'ctime';
	switch ($field) {
		case 'views' :
			$sortby = "a.views";
			break;
		case 'ctime' :
			$sortby = "a.ctime";
			break;
		default :
			$sortby = "a.ctime";
			break;
	}
	$order = strtoupper($order);
	$sql = "SELECT a.id, a.title,a.cover,a.ishot,a.isbest,a.url,a.status, a.ctime, c.cate_id, c.cate_name FROM ".$DB->table('games')." a LEFT JOIN ".$DB->table('categories')." c ON a.cate_id=c.cate_id  $where ORDER BY a.istop DESC, $sortby $order LIMIT $start, $pagesize";
	$query = $DB->query($sql);
	$results = array();
	while ($row = $DB->fetch_array($query)) {
		switch ($row['status']) {
			case 1 :
				$status = '<font color="#333333">草稿</font>';
				break;
			case 2 :
				$status = '<font color="#ff3300">待审核</font>';
				break;
			case 3 :
				$status = '<font color="#008800">已审核</font>';
				break;
		}
		$row['attr'] = $status;
		$row['ctime'] =date('Y-m-d',$row['ctime']);
		$row['utime'] = isset($row['utime'])?date('Y-m-d', $row['utime']):'';
		$results[] = $row;
	}
	unset($row);
	$DB->free_result($query);
		
	return $results;
}

/** one article */
function get_one_game($where = 1) {
	global $DB;
	
	$row = $DB->fetch_one("SELECT  a.id, a.title,a.cover,a.ishot,a.isbest,a.url,a.status, a.ctime, c.cate_id, c.cate_name FROM ".$DB->table('games')." a LEFT JOIN ".$DB->table('categories')." c ON a.cate_id=c.cate_id WHERE $where LIMIT 1");
	
	return $row;
}