<?php
// +----------------------------------------------------------------------
// | mobanbox [ Beautiful Digital Content Trading System ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://mobanbox.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Email author@mobanbox.net
// +----------------------------------------------------------------------

_setView(__FILE__);
_setTitle($langArray['author_dashboard']);	

if(!check_login_bool()) {
		$_SESSION['temp']['golink'] = '/'.$languageURL.'author_dashboard/';
		refresh('/'.$languageURL.'sign_in/');
}

	if($_SESSION['user']['quiz'] != 'true') {
		refresh('/'.$languageURL.'make_money/become_an_author/');
	} 	

	require_once ROOT_PATH.'/apps/items/models/orders.class.php';
	$ordersClass = new orders();
	
	$weekStats = $ordersClass->getWeekStats();
	abr('weekStats', $weekStats);




$usersClass = new users();

if(check_login_bool() && $_SESSION['user']['user_id'] != $users['user_id']) {
	$users['is_follow'] = $usersClass->isFollow($users['user_id']);
}

$users['profile_desc'] = replaceEmoticons($users['profile_desc']);

abr('user', $users);

abr('checkItemsType', 'yes');

if(check_login_bool() && ($username == '' || $username == $_SESSION['user']['username'])) {
	$username = $_SESSION['user']['username'];
	$whereQuery = " AND (`status` = 'active' OR `status` = 'unapproved' ) ";
}
else {
	$whereQuery = " AND `status` = 'active' ";
}
$user = $usersClass->getByUsername($username);
if(!is_array($user)) {
	header("HTTP/1.0 404 Not Found");
	header("Location: http://". DOMAIN ."/".$languageURL."error");
}
abr('user', $user);


$userss = $usersClass->getAll(0, 0, $itemsClass->usersWhere);
abr('userss', $userss);


//勋章
require_once ROOT_PATH.'/apps/system/models/badges.class.php';
$badges = new badges();

$badges_data = $badges->getAllFront();

$user = $_SESSION['user'];

$other_badges = array_map('trim', explode(',', $user['badges']));

$user_badges = array();

if($user['exclusive_author'] == 'true' && isset($badges_data['system']['is_exclusive_author'])) {
	if($badges_data['system']['is_exclusive_author']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $badges_data['system']['is_exclusive_author']['photo'])) {
		$user_badges[] = array(
			'name' => $badges_data['system']['is_exclusive_author']['name'],
			'photo' => '/uploads/badges/' . $badges_data['system']['is_exclusive_author']['photo']
		);
	}
}

if($user['featured_author'] == 'true' && isset($badges_data['system']['has_been_featured'])) {
	if($badges_data['system']['has_been_featured']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $badges_data['system']['has_been_featured']['photo'])) {
		$user_badges[] = array(
			'name' => $badges_data['system']['has_been_featured']['name'],
			'photo' => '/uploads/badges/' . $badges_data['system']['has_been_featured']['photo']
		);
	}
}

if(isset($user['statuses']['freefile']) && $user['statuses']['freefile'] && isset($badges_data['system']['has_free_file_month'])) {
	if($badges_data['system']['has_free_file_month']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $badges_data['system']['has_free_file_month']['photo'])) {
		$user_badges[] = array(
			'name' => $badges_data['system']['has_free_file_month']['name'],
			'photo' => '/uploads/badges/' . $badges_data['system']['has_free_file_month']['photo']
		);
	}
}

if(isset($user['statuses']['featured']) && $user['statuses']['featured'] && isset($badges_data['system']['has_had_item_featured'])) {
	if($badges_data['system']['has_free_file_month']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $badges_data['system']['has_had_item_featured']['photo'])) {
		$user_badges[] = array(
			'name' => $badges_data['system']['has_had_item_featured']['name'],
			'photo' => '/uploads/badges/' . $badges_data['system']['has_had_item_featured']['photo']
		);
	}
}

if($user['buy'] && isset($badges_data['buyers']) && is_array($badges_data['buyers'])) {
	foreach($badges_data['buyers'] AS $k => $v) {
		list($from, $to) = explode('-', $k);
		if($from <= $user['buy'] && $to >= $user['buy']) {
			if($v['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $v['photo'])) {
				$user_badges[] = array(
					'name' => $v['name'],
					'photo' => '/uploads/badges/' . $v['photo']
				);
			}
			break;
		}
	}
}

if($user['sold'] && isset($badges_data['authors']) && is_array($badges_data['authors'])) {
	foreach($badges_data['authors'] AS $k => $v) {
		list($from, $to) = explode('-', $k);
		if($from <= $user['sold'] && $to >= $user['sold']) {
			if($v['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $v['photo'])) {
				$user_badges[] = array(
					'name' => $v['name'],
					'photo' => '/uploads/badges/' . $v['photo']
				);
			}
			break;
		}
	}
}

if($user['referals'] && isset($badges_data['referrals']) && is_array($badges_data['referrals'])) {
	foreach($badges_data['referrals'] AS $k => $v) {
		list($from, $to) = explode('-', $k);
		if($from <= $user['referals'] && $to >= $user['referals']) {
			if($v['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $v['photo'])) {
				$user_badges[] = array(
					'name' => $v['name'],
					'photo' => '/uploads/badges/' . $v['photo']
				);
			}
			break;
		}
	}
}

if(isset($badges_data['other']) && is_array($badges_data['other'])) {
	foreach($badges_data['other'] AS $k => $b) {
		if(in_array($k, $other_badges) && $b['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $b['photo'])) {
			$user_badges[] = array(
				'name' => $b['name'],
				'photo' => '/uploads/badges/' . $b['photo']
			);
		}
	}
}

if(isset($user['country']['photo']) && $user['country']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/countries/" . $user['country']['photo'])) {
	$user_badges[] = array(
		'name' => $user['country']['name'],
		'photo' => '/uploads/countries/' . $user['country']['photo']
	);
} elseif(isset($badges_data['system']['location_global_community']) && $badges_data['system']['location_global_community']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $badges_data['system']['location_global_community']['photo'])) {
	$user_badges[] = array(
		'name' => $badges_data['system']['location_global_community']['name'],
		'photo' => '/uploads/badges/' . $badges_data['system']['location_global_community']['photo']
	);
}

if($user['power_elite_author'] == 'true' && isset($badges_data['system']['power_elite_author'])) {
	if($badges_data['system']['power_elite_author']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $badges_data['system']['has_been_featured']['photo'])) {
		$user_badges[] = array(
			'name' => $badges_data['system']['power_elite_author']['name'],
			'photo' => '/uploads/badges/' . $badges_data['system']['power_elite_author']['photo']
		);
	}
}

if($user['elite_author'] == 'true' && isset($badges_data['system']['elite_author'])) {
	if($badges_data['system']['elite_author']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $badges_data['system']['has_been_featured']['photo'])) {
		$user_badges[] = array(
			'name' => $badges_data['system']['elite_author']['name'],
			'photo' => '/uploads/badges/' . $badges_data['system']['elite_author']['photo']
		);
	}
}

abr('user_badges', $user_badges);


#获取粉丝
$follow['to'] = $usersClass->getFollowers($user['user_id'], 0, 9, 'RAND()', true);
$follow['to_count'] = $usersClass->foundRows;
$follow['from'] = $usersClass->getFollowers($user['user_id'], 0, 9, 'RAND()');
$follow['from_count'] = $usersClass->foundRows;
abr('follow', $follow);


$follow['toto'] = $usersClass->getFollowers($user['user_id'], 0, 10000000, 'RAND()', true);
$follow['toto_count'] = $usersClass->foundRows;
$follow['fromfrom'] = $usersClass->getFollowers($user['user_id'], 0, 10000000, 'RAND()');
$follow['fromfrom_count'] = $usersClass->foundRows;
abr('follow', $follow);

#最新评论
	require_once ROOT_PATH.'/apps/items/models/comments.class.php';
	$commentsClass = new comments();
	
	$comments = $commentsClass->getAll(0, 100, " `owner_id` = '".intval($_SESSION['user']['user_id'])."' AND `reply_to` = '0' ", true, '`datetime` DESC');
	if(is_array($comments)) {
		$usersClass = new users();
		
		$users = $usersClass->getAll(0, 0, $commentsClass->usersWhere);
		abr('users', $users);		
	}
	abr('comments', $comments);
	

    require_once ROOT_PATH.'/apps/items/models/orders.class.php';
	$ordersClass = new orders();
	
	if(isset($_POST['ajax'])) {
		
		$month = get_id(2);
		$year = get_id(3);
		
		$text = '';
		$sales = $ordersClass->getAll(" `paid_datetime` > '".date('Y-m-d 23:59:59', mktime(0, 0, 0, ($month-1), date('t', mktime(0, 0, 0, ($month-1), 1, $year)), $year))."' AND `paid_datetime` < '".date('Y-m-d 00:00:00', mktime(0, 0, 0, ($month+1), 1, $year))."' AND `paid` = 'true' AND `type` = 'buy' AND `owner_id` = '".intval($_SESSION['user']['user_id'])."' ", "`paid_datetime` ASC");
		if(is_array($sales)) {
			$buff = array();
			foreach($sales as $s) {
				$day = explode(' ', $s['paid_datetime']);
				$day = explode('-', $day[0]);

				if(!isset($buff[$day[2]])) {
					$buff[$day[2]]['sale'] = 1;
					$buff[$day[2]]['earning'] = $s['receive'];
				}
				else {
					$buff[$day[2]]['sale']++;
					$buff[$day[2]]['earning'] += $s['receive'];
				}
			}
			
			foreach($buff as $day=>$r) {
				$text .= '<tr><td>'.$day.'</td><td>'.$r['sale'].' '.$langArray['sales'].'</td><td>$'.number_format($r['earning'], 2).'</td></tr>';
			}
		}
		
		die('
			jQuery("#month_'.$month.'_'.$year.'_details").html(\''.$text.'\');
			jQuery("#month_'.$month.'_'.$year.'_show").hide();
			jQuery("#month_'.$month.'_'.$year.'_hide").show(); 
		');
	}

	$usersClass = new users();
	
	$user = $usersClass->get($_SESSION['user']['user_id']);
	abr('user', $user);


#加载作品
require_once ROOT_PATH.'/apps/items/models/items.class.php';
$itemsClass = new items();

$limit = 8;
$start = (PAGE-1)*$limit;

$items = $itemsClass->getAll($start, $limit, " `user_id` = '".intval($user['user_id'])."' ".$whereQuery);
abr('items', $items);

abr('paging', paging('/'.$languageURL.'user/'.$username.'/?p=', '&sort_by='.$_GET['sort_by'].'&order='.$_GET['order'], PAGE, $limit, $itemsClass->foundRows));
$allRows = $itemsClass->foundRows;
abr('allRows',$allRows);

#获取百分比
	require_once ROOT_PATH.'/apps/percents/models/percents.class.php';
	$percentsClass = new percents();
	
	$percent = $percentsClass->getPercentRow($user);
	if($percent['to'] == '0') {
		$percent['more'] = '-';
	}
	else {
		$percent['more'] = floatval($percent['to']) - floatval($user['sold']);
	}
	abr('percent', $percent);
	
	$earnings = array(
		'sales' => 0,
		'sales_earning' => 0,
		'referal' => 0,
		'total' => 0
	);	
	
	$maxSales = 0;
	
	$earningArr = false;
	
#获取销售金额
	$sales = $ordersClass->getAll(" `paid` = 'true' AND `type` = 'buy' AND `owner_id` = '".intval($user['user_id'])."' ", "`paid_datetime` ASC");
	if(is_array($sales)) {
		$buff = array();
		foreach($sales as $r) {
			
			$date = explode(' ', $r['paid_datetime']);
			$date = explode('-', $date[0]);
			
			if(isset($buff[$date[0]][$date[1]]['buy'])) {
				$buff[$date[0]][$date[1]]['buy']++;
			}
			else {
				$buff[$date[0]][$date[1]]['buy'] = 1;
			}
			
			if(isset($buff[$date[0]][$date[1]]['total'])) {
				$buff[$date[0]][$date[1]]['total'] += $r['receive'];
			}
			else {
				$buff[$date[0]][$date[1]]['total'] = $r['receive'];
			}
			
			if(isset($earningArr[$date[0]][$date[1]])) {
				$earningArr[$date[0]][$date[1]] += $r['receive'];
			}
			else {
				$earningArr[$date[0]][$date[1]] = $r['receive'];
			}
			
			if($buff[$date[0]][$date[1]]['buy'] > $maxSales) {
				$maxSales = $buff[$date[0]][$date[1]]['buy'];
			}
			
			$earnings['sales']++;
			$earnings['sales_earning'] += $r['receive'];
			$earnings['total'] += $r['receive'];
			
		}
		unset($sales);
		$sales = $buff;
		unset($buff);
	}	
	abr('sales', $sales);
	
	if($maxSales > 0) {
		$saleIndex = 300 / floatval($maxSales);		
	}
	else {
		$saleIndex = 0;
	}
	abr('saleIndex', $saleIndex);
	
#获取推广金额
	$referals = $ordersClass->getAll(" `paid` = 'true' AND `type` = 'referal' AND `owner_id` = '".intval($user['user_id'])."' ", "`paid_datetime` ASC");
	if(is_array($referals)) {
		$buff = array();
		foreach($referals as $r) {
			
			$date = explode(' ', $r['paid_datetime']);
			$date = explode('-', $date[0]);
			
			if($r['item_id'] == '0') {
				if(isset($buff[$date[0]][$date[1]]['deposit'])) {
					$buff[$date[0]][$date[1]]['deposit']++;
				}
				else {
					$buff[$date[0]][$date[1]]['deposit'] = 1;
				}
			}
			else {
				if(isset($buff[$date[0]][$date[1]]['buy'])) {
					$buff[$date[0]][$date[1]]['buy']++;
				}
				else {
					$buff[$date[0]][$date[1]]['buy'] = 1;
				}
			}
			
			if(isset($buff[$date[0]][$date[1]]['total'])) {
				$buff[$date[0]][$date[1]]['total'] += $r['receive'];
			}
			else {
				$buff[$date[0]][$date[1]]['total'] = $r['receive'];
			}
			
			if(isset($earningArr[$date[0]][$date[1]])) {
				$earningArr[$date[0]][$date[1]] += $r['receive'];
			}
			else {
				$earningArr[$date[0]][$date[1]] = $r['receive'];
			}			
			
			$earnings['referal'] += $r['receive'];
			$earnings['total'] += $r['receive'];
			
		}
		unset($referals);
		$referals = $buff;
		unset($buff);
	}	
	abr('referals', $referals);
	
	abr('earnings', $earnings);
	
	abr('earningArr', $earningArr);
	
	if(is_array($earningArr)) {
		$maxSales = 0;
		foreach($earningArr as $e) {
			foreach($e as $r) {
				if($r > $maxSales) {
					$maxSales = $r;
				}
			}
		}
		
		$earningIndex = ($maxSales>0) ? 300 / floatval($maxSales) : 0;
		abr('earningIndex', $earningIndex);
	}
    

    //推荐
	require_once ROOT_PATH.'/apps/qnews/models/qnews.class.php';
	$qnews = new qnews();
	$data = array();
	foreach($qnews->getAll(0, 1, "`visible` = 'true'") AS $key => $value) {
		if($value['photo']) {
			$data[$key] = $value;
			$data[$key]['thumb'] = 'static/uploads/qnews/260x140/' . $value['photo'];
		}
	}
	
	abr('qnews_data', $data);



if(!isset($_GET['month'])) {
	$_GET['month'] = date('m');
}
if(!isset($_GET['year'])) {
	$_GET['year'] = date('Y');
}
if(!checkdate($_GET['month'], 1, $_GET['year'])) {
	$_GET['month'] = date('m');
	$_GET['year'] = date('Y');
}

abr('download_csv_info', langMessageReplace($langArray['download_csv_info'], array('URL' => '/'.$languageURL.'users/statement/?month='.$_GET['month'].'&$year='.$_GET['year'].'&export')));

$registrationDate = explode(' ', $_SESSION['user']['register_datetime']);
$registrationDate = explode('-', $registrationDate[0]);
abr('registrationDate', $registrationDate);

$today['month'] = date('m');
$today['year'] = date('Y')+1;
abr('today', $today);

$nav['prev']['month'] = date('m', mktime(0, 0, 0, ($_GET['month']-1), 1, $_GET['year']));
$nav['prev']['year'] = date('Y', mktime(0, 0, 0, ($_GET['month']-1), 1, $_GET['year']));
$nav['next']['month'] = date('m', mktime(0, 0, 0, ($_GET['month']+1), 1, $_GET['year']));
$nav['next']['year'] = date('Y', mktime(0, 0, 0, ($_GET['month']+1), 1, $_GET['year']));
if($nav['prev']['month'] < $registrationDate[1] && $nav['prev']['year'] <= $registrationDate[0]) {
	$nav['prev']['show'] = 'false';
}
else {
	$nav['prev']['show'] = 'true';
}
if($nav['next']['month'] > date('m') && $nav['next']['year'] >= date('Y')) {
	$nav['next']['show'] = 'false';
}
else {
	$nav['next']['show'] = 'true';
}
abr('nav', $nav);

//获取资金流动记录
$logClass = new transaction_details();
$statement = $logClass->getRecord($_SESSION['user']['user_id']);

#获取资金记录
//require_once ROOT_PATH.'/apps/items/models/orders.class.php';
//$ordersClass = new orders();

//$statement = $ordersClass->getStatement($_SESSION['user']['user_id'], $_GET['month'], $_GET['year']);
abr('statement', $statement);

if(isset($_GET['export'])) {

	header('Content-Type: application/text/x-csv; charset=utf-8; encoding=utf-8');
	header('Content-Disposition: attachment; filename="stetement_'.$_GET['month'].'_'.$_GET['year'].'.csv"');
	header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
	header('Pragma: public');
	header("Content-Transfer-Encoding: binary");
	header('Expires: 0');
	@ob_clean();
	@flush();

	if(is_array($statement)) {
		foreach($statement as $s) {
			echo '"'.date('d M Y', strtotime($s['datetime'])).'",';

			if($s['type'] == 'deposit')
				echo '"'.$langArray['deposit'].'",';
			elseif($s['type'] == 'withdraw')
				echo '"'.$langArray['withdraw_money'].'",';
			elseif($s['type'] == 'order' && $s['owner_id'] == $_SESSION['user']['user_id'])
				echo '"'.$langArray['receive_money'].'",';
			else
				echo '"'.$langArray['purchase_money'].'",';

			if($s['type'] == 'deposit')
				echo '"$ '.number_format($s['price'], 2).'",';
			elseif($s['type'] == 'withdraw')
				echo '"$ -'.number_format($s['price'], 2).'",';
			elseif($s['type'] == 'order' && $s['owner_id'] == $_SESSION['user']['user_id'])
				echo '"$ '.number_format($s['receive'], 2).'",';
			else
				echo '"$ -'.number_format($s['price'], 2).'",';

			if($s['type'] == 'deposit')
				echo '"'.$langArray['deposit_money'].'",';
			elseif($s['type'] == 'withdraw')
				echo '"'.$langArray['earning_money'].'",';
			elseif($s['type'] == 'order' && $s['owner_id'] == $_SESSION['user']['user_id']) {
				if($s['referal'] == 'buy')
					echo '"'.$langArray['sold_item'].' '.$s['item_name'].'",';
				else
					echo '"'.$langArray['referal_money'].'",';
			}
			else
				echo '"'.$langArray['buy_item'].' '.$s['item_name'].'",';

			echo "\n";
		}
	}
	die();

}



#面包屑	
	abr('breadcrumb', '<a href="/'.$languageURL.'" title="">'.$langArray['home'].'</a> \ <a href="/'.$languageURL.'users/dashboard/" title="">'.$langArray['my_account'].'</a>');		
	
?>