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

include ( 'sessioninc.php' );

define( 'PAGE_ID', 'promo_mgt' );

if ( !checkAdminPermission( PAGE_ID ) ) {

	header( 'location: not_authorize.php' );
	exit;
}
$psize = getPageSize();

if ( $_GET['edit'] ) {

	if ($_GET['errid'] != '') {
		$data['date'] = $_SESSION['txtdate'];
		$data['header'] = $_SESSION['txttitle'];
		$data['text'] = $_SESSION['txttext'];
		$data['promoid'] = $_GET['edit'];
	} else{
		$data =& $osDB->getRow( 'SELECT * from ! Where id = ?', array(PROMO_TABLE, $_GET['edit']) );
	}
	$t->assign( 'lang', $lang );

	if ($_GET['errid'] != '') {
		$t->assign( 'error_msg', get_lang('promo_error', $_GET['errid'] ) );
	}
	$t->assign( 'promos', $data );

	unset($data);

	$roles = array();

	$rs =& $osDB->getAll( 'SELECT roleid, name FROM !',array( MEMBERSHIP_TABLE ) );

	foreach ( $rs as $row ) {

		$roles[$row['roleid']] = $row['name'];
	}

	$t->assign( 'memberships', $roles );

	unset($roles, $rs);

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

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

	exit;
}

$id = $_REQUEST['promoid'];

if ( $_REQUEST['delete'] == 'promo' ) {

	$osDB->query( 'DELETE FROM ! Where id = ?', array(PROMO_TABLE, $id ) );

	header('location: managepromo.php');

	exit;

}

if ( $_REQUEST['active'] == 'promo' ) {

	$osDB->query( 'UPDATE ! SET active = ? WHERE id = ?', array( PROMO_TABLE, '1', $id ) );

	header('location: managepromo.php');

	exit;
}

if ( $_REQUEST['inactive'] == 'promo' ) {

	$osDB->query( 'UPDATE ! SET active = ? WHERE id = ?', array( PROMO_TABLE, '0', $id ) );

	header('location: managepromo.php');

	exit;
}


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

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

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

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

if( $_GET['sort'] == get_lang('col_head_sendtime') ) {

	$sort = 'date '. checkSortType ( $_GET['type'] );

} elseif ($_REQUEST['sort'] == 'promo_code') {

	$sort = ' promocode '.checkSortType ( $_GET['type'] );

} elseif ($_REQUEST['sort'] == 'promo_desc') {

	$sort = ' pdesc '.checkSortType ( $_GET['type'] );

} else {

	$sort = findSortBy('id');
}

$t->assign ( 'total_recs', $osDB->getOne( 'SELECT count(*) as num FROM !', array(PROMO_TABLE) ) );

$t->assign( 'data', $osDB->getAll( 'SELECT * FROM ! ORDER BY ' . $sort . " LIMIT $upr,$psize ", array(PROMO_TABLE) ) );

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

$t->assign( 'sort_type', checkSortType( $_GET['type'] ) );

$t->assign( 'querystring', 'sort=' . $_GET['sort'] . '&type=' . $_GET['type']);

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

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

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


?>