<?php
/*======================================================================*\
|| #################################################################### ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright ©2013 Fillip Hannisdal AKA Revan/NeoRevan/Belazor 	  # ||
|| # All Rights Reserved. 											  # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # ---------------------------------------------------------------- # ||
|| # You are not allowed to use this on your server unless the files  # ||
|| # you downloaded were done so with permission.					  # ||
|| # ---------------------------------------------------------------- # ||
|| #################################################################### ||
\*======================================================================*/

// #######################################################################
// ######################## START MAIN SCRIPT ############################
// #######################################################################

// #############################################################################
if ($_REQUEST['action'] == 'feedback' OR empty($_REQUEST['action']))
{
	// Grab stuff
	$vbulletin->input->clean_array_gpc('r', array(
		'shopid' 		=> TYPE_UINT,
		'pagenumber' 	=> TYPE_UINT,
		'perpage' 		=> TYPE_UINT,
	));

	if (!$shop = VBSHOP::$cache['shop'][$vbulletin->GPC['shopid']])
	{
		// Couldn't find the shop
		eval(standard_error(fetch_error('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_shop'], $vbulletin->GPC['shopid'])));
	}

	if (!$shop['canhavefeedback'])
	{
		// Couldn't find the shop
		eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_shop_cannot_receive_feedback'])));
	}

	if ($shop['ownerid'])
	{
		$owner = fetch_userinfo($shop['ownerid']);

		if (!is_array($owner['permissions']))
		{
			// Ensure we have the perms
			cache_permissions($owner);
		}

		if (!($owner['permissions']['dbtech_vbshoppermissions'] & $vbulletin->bf_ugp_dbtech_vbshoppermissions['canreceivefeedback']))
		{
			// Couldn't find the shop
			eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_shop_cannot_receive_feedback'])));
		}
	}

	if (VBSHOP::$permissions['canleavefeedback'])
	{
		$feedback = '';
		$missingFeedback = VBSHOP::$db->fetchAllKeyed('
			SELECT *
			FROM $dbtech_vbshop_purchase
			WHERE feedbackstatus < 2
				AND shopid = ?
				AND userid = ?
		', 'purchaseid', array(
			$shop['shopid'],
			$vbulletin->userinfo['userid']
		));
		foreach ($missingFeedback as $missing)
		{
			if ($shop['ownerid'] AND $shop['ownerid'] == $vbulletin->userinfo['userid'])
			{
				// Flag as having sent reminder
				VBSHOP::$db->update('dbtech_vbshop_purchase', array('feedbackstatus' => 1), 'WHERE purchaseid = ' . $missing['purchaseid']);
				continue;			
			}

			// Ensure we have the proper day selected for the grouping
			$missing['date'] = vbdate($vbulletin->options['dateformat'], $missing['dateline'], true);
			$missing['time'] = vbdate($vbulletin->options['timeformat'], $missing['dateline']);

			// Sort out the title
			$missing['title'] = VBSHOP::$cache[$missing['feature']][$missing['featureid']]['title'];

			// Create the archive template
			$templater = vB_Template::create('dbtech_vbshop_shopfeedback_missing');
				$templater->register('item', 			$missing);
			$feedback .= $templater->render();
		}
	}

	// Ensure there's no errors or out of bounds with the page variables
	if ($vbulletin->GPC['pagenumber'] < 1)
	{
		$vbulletin->GPC['pagenumber'] = 1;
	}
	$pagenumber = $vbulletin->GPC['pagenumber']; // $vbulletin->options['dbtech_vbshout_maxshouts']
	$perpage = (!$vbulletin->GPC['perpage'] OR $vbulletin->GPC['perpage'] > 25) ? 25 : $vbulletin->GPC['perpage'];

	// Count number of users
	$count = VBSHOP::$db->fetchOne('
		SELECT COUNT(*) 
		FROM $dbtech_vbshop_feedback AS feedback
		INNER JOIN $dbtech_vbshop_purchase AS purchase USING(purchaseid)
		WHERE shopid = ?
	', array(
		$shop['shopid']
	));

	// Ensure every result is as it should be
	sanitize_pageresults($count, $pagenumber, $perpage);
	
	// Find out where to start
	$startat = ($pagenumber - 1) * $perpage;
	
	// Constructs the page navigation
	$pagenav = construct_page_nav(
		$pagenumber,
		$perpage,
		$count,
		'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=feedback&amp;shopid=' . $shop['shopid'],
		"&amp;perpage=$perpage"
	);
	
	// Fetch users
	$results = VBSHOP::$db->fetchAll('
		SELECT *, feedback.dateline
		FROM $dbtech_vbshop_feedback AS feedback
		INNER JOIN $dbtech_vbshop_purchase AS purchase ON(purchase.purchaseid = feedback.purchaseid)
		INNER JOIN $user AS user ON(user.userid = feedback.userid)
		WHERE purchase.shopid = ?
		ORDER BY feedback.dateline DESC
		LIMIT :limitStart, :limitEnd
	', array(
		$shop['shopid'],
		':limitStart' => $startat,
		':limitEnd' => $perpage,
	));

	$purchaseentries = array();
	foreach ($results as $result)
	{
		// Ensure we have the proper day selected for the result
		$day = vbdate($vbulletin->options['dateformat'], $result['dateline']);

		// Grab musernames
		fetch_musername($result);

		$result['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_x_left_feedback_for_item_y'],
			'<a href="member.php?' . $vbulletin->session->vars['sessionurl'] . 'u=' . $result['userid'] . '">' . $result['musername'] . '</a>',
			VBSHOP::$cache[$result['feature']][$result['featureid']]['title'],
			$result['feedback'],
			$result['rating']
		);

		if (VBSHOP::$permissions['canmoderatefeedback'])
		{
			$result['phrase'] = '<a href="vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=feedback&amp;action=kill&amp;feedbackid=' . $result['feedbackid'] . '" onclick="return confirm(\'' . str_replace("'", "\'", $vbphrase['dbtech_vbshop_are_you_sure_delete_feedback']) . '\');">[' . $vbphrase['delete'] . ']</a> - '. $result['phrase'];
		}

		// Add the entry to the list, grouped by day
		$purchaseentries[$day][$result['feedbackid']] = $result;
	}

	$entrybits = '';
	foreach ($purchaseentries as $day => $entries)
	{
		$entrybitbits = '';
		foreach ($entries as $entry)
		{
			$entry['dateline'] = vbdate($vbulletin->options['timeformat'], $entry['dateline']);
			
			$templaterr = vB_Template::create('dbtech_vbshop_entrybit');
				$templaterr->register('entry', $entry);
			$entrybitbits .= $templaterr->render();
		}
		
		$templater = vB_Template::create('dbtech_vbshop_daybit');
			$templater->register('day', $day);
			$templater->register('entrybits', $entrybitbits);				
		$entrybits .= $templater->render();
	}

	$stats = array(
		'totalfeedback' => vb_number_format($count),
		'avg' 			=> vb_number_format($shop['averagerating'], 2),
		'avgRounded' 	=> floor($shop['averagerating']),
		'positive' 		=> vb_number_format($shop['positivepercent'], 2),
		'negative' 		=> vb_number_format($shop['negativepercent'], 2),
		'neutral' 		=> vb_number_format($shop['neutralpercent'], 2),
	);

	// Add to the navbits
	$navbits['vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=shop&amp;shopid=' . $shop['shopid']] = htmlspecialchars_uni($shop['title']);
	$navbits[''] = $pagetitle = construct_phrase($vbphrase['dbtech_vbshop_shop_feedback_x'], htmlspecialchars_uni($shop['title']));
	
	// Create the archive template
	$templater = vB_Template::create('dbtech_vbshop_shopfeedback');
		$templater->register('pagetitle', 	$pagetitle);
		$templater->register('shop', 		$shop);
		$templater->register('feedback', 	$feedback);
		$templater->register('history', 	$entrybits);
		$templater->register('stats', 		$stats);
		$templater->register('pagenav', 	$pagenav);
	$HTML = $templater->render();
}

// #############################################################################
if ($_REQUEST['action'] == 'update')
{
	// Grab stuff
	$vbulletin->input->clean_array_gpc('p', array(
		'shopid' 	=> TYPE_UINT,
		'feedback' 	=> TYPE_ARRAY,
	));

	if (!$shop = VBSHOP::$cache['shop'][$vbulletin->GPC['shopid']])
	{
		// Couldn't find the shop
		eval(standard_error(fetch_error('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_shop'], $vbulletin->GPC['shopid'])));
	}

	if (!$shop['canhavefeedback'])
	{
		// Couldn't find the shop
		eval(standard_error(fetch_error('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_shop'], $vbulletin->GPC['shopid'])));
	}

	if ($shop['ownerid'])
	{
		$owner = fetch_userinfo($shop['ownerid']);

		if (!is_array($owner['permissions']))
		{
			// Ensure we have the perms
			cache_permissions($owner);
		}

		if (!($owner['permissions']['dbtech_vbshoppermissions'] & $vbulletin->bf_ugp_dbtech_vbshoppermissions['canreceivefeedback']))
		{
			// Couldn't find the shop
			eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_shop_cannot_receive_feedback'])));
		}
	}

	if (!VBSHOP::$permissions['canleavefeedback'])
	{
		// Couldn't find the shop
		eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_cannot_leave_feedback'])));
	}


	//$vbulletin->GPC['shop']['title'] 		= htmlspecialchars_uni($vbulletin->GPC['shop']['title']);
	//$vbulletin->GPC['shop']['description'] 	= htmlspecialchars_uni($vbulletin->GPC['shop']['description']);
	
	$missingFeedback = VBSHOP::$db->fetchAllKeyed('
		SELECT *
		FROM $dbtech_vbshop_purchase
		WHERE feedbackstatus < 2
			AND shopid = ?
			AND userid = ?
	', 'purchaseid', array(
		$shop['shopid'],
		$vbulletin->userinfo['userid']
	));

	// shop fields
	foreach ($vbulletin->GPC['feedback'] AS $purchaseid => $arr)
	{
		if (!isset($missingFeedback[$purchaseid]))
		{
			// Skip this
			continue;
		}

		if (!$arr['rating'])
		{
			// Opt out of feedback
			if ($vbulletin->options['dbtech_vbshop_allowoptout'])
			{
				// Only if we allow opt outs
				VBSHOP::$db->update('dbtech_vbshop_purchase', array('feedbackstatus' => 2), 'WHERE purchaseid = ' . $purchaseid);
			}
			continue;
		}

		if ($arr['feedback'] AND $vbulletin->options['dbtech_vbshop_feedback_maxlength'])
		{
			// Crop to size
			$arr['feedback'] = substr($arr['feedback'], 0, $vbulletin->options['dbtech_vbshop_feedback_maxlength']);
		}

		// Ensure these things get set
		$arr['userid'] = $vbulletin->userinfo['userid'];
		$arr['purchaseid'] = $purchaseid;

		// init data manager
		$dm =& VBSHOP::initDataManager('Feedback', $vbulletin, ERRTYPE_STANDARD);
			$dm->set_info('shop', $shop);
		
		// shop fields
		foreach ($arr AS $key => $val)
		{
			// Only set changed values
			$dm->set($key, $val);
		}
		
		// Save! Hopefully.
		$dm->save();
	}
	
	// Success phrase
	$vbulletin->url = 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=feedback&shopid=' . $shop['shopid'];
	eval(print_standard_redirect('dbtech_vbshop_shop_updated'));	
}

// #############################################################################
if ($_REQUEST['action'] == 'kill')
{
	if (!VBSHOP::$permissions['canmoderatefeedback'])
	{
		// We need permissions
		print_no_permission();
	}

	$vbulletin->input->clean_gpc('r', 'feedbackid', TYPE_UINT);
	
	if (!$existing = VBSHOP::$db->fetchRow('
		SELECT feedback.*, purchase.shopid 
		FROM $dbtech_vbshop_feedback AS feedback
		INNER JOIN $dbtech_vbshop_purchase AS purchase USING(purchaseid)
		WHERE feedback.feedbackid = ?
	', array(
		$vbulletin->GPC['feedbackid']
	)))
	{
		// Couldn't find the category
		eval(standard_error(fetch_error('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_feedback'], $vbulletin->GPC['feedbackid'])));
	}

	if (!$shop = VBSHOP::$cache['shop'][$existing['shopid']])
	{
		// Couldn't find the shop
		eval(standard_error(fetch_error('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_shop'], $existing['shopid'])));
	}

	// To be safe
	unset($existing['shopid']);

	// init data manager
	$dm =& VBSHOP::initDataManager('Feedback', $vbulletin, ERRTYPE_STANDARD);
		$dm->set_existing($existing);
		$dm->set_info('shop', $shop);
	$dm->delete();
	
	// Success phrase
	$vbulletin->url = 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=feedback&shopid=' . $shop['shopid'];
	eval(print_standard_redirect('dbtech_vbshop_shop_updated'));
}

// draw cp nav bar
VBSHOP::setNavClass('shop');