<?php
	include('/var/www/portal/auth.php');
	setlocale(LC_MONETARY, 'en_US');
	$db = $dbClass->connect('products', 'SELECT');
	
	$account_id = "";
	$discountlevel = 'list';
	$exacq = false;
	$rep = false;
	$dist = false;
	
	if ($authenticated) {
		// Grab account information.
		chkPermissions();
		$vars = unserialize(base64_decode($_SESSION['vars']));
		$account_id = $vars['said'];
		
		if ($vars['srid'] != NULL)
			$rep = true;

		$discount_query = 'SELECT discount_c, customertype_c FROM accounts_cstm WHERE id_c=:id';
		$discount_ex = $sugardb->prepare($discount_query);
		$discount_ex->execute(array(':id' => $account_id));
		$discount = $discount_ex->fetch();
		
		if ($account_id == '3c86fd68-951e-d226-56c4-4e5f0ee84d67' || $vars['catalog_c'] == 'Tyco')
			$exacq = true;
		else if ($discount['customertype_c'] == 'Distributor')
			$dist = true;
		else if ($discount['customertype_c'] == 'Rep')
			$rep = true;
			
		if (strpos($discount['discount_c'], '45') !== false)
			$discountlevel = 'dpls';
		else if (strpos($discount['discount_c'], '42.5') !== false)
			$discountlevel = 'dist';
		else if (strpos($discount['discount_c'], '40') !== false)
			$discountlevel = 'cpls';
		else if (strpos($discount['discount_c'], '35') !== false)
			$discountlevel = 'cert';
		else if (strpos($discount['discount_c'], '30') !== false)
			$discountlevel = 'rslr';
			
		$access_query = 'SELECT access_type FROM cportal_catalog WHERE sugar_contact_id = :scid';
		$access_ex = $wadb->prepare($access_query);
		$access_ex->execute(array(':scid' => $_SESSION['scid']));
		$access = $access_ex->fetch();
	}
	

	// Populate category list.
	$category_query = 'SELECT * FROM product_categories c INNER JOIN product_categories_cstm m ON c.id = m.id_c WHERE c.deleted = 0 AND m.status_c = "Production" ORDER BY c.list_order ASC';
	$category_ex = $db->prepare($category_query);
	$category_ex->execute();
	$categories = $category_ex->fetchAll();
	
	$option_query = 'SELECT p.name, p.list_price, p.description FROM product_templates p '
		. 'INNER JOIN product_types t ON p.type_id = t.id '
		. 'WHERE p.deleted = 0 AND (t.name = "Options & Accessories" OR t.name = "License" OR t.name = "Software") '
		. 'ORDER BY p.name ASC';
	$option_ex = $db->prepare($option_query);
	$option_ex->execute();
	$options = json_encode($option_ex->fetchAll(), JSON_HEX_QUOT | JSON_HEX_APOS);

	$series_list = array();
	foreach ($categories as $category) {
		if ($category['parent_id'] == '') {
			$series_list[$category['id']] = array(
				'name' => $category['name'],
				'display_name' => $category['display_name_c']
			);
		}
	}
	
	foreach ($categories as $category) {
		if ($category['parent_id'] != '') {
			$cat[] = array(
				'name' => $category['name'],
				'display' => $category['display_name_c'],
				'description' => $category['description'],
				'series' => ($series_list[$category['parent_id']]['name'] ?? "")
			);
		}
	}

	if (isset($_REQUEST['category'])) {
		 $apos = strpos($_REQUEST['category'],"'");
	                 if($apos)
                         $_REQUEST['category'] = substr($_REQUEST['category'],0,$apos);
		$permalink = $_REQUEST['category'];
	}
	
	// CURRENCY STUFF
	$wadb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$currency_query = 'SELECT * FROM currency WHERE deleted = 0 ORDER BY type ASC';
	$currency_ex = $wadb->prepare($currency_query);
	$currency_ex->execute();
	$currency  = $currency_ex->fetchAll(PDO::FETCH_ASSOC);
	
	// Get default currency.
	$default_currency_query = 'SELECT currency_type_c FROM accounts_cstm WHERE id_c=:id';
	$default_currency_ex = $db->prepare($default_currency_query);
	$default_currency_ex->execute(array(':id' => $account_id));
	$default_currency = $default_currency_ex->fetch(PDO::FETCH_ASSOC);
	$default_array = explode(',', str_replace(' ', '', strtoupper(($default_currency['currency_type_c'] ?? ""))));
	$default_select = array();
	
	if ($default_array[0] != '')
		$default = $default_array[0];
	else
		$default = 'USD';
	
	$modifier = 1;
	$symbol = "$";
	if (isset($_REQUEST['currencytype']) || $default != '') {
		if (isset($_REQUEST['currencytype']) && $_REQUEST['currencytype'] != 'undefined')
			$comp = $_REQUEST['currencytype'];
		else
			$comp = $default;
			
		foreach($currency  as $c) {
			foreach ($default_array as $d) {
				if ($d == $c['abbr'])
					$default_select[] = array($cu['abbr'], $c['type']);
			}
		}
	}
	// Release Notes?
	$q = 'SELECT * FROM catalog_releases ORDER BY id DESC';
	$p = $wadb->prepare($q);
	$p->execute();
	$releases = $p->fetchAll(PDO::FETCH_ASSOC);
	
	$title = 'Exacq Online Product Catalog for exacqVision Video Security Servers and Software | Exacq';
	$meta = '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'
		. '<meta name="description" content="'._("The Exacq Online Catalog lists all the exacqVision products in one place, including video surveillance servers, software, options, accessories, and release notes.").'" />';
	$headerImg = '<img height="100" width="900" src="/catalog/images/product-catalog-banner.png">';
	$links = '<link rel="stylesheet" type="text/css" href="/catalog/css/catalog.css"/>';
	$useNewestJQuery = true;

	include('/var/www/PHPwebsite/olde_header.php');
?>

	<div id="left_content">
		<?php
			$dropdowns = '<div class="category_wrapper"><div class="category_box all" id="all">Full exacqVision Catalog</div></div>';
			foreach ($series_list as $series) {
				$dropdowns .= '<div class="category_wrapper"><div class="category_box series '.strtok($series['name'], ' ').'" id="'.preg_replace('/[^A-Za-z0-9]/', '', $series['name']).'">';
				$dropdowns .= '<span class="arrow">&#9654;</span> '.$series['display_name'].'</div><div class="category_submenu" id="'.preg_replace('/[^A-Za-z0-9]/', '', $series['name']).'_submenu">';
				
				foreach ($cat as $c) {
					if($c['series'] == $series['name']) {
						$dropdowns .= '<span class="category_item '.strtok($series['name'], ' ').'_item" id="'.$c['name'].'">'.$c['display'].'</span>';
					}
				}
				$dropdowns .= '</div></div>';
			}
			$dropdowns .= '<div class="category_wrapper"><div class="category_box notes" id="releases">&#9632;&nbsp; Release Notes</div></div>';
			
			echo $dropdowns;
			
			if ($rep || $dist || $exacq) {
				$levels = array(
					'list' => 'List', 
					'rslr' => '30%'
				);

				if ($exacq) {
					$levels['cert'] = '35%';
					$levels['cpls'] = '40%';
				}
				
				if (!$dist || strpos($discount['discount_c'], "42.5") !== false)
					$levels['dist'] = '42.5%';

				if (strpos($discount['discount_c'], "42.5") === false)
					$levels['dpls'] = '45%';
					
				echo '<select id="exportlevel">';
				foreach ($levels as $key=>$value) {
					if ($key == urldecode(@$_REQUEST['discountlevel']))
						echo '<option value="'.$key.'" selected>Discount: ' . $value . '</option>';
					else
						echo '<option value="'.$key.'">Discount: ' . $value . '</option>';
				}
				echo '</select>';
			}
			
			if ($exacq) {
				echo '<select id="currencytype">';
				foreach ($currency  as $cu) {
					if ($cu['abbr'] == urldecode(@$_REQUEST['currencytype']))
						echo '<option value="'. $cu['abbr'] . '" selected>Currency: ' . $cu['type'] . '</option>';
					else if ($cu['abbr'] == $default && !isset($_REQUEST['currencytype']))
						echo '<option value="'. $cu['abbr'] . '" selected>Currency: ' . $cu['type'] . '</option>';
					else
						echo '<option value="'. $cu['abbr'] . '">Currency: ' . $cu['type'] . '</option>';
				}
				echo '</select><br />';
			} else if (count($default_select) > 1 && $vars['customer_type'] !== 'Authorized') {
				echo '<label style="font-weight: bold; margin-right: 10px;">Pricing Currency:</label><select id="currencytype" style="width: 200px">';
				foreach ($default_select as $cu) {
					if ($cu[0] == urldecode($_REQUEST['currencytype']))
						echo '<option value="'. $cu[0] . '" selected>' . $cu[1] . '</option>';
					else if ($cu[0] == $default && !isset($_REQUEST['currencytype']))
						echo '<option value="'. $cu[0] . '" selected>' . $cu[1] . '</option>';
					else
						echo '<option value="'. $cu[0] . '">' . $cu[1] . '</option>';
				}
				echo '</select><br />';
			} else {
				echo '<input type="hidden" id="currencytype" value="'.$default.'" />';
			}
		?>
	</div>
	<div id="right_content">
		<div id="series_div">
			<img src='images/catalog-main-landing.png' />
			<br />
			<button class='print'>View Full Catalog (PDF)</button>
			<button class='excel'>View Full Catalog (XLS)</button>
		</div>
		<div id="cat_div">
			<div id="category_header"></div>
			<div id="category_buttons">
				<button class="print">Export PDF</button>
				<button class="excel">Export XLS</button>
				<button class="product_page">Product Page</button>
			</div>
			<div id="price_heading">
                             <?php echo isset($vars['headerName']) ? "Discounted prices listed are only available to " . $vars['headerName'] . "." : ""; ?>
			</div>
			<div width="100%" class="ui-corner-all ui-widget-header">
				<div id="category_name"></div>
			</div>
			<div id="category_desc"></div>
			<br />
			<table width="100%" id="product_table"></table>
			<br />
			<div id="linux_available">Linux option available by adding "L" to the end of A-Series and Z-Series part numbers.</div>
			<div id="enterprise_available">Base licenses upgraded to Enterprise by adding "-E" to the end of the part numbers. Available to<br />Select and Elite dealers only.</div>
			<br />
			<div id="options_header" width="100%" class="ui-corner-all ui-widget-header">
				<div id="category_options">Select a category for options.</div>
			</div>
			<div id="category_option_list">
				<table width="100%" id="option_table"></table>
			</div>
			<br />
		</div>
		<div id="notes_div">
			<?php
				echo '<table class="releases">';
				foreach ($releases as $r) {
					echo '<tr><td class="release_date">'.$r['date'].':</h1></td><td class="release_notes">' . $r['notes'] . '</td></tr>';
				}
				echo '</table>';
			?>
		</div>
		<span id="permalink" style="float: right;"></span>
	</div>
	<?php	
		include("/var/www/PHPwebsite/footer.php");
	?>

	<script type="text/javascript" src="js/jquery.jstree.js"></script>
	<script type="text/javascript" src="js/catalog.js"></script>
	<script type="text/javascript">
		var current = "all";
		var discount = "<?php
		if (isset($_REQUEST['discountlevel']))
			echo $_REQUEST['discountlevel'];
		else
			echo $discountlevel;
		
		?>";
		var currency = "<?php echo isset($_REQUEST['currencytype']) ? preg_replace('/<[^>]*>[^<]*<[^>]*>/','',$_REQUEST['currencytype']) : $default; ?>";
		var status = <?php 
			if ($authenticated === true)
				echo "1";
			else
				echo "0";
		?>;
		var permalink = "<?php echo isset($permalink) ? preg_replace('/<[^>]*>[^<]*<[^>]*>/','',$permalink) : 'all'; ?>";
	</script>
