<?php

define('BB_SCRIPT', 'present');
define('BB_ROOT', './');
require(BB_ROOT .'common.php');
require INC_DIR . '/bbcode.php';

$start = (int) request_var('start', '');
$present = (string) request_var('present', 'list');
$present_id = (int) request_var('pre', '0');
$submit = @$_POST['submit'];
$type = (int) request_var('type', '');
$user_id = (int) request_var('u', '');

$allowed_ext = array('jpeg', 'jpg',	'png', 'gif');
$dir = 'styles/images/presents/';

$url = "presents.php?present=$present";
if($present_id)
{
	$url .= "&pre=$present_id";
}

$user->session_start();

$present_type = array(
	0  => $lang['PRESENT_SPECITY_TYPE'],
	1  => $lang['PRESENT_TIMELESS'],
	2  => $lang['PRESENT_BALOONS'],
	3  => $lang['PRESENT_MASKS'],
	4  => $lang['PRESENT_FOR_LOVERS'],
	5  => $lang['PRESENT_FOR_GIRLS'],
	6  => $lang['PRESENT_FOR_MEN'],
	7  => $lang['PRESENT_FOOD'],
	8  => $lang['PRESENT_ANIMALS'],
	9  => $lang['PRESENT_COMPUTERS'],
	10 => $lang['PRESENT_SUMMER'],
	11 => $lang['PRESENT_PRIVATE'],
	12 => $lang['PRESENT_STUFFED_TOYS'],
	13 => $lang['PRESENT_DRINKS'],
	14 => $lang['PRESENT_KISSES'],
	15 => $lang['PRESENT_OTHER'],
	16 => $lang['PRESENT_SUNGLASSES'],
	17 => $lang['PRESENT_SPORT'],
	18 => $lang['PRESENT_STATUES'],
	19 => $lang['PRESENT_DECORATION'],
	20 => $lang['PRESENT_HOBBY'],
	21 => $lang['PRESENT_FLOWERS'],
	22 => $lang['PRESENT_NEW_YEAR'],
);
foreach ($present_type as $id => $name)
{
	$select_type[$name] = $id;
}

$page_title = '';

if ($bb_cfg['seed_bonus_enabled'] && $bb_cfg['presents'])
{
	if($present == 'list')
	{
		$template->assign_vars(array(
			'PRESENT_LIST'  => true,
		));
		$page_title = $lang['PRESENTS_CATALOG'];

		if($submit)
		{
			if(!IS_ADMIN) bb_die($lang['NOT_ADMIN']);

			$files = $_FILES['pic'];
			$name = (string) $_POST['name'];
			$price = (int) $_POST['price'];
			$type = (int) @$_POST['type'];
			$active = (int) @$_POST['active'];

			$ext = substr(strrchr(strtolower($files['name']), '.'), 1);
			$allow = in_array($ext, $allowed_ext);
			$pic_type = '.'. $ext;

			if ($allow)
			{
				$pic_name = substr(md5_file($files['tmp_name']), 0, 10);

				if (file_exists($dir . $pic_name . $pic_type))
				{
					meta_refresh("presents.php", 1);
					bb_die($lang['PRESENT_ERROR_PIC']);
				}
				else
				{
					if (copy($files['tmp_name'], $dir . $pic_name . $pic_type))
					{
						$pic = $pic_name . $pic_type;
						DB()->query("INSERT INTO ". BB_PRESENTS ."
							(present_id, present_name, present_pic, present_price, present_active, present_type)
							VALUES('',   '$name',      '$pic',      '$price',      '$active',      '$type')
						");

						meta_refresh("presents.php", 1);
						bb_die($lang['PRESENT_ADD']);
					}
					else
					{
						meta_refresh("presents.php", 1);
						bb_die($lang['PRESENT_NO_ADD']);
					}
				}
			}

			meta_refresh("presents.php", 1);
			bb_die($lang['WRONG_FORMAT']);
		}
		else
		{
			$where_sql = 'WHERE present_id';
			if(!IS_AM) $where_sql .= " AND present_active = 1";
			if($type) $where_sql .= " AND present_type = $type";

			$count = DB()->fetch_row("SELECT COUNT(present_id) as present FROM ". BB_PRESENTS ." $where_sql");

			if($count['present'])
			{
				$sql = DB()->fetch_rowset("SELECT * FROM ". BB_PRESENTS ." $where_sql ORDER BY present_id DESC LIMIT $start, 12");

				$presentrow = array();
				foreach($sql as $row)
				{
					$presentrow[] = $row;
				}

				if (!$presentrow)
				{
					$template->assign_block_vars('not_present', array());
				}

				for ($j = 0; $j < count($presentrow); $j += 4)
				{
					$template->assign_block_vars('presentrow', array());

					for ($i = $j; $i < ($j + 4); $i++)
					{
						if( $i >= count($presentrow) )
						{
							$template->assign_block_vars('presentrow.not', array());
							continue;
						}

						$template->assign_block_vars('presentrow.presentcol', array(
							'NAME'  => $presentrow[$i]['present_name'],
							'PIC'   => $presentrow[$i]['present_pic'],
							'PRICE' => $presentrow[$i]['present_price'],
							'ID'    => $presentrow[$i]['present_id'],
							'TYPE'  => $present_type[$presentrow[$i]['present_type']]
						));
					}
				}
				if($user_id)
				{
					$url .= "&u=$user_id";
				}
				generate_pagination($url. "&type=$type", $count['present'], 12, $start);
				$template->assign_vars(array(
					'SELECT_TYPE'     => build_select('type', $select_type, $type, null, null, 'onchange="$(\'#type\').submit();"'),
					'SELECT_TYPE_PRESENT'=> build_select('type', $select_type, $type, null, null),
				));
			}
		}
	}
	else if($present == 'edit')
	{
		if(!IS_ADMIN) bb_die($lang['NOT_ADMIN']);

		$template->assign_vars(array(
			'PRESENT_EDIT'  => true,
		));
		$page_title = $lang['CHANGING_PRESENT'];

		if(!$present_id)
		{
			meta_refresh("presents.php", 1);
			bb_die($lang['PRESENT_NOT_SELECT']);
		}

		if($submit)
		{
			$files = $_FILES['pic'];
			$name = (string) $_POST['name'];
			$price = (int) $_POST['price'];
			$type = (int) @$_POST['type'];
			$active = (int) @$_POST['active'];
			$delete = (int) @$_POST['delete'];

			if($delete)
			{
				if(!IS_AM)
				{
					bb_die($lang['NOT_AUTHORISED']);
				}

				if($row = DB()->fetch_row("SELECT present_pic FROM ". BB_PRESENTS ." WHERE present_id = $present_id"))
				{
					unlink($dir . $row['present_pic']);
					DB()->query("DELETE pre.*, upre.* FROM ". BB_PRESENTS ." pre LEFT JOIN ". BB_USERS_PRESENTS ." upre ON (pre.present_id = upre.present_id) WHERE pre.present_id = $present_id");
					meta_refresh("presents.php", 1);
					bb_die($lang['PRESENT_DELETE']);
				}
				else
				{
					meta_refresh("presents.php", 1);
					bb_die($lang['PRESENT_NO']);
				}
			}

			DB()->query("UPDATE ". BB_PRESENTS ." SET present_name = '$name', present_price = '$price', present_type = '$type', present_active = '$active' WHERE present_id = $present_id");

			$ext = mb_substr(mb_strrchr(mb_strtolower($files['name']), '.'), 1);
			$allow = in_array($ext, $allowed_ext);
			$pic_type = '.'. $ext;

			if ($allow)
			{
				$row = DB()->fetch_row("SELECT present_pic FROM ". BB_PRESENTS ." WHERE present_id = $present_id");
				unlink($dir . $row['present_pic']);

				$pic_name = substr(md5_file($files['tmp_name']), 0, 10);

				if (copy($files['tmp_name'], $dir . $pic_name . $pic_type))
				{
					$pic = $pic_name . $pic_type;
					DB()->query("UPDATE ". BB_PRESENTS ." SET present_pic = '$pic' WHERE present_id = $present_id");
				}
				else
				{
					meta_refresh("presents.php", 1);
					bb_die($lang['PRESENT_NO_ADD']);
				}
			}
			meta_refresh("presents.php", 1);
			bb_die($lang['PRESENT_EDITED']);
		}
		else if($row = DB()->fetch_row("SELECT * FROM ". BB_PRESENTS ." WHERE present_id = $present_id"))
		{
			$template->assign_vars(array(
				'SELECT_TYPE'     => build_select('type', $select_type, $row['present_type'], null, null),
				'NAME'            => $row['present_name'],
				'PRICE'           => $row['present_price'],
				'PIC'             => $row['present_pic'],
				'ACTIVE_CHECKED'  => ($row['present_active']) ? HTML_CHECKED : '',
			));
		}
		else
		{
			meta_refresh("presents.php", 1);
			bb_die($lang['PRESENT_NO']);
		}
	}
	else if($present == 'donate')
	{
		IF(IS_GUEST) redirect("login.php?redirect=$url");

		$template->assign_vars(array(
			'PRESENT_DONATE'  => true,
		));
		$page_title = $lang['GIVE_PRESENT'];

		if(!$present_id)
		{
			meta_refresh("presents.php", 1);
			bb_die($lang['PRESENT_NOT_SELECT']);
		}

		if($row = DB()->fetch_row("SELECT * FROM ". BB_PRESENTS ." WHERE present_id = $present_id"))
		{
			$template->assign_vars(array(
				'SELECT_TYPE'     => build_select('type', $select_type, $row['present_type'], null, null),
				'NAME'            => $row['present_name'],
				'PRICE'           => (($row['present_price'] <= $userdata['user_points']) ? '<font color="green"><b>' : '<font color="red"><b>') . $row['present_price'] .'</b></font> '. sprintf($lang['PRESENT_PRICE_MESS'], $userdata['user_points']),
				'PIC'             => $row['present_pic'],
				'ACTIVE_CHECKED'  => ($row['present_active']) ? HTML_CHECKED : '',
				'TYPE'            => $present_type[$row['present_type']],
				'USERNAME'        => ($user_id) ? get_username ($user_id) : '',
			));
		}
		else
		{
			meta_refresh("presents.php", 1);
			bb_die($lang['PRESENT_NO']);
		}

		if($submit)
		{
			$errors = array();
			$username = !empty($_POST['username']) ? clean_username($_POST['username']) : $errors[] = $lang['PRESENT_NOT_SELECT_USER'];
			$user_id = get_user_id ($username);
			if(!$user_id)
			{
				$errors[] = $lang['PRESENT_NOT_FOUND_USER'];
			}
			elseif($user_id == $userdata['user_id'])
			{
				$errors[] = $lang['PRESENT_NOT_YOURSELF'];
			}
			elseif($user_id == GUEST_UID)
			{
				$errors[] = $lang['PRESENT_NOT_GUEST_UID'];
			}
			elseif($user_id == BOT_UID)
			{
				$errors[] = $lang['PRESENT_NOT_BOT'];
			}

			if($user_id)
			{
				$url .= "&u=$user_id";
			}

			$message = !empty($_POST['message']) ? $_POST['message'] : '';

			$price = $row['present_price'];
			if($userdata['user_points'] < $price) $errors[] = $lang['PRESENT_TOO_HIGH'];

			$hide = (int) $_POST['hide_present'];

			$template->assign_vars(array(
				'MESSAGE'       => $message,
				'ERROR_MESSAGE' => ($errors) ? join('<br />', array_unique($errors)) : '',
			));

			if(!$errors)
			{
				$username = ($hide) ? $lang['PRESENT_INCOGNITO'] : '[url='. make_url(PROFILE_URL . $userdata['user_id']) .'][b]'. $userdata['username'] .'[/b][/url]';
				$comment  = ($message) ? "[br][br]". $lang['PRESENT_COMMENT'] .": $message" : '';
				$text = sprintf($lang['PRESENT_MESSAGE'], $username, $comment, make_url(PROFILE_URL . $user_id) ."#presents");
				send_pm($user_id, $lang['PRESENT_NEW'], prepare_message($text), BOT_UID);

				DB()->query("UPDATE ". BB_USERS ." SET user_points = user_points - $price WHERE user_id = {$userdata['user_id']} LIMIT 1");
				DB()->query("INSERT INTO ". BB_USERS_PRESENTS ." SET user_id = $user_id, present_id = $present_id, time = '". TIMENOW ."', comment = '". DB()->escape(trim($message)) ."', given_id = {$userdata['user_id']}, given_hide = $hide");
				cache_rm_user_sessions ($userdata['user_id']);

				meta_refresh("presents.php", 10);
				bb_die(
					$lang['PRESENT_GIFTED'] . '
					<br /><br />
					<a href="'. PROFILE_URL . $user_id .'" onclick="return post2url(this.href, {after_edit: 1});">'. $lang['PROFILE_RETURN'] .'</a>
					'. (IS_ADMIN ? '
					<br /><br />
					<a href="profile.php?mode=editprofile&amp;u=$user_id" onclick="return post2url(this.href, {after_edit: 1});">'. $lang['PROFILE_EDIT_RETURN'] .'</a>' : '') .'
					<br /><br />
					<a href="index.php">'. $lang['INDEX_RETURN'] .'</a>'
				);
				
				//bb_die($lang['PRESENT_GIFTED']);
			}
		}
	}
}
else
{
	bb_die($lang['PRESENTS_OFF']);
}

$template->assign_vars(array(
	'PAGE_TITLE'       => $page_title,
	'USER_PRESENT'     => $user_id,
	'PRESENT_URL'      => $url,
	'USER_POINTS'        => $userdata['user_points'],
));

print_page('presents.tpl');
