<?php
if ( !defined( 'SMARTY_DIR' ) ) {
	include_once( '../init.php' );
}

include ( 'sessioninc.php' );

define( 'PAGE_ID', 'profile_mgt' );

if ( !checkAdminPermission( PAGE_ID ) ) {

	header( 'location: not_authorize.php' );
	exit;
}

$psize = getPageSize();

if ($_GET['status'] != '') {
	$_SESSION['query_for_status'] = $_GET['status'];
}

//Default Sorting
$sort = findSortBy();

$data=array();

//For Editing Sections
if ( $_GET['edit'] ) {


	if ($_SESSION['modifiedrow'] != '') {

		$data = $_SESSION['modifiedrow'];

		$data['level'] = $data['mlevel'];

		$data['id'] = $_GET['edit'];

		$_SESSION['modifiedrow'] = '';

	} else {

		$data =& $osDB->getRow( 'SELECT * from ! Where id = ?', array( USER_TABLE, $_GET['edit'] ) );

	}

	$lang['states'] = getStates($data['country'],'N');

	$lang['lookstates'] = getStates($data['lookfrom']);

	if ($data['state_province'] != '') {

		$lang['counties'] = getCounties($data['country'], $data['state_province'], 'N');

		if (count($lang['counties']) == 1) {
			foreach ($lang['counties'] as $key => $val) {
				$data['county'] = $key;
			}
		}

		if ($data['county'] != '') {

			$lang['cities'] = getCities($data['country'], $data['state_province'], $data['county'], 'N');

			if (count($lang['cities']) == 1) {
				foreach($lang['cities'] as $key => $val) {
					$data['city'] = $key;
				}
			}

			if ($data['city'] != '') {

				$lang['zipcodes'] = getZipcodes($data['country'], $data['state_province'], $data['county'], $data['city'], 'N');
			}
		}
	}

	if ($data['lookstate_province'] != '') {

		$lang['lookcounties'] = getCounties($data['lookcountry'], $data['lookstate_province'], 'Y');

		if (count($lang['lookcounties']) == 1) {
			foreach ($lang['lookcounties'] as $key => $val) {
				$data['lookcounty'] = $key;
			}
		}

		if ($data['lookcounty'] != '') {

			$lang['lookcities'] = getCities($data['lookcountry'], $data['lookstate_province'], $data['lookcounty'], 'Y');

			if (count($lang['lookcities']) == 1) {
				foreach($lang['lookcities'] as $key => $val) {
					$data['lookcity'] = $key;
				}
			}

			if ($data['lookcity'] != '') {

				$lang['lookzipcodes'] = getZipcodes($data['lookcountry'], $data['lookstate_province'], $data['lookcounty'], $data['lookcity'], 'Y');
			}
		}
	}

	$lang['tz'] = get_lang_values('tz');

	$t->assign( 'lang', $lang );

	if ($_GET['errid'] ) {
		$t->assign( 'error_message', get_lang('errormsgs', $_GET['errid'] ) );
	}

	$t->assign( 'user', $data );

	unset($data);

	$_SESSION['UserId'] = $_GET['edit'];

	$t->assign( 'mships', getMembershipsInfo() );

	$t->assign('rendered_page', $t->fetch('admin/profileedit.tpl'));

	$t->display( 'admin/index.tpl' );

	exit;
}

//For Deletion of profiles
if ( $_GET['txtdelete'] ) {

	deleteUser($_GET['txtdelete']);

	$t->assign('errmsg', PROFILE_DELETED);

	$t->assign('error_message', get_lang('errormsgs', PROFILE_DELETED) );

} elseif ($_POST['delete_selected'] == get_lang('delete_selected')) {

	@set_time_limit(1200);

	$arr = $_POST['txtchk'];

	if (count($arr) > 0) {
		/* Delete profile routine */
		foreach ($arr as $userId) {
			deleteUser($userId);
		}
		unset($arr);

		$t->assign('errmsg', PROFILES_DELETED);
		$t->assign('error_message', get_lang('errormsgs', PROFILE_DELETED) );
	}
}


$mships =& $osDB->getAll('select roleid, activedays, name from ! order by roleid',array( MEMBERSHIP_TABLE) );

$memberships = array();

$membership_names = array();

foreach ($mships as  $val) {

	$memberships[$val['roleid']] = $val['activedays'];

	$membership_names[$val['roleid']] = $val['name'];
}

unset($mships);

if ( $_POST['groupaction'] ) {

	$arr = $_POST['txtchk'];

	$status = 	$_POST['groupaction'];

	foreach ($lang['status_act'] as $key=>$val) {

		if ($val == $_POST['groupaction']) {

			$status = $key;
		}
	}

	if ( $status == get_lang('changeto') and count($arr) > 0 ) {

		$level =  $_POST['txtmlevel'];

		foreach( $arr as $val ) {
			if ($val != '' ) {
				$userlevel = $osDB->getRow('select * from ! where id = ?', array( USER_TABLE, $val) );

				if ($userlevel['levelend'] == '' || $level != $userlevel['level']) {

					$userlevel['levelend'] = time();

				}

				$add_days = $memberships[$level];

				$levelend = $userlevel['levelend'];

				$levelend = strtotime("+$add_days day",$levelend);

				$osDB->query( 'UPDATE !  SET level = ?, levelend = ?  WHERE id = ?', array( USER_TABLE, $level,  $levelend, $val ) );

				/* Now send email to member about this change */

				$message = get_lang('profile_membership_changed', MAIL_FORMAT);

				$Subject =  get_lang('profile_membership_changed_sub') ;

				$From = $config['admin_email'];

				$To = $userlevel['email'];

				$message = str_replace('#FirstName#', $userlevel['firstname'],$message);

				$message = str_replace('#ValidDate#',date(get_lang('DISPLAY_DATE_FORMAT'), $levelend), $message);

				$message = str_replace('#CurrentLevel#', $membership_names[$userlevel['level']], $message);

				$message = str_replace('#NewLevel#', $membership_names[$level], $message);

				$success = mailSender($From, $To, $userlevel['email'], $Subject, $message);
				unset($message, $Subject, $From, $To);
			}
		}
		unset($arr);
	} elseif ( count($arr) > 0 ) {

		foreach( $arr as $val ) {

			if ($val != '') {
				$usr = $osDB->getRow('select * from ! where id = ?', array( USER_TABLE, $val) );

				if ($usr['levelend'] == '' || $usr['levelend'] < time() ) {

					$usr['levelend'] = time();

				}

				$levelend = $usr['levelend'];

				$add_days = $memberships[$usr['level']];

				$osDB->query( "UPDATE ".USER_TABLE." SET status = '".$status."' WHERE id = '". $val ."'" ) ;

				if ($status == 'active' or $status == get_lang('status_act','active') ) {

					$osDB->query( "UPDATE ".USER_TABLE." SET active = 1, actkey='Confirmed'  WHERE id = '". $val ."'" ) ;

					/* Send activation email to the member */

					$message = get_lang('profile_activated', MAIL_FORMAT);

					$Subject =  get_lang('profile_activated_sub') ;

					$From = $config['admin_email'];

					$To = $usr['email'];

					$message = str_replace('#FirstName#', $usr['firstname'],$message);

					$message = str_replace('#AdminName#', $config['admin_name'],$message);

					$message = str_replace('#ValidDate#',date(get_lang('DISPLAY_DATE_FORMAT'), $usr['levelend']), $message);

					$message = str_replace('#MembershipLevel#', $membership_names[$usr['level']], $message);

					$success = mailSender($From, $To, $usr['email'], $Subject, $message);
					unset($message, $Subject, $From, $To);
				}
			}
		}
		unset($arr);
	}
}

$t->assign ( 'psize',  $psize );

$page_size = $psize;

$page = (int)$_GET['offset'];

if( $page == 0 ) $page = 1;

$upr = ($page)*$page_size - $page_size;

if ( $_POST['filter'] == 1 ) {

	$searchat = $_POST['txtsrchat'];

	$search = $_POST['txtsearch'];
	if ($searchat == 'status') $search = strtolower($search);

	if ($search == 'pending') $search='approval';

	$sql = "SELECT * FROM ! WHERE $searchat LIKE '%$search%'";

} else {

	$sql = 'SELECT * FROM ! ';
	if ($_SESSION['query_for_status'] != '') {
		$sql .= " where status = '".strtolower($_SESSION['query_for_status'])."' ";
	}
	$sql .= ' ORDER BY ' . $sort . " LIMIT $upr,$page_size ";

}



$data =& $osDB->getAll( $sql, array( USER_TABLE ) );

$t->assign('filter_options', get_lang_values('filter_options'));

if ($search != '' ) {
	$reccount = $osDB->getOne( "SELECT count(id) FROM ! WHERE ".$searchat." LIKE '%".$search."%'", array( USER_TABLE) );
} else {
	$reccount = $osDB->getOne( "SELECT count(id) FROM ! ", array( USER_TABLE) );
}

$t->assign ( 'total_recs',  $reccount );

$total_pages = ceil( $reccount / $page_size );

$pages_vals = array();

for( $i=1; $i<=$total_pages; $i++ ) { $pages_vals[$i] = $i; }

$t->assign ( 'total_pages',  $pages_vals );

$page_limit = 5;
$j = 1;
if ( $page > 2 ) { $page = $page - 2; } else { $page = 1; }
for( $i=$page; $i<=$total_pages; $i++ ) {
	$pages_show[$i] = $i;

	$j++;
	if ( $j > $page_limit )	break;
}

$t->assign ( 'pages_show',  $pages_show );

$t->assign ( 'reccount',  $reccount );

$t->assign( 'lang', $lang );

$t->assign( 'sort_type', ($_GET['type']=='asc'?'desc':'asc' ) );

/* if ($_GET['type'] == 'desc') {
	$srttype='asc';
} else {
	$srttype='desc';
}
*/
$t->assign( 'querystring', 'sort=' . $_GET['sort'] . '&amp;type=' . $_GET['type']);

$t->assign( 'upr', $upr );

$usersinfo = array();

foreach ($data as $rec) {

	$feat = $osDB->getOne('select userid from ! where userid = ?',array(FEATURED_PROFILES_TABLE, $rec['id']) );
	if ( $feat ==$rec['id'] ) {
		$rec['featured'] = '1';
	}

	$rec['picscnt'] = $osDB->getOne('select count(*) from ! where userid = ?', array(USER_SNAP_TABLE, $rec['id']) );

	$rec['videoscnt'] = $osDB->getOne('select count(*) from ! where userid = ?', array(USER_VIDEOS_TABLE, $rec['id']) );

/* Modify the status flag if the profile is not activated by the user. */
	if ($rec['active'] != '1' && $rec['active'] != 'Y'  && $rec['status'] != 'cancel' ) {
		$rec['status'] = 'approval';
	}

	$usersinfo[]=$rec;

}

$t->assign( 'data', $usersinfo );

unset($userinfo);

$t->assign('nowdate', time());

$t->assign( 'mships', getMembershipsInfo() );

$t->assign('rendered_page', $t->fetch('admin/profile.tpl'));

$t->display( 'admin/index.tpl' );

exit;
?>