<?php

/**
 * @param id_telboxes
 * @param id_companies
 */
function DEALS_SALES() {

	$id_telboxes  = V::get('id_telboxes', '', $_REQUEST);
	$id_companies = V::get('id_companies', '', $_REQUEST, 'int');
	$task = V::get('_task', '', $_REQUEST);
	switch ($task) {
		case 'TYPESPECIAL': {
			$DBG = ('1' == V::get('DBG', '', $_REQUEST));
			header("Content-type: application/json");

			$fld = V::get('fld', '', $_GET);
			switch ($fld) {
				case 'id_telboxes': {
						Lib::loadClass('TypespecialVariable');
						$typeSpecialTelboxes = TypespecialVariable::getInstance(-1, '__TELBOXES_NAME');

						$query = V::get('q', '', $_REQUEST);
						$rawRows = null;
						$rows = $typeSpecialTelboxes->getValuesWithExports($query);
						if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">rows('.$query.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($rows);echo'</pre>';}
						foreach ($rows as $kID => $vItem) {
							$itemJson = new stdClass();
							$itemJson->id = $vItem->id;
							$itemJson->name = $vItem->param_out;
							if (!empty($vItem->exports)) {
								$itemJson->exports = $vItem->exports;
							}
							$jsonData[] = $itemJson;
						}
						echo json_encode($jsonData);
					}
					break;
				case 'id_companies': {
						Lib::loadClass('TypespecialVariable');
						$typeSpecialCompanies = TypespecialVariable::getInstance(-1, '__COMPANIES');

						$query = V::get('q', '', $_REQUEST);
						$rawRows = null;
						$rows = $typeSpecialCompanies->getValuesWithExports($query);
						if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">rows('.$query.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($rows);echo'</pre>';}
						foreach ($rows as $kID => $vItem) {
							$itemJson = new stdClass();
							$itemJson->id = $vItem->id;
							$itemJson->name = $vItem->param_out;
							if (!empty($vItem->exports)) {
								$itemJson->exports = $vItem->exports;
							}
							$jsonData[] = $itemJson;
						}
						echo json_encode($jsonData);
					}
					break;
			}
			exit;
		}
	}

	SE_Layout::menu();

	Lib::loadClass('TypespecialVariable');
	$typeSpecialTelboxes  = TypespecialVariable::getInstance(-1, '__TELBOXES_NAME');
	$typeSpecialCompanies = null;// TypespecialVariable::getInstance(-1, '__COMPANIES');

	$obroty = array();
	if (!empty($id_telboxes) || $id_companies > 0) {
		$db = DB::getDB();
		$sqlWhere = array();
		//if (!empty($id_telboxes))  $sqlWhere[] = " d.`T_TELBOX_NEIGHBOUR_IN`='{$id_telboxes}' ";
		if (!empty($id_telboxes))  $sqlWhere[] = " o.`T_TELBOX_NEIGHBOUR_IN`='{$id_telboxes}' ";
		//if ($id_companies > 0) $sqlWhere[] = " d.`ID_BILLING_USERS`='{$id_companies}' ";
		$sqlWhere = (!empty($sqlWhere))? implode(" or ", $sqlWhere) : '';
		$sql = "select o.`ID`
				-- , d.`T_TELBOX_NEIGHBOUR_IN`
				, o.`T_TELBOX_NEIGHBOUR_IN`
				, o.`ID_DEALS_TABLE`
				, o.`SALES_DATE`
				, o.`SALES_VALUE`
			from `DEALS_SALES` as o
				-- join `DEALS_TABLE` as d on (d.`ID`=o.`ID_DEALS_TABLE`)
			where
				{$sqlWhere}
		";
		if(V::get('DBG','',$_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$year  = substr($r->SALES_DATE, 0, 4);
			$month = substr($r->SALES_DATE, 5, 2);
			$obroty[$r->ID_DEALS_TABLE][$year][$month] = $r->SALES_VALUE;
		}
	}

	$monthsOut = array();
	for ($i = 0; $i < 12; $i++) $monthsOut[] = sprintf("%02d", $i + 1);

	?>

	<div class="container-fluid">

	<form action="" method="GET" class="form-inline">
	<table>
<!--
	<summary>Wybierz lokal i/lub firmę w celu przeglądania obrotów </summary>
-->
	<thead>
		<tr>
			<th style="text-align:left">Lokal</th>
			<th style="text-align:left">
				<?php if ($typeSpecialCompanies) : ?>
					Firma
				<?php endif; ?>
			</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>
				<?php if ($typeSpecialTelboxes) : ?>
					<?php
						$fName = 'id_telboxes';
						$fldParams = array();
						$fldParams['allowCreate'] = false;
						$fldParams['ajaxDataUrlBase'] = "index.php?FUNCTION_INIT=" . __FUNCTION__ . "&HEADER_NOT_INIT=YES&_task=TYPESPECIAL&fld={$fName}";
						//$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
						echo $typeSpecialTelboxes->showFormItem($tblID = -1, $fName, $selValue = $id_telboxes, $fldParams);
					?>
				<?php endif; ?>
			</td>
			<td>
				<?php if ($typeSpecialCompanies) : ?>
						<?php
							$fName = 'id_companies';
							$fldParams = array();
							$fldParams['allowCreate'] = false;
							$fldParams['ajaxDataUrlBase'] = "index.php?FUNCTION_INIT=" . __FUNCTION__ . "&HEADER_NOT_INIT=YES&_task=TYPESPECIAL&fld={$fName}";
							//$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
							echo $typeSpecialCompanies->showFormItem($tblID = -1, $fName, $selValue = $id_companies, $fldParams);
						?>
				<?php endif; ?>
			</td>
		</tr>
		<tr>
			<td clspan="2">
				<button class="btn">wybierz</button>
			</td>
		</tr>
	</tbody>
	</table>
	</form>

	<?php if (empty($obroty)) : ?>
		
	<?php else : ?>
		<table class="table table-bordered table-hover">
			<thead>
				<th></th>
				<?php foreach ($monthsOut as $vMonth) : ?>
					<th><?php echo $vMonth; ?></th>
				<?php endforeach; ?>
				<th>suma</th>
			</thead>
		<?php foreach ($obroty as $kComId => $vSalesByYear) : ?>
			<?php krsort($vSalesByYear); foreach ($vSalesByYear as $kYearId => $vSalesByMonth) : ?>
				<tr>
					<th><?php echo $kYearId; ?></th>
					<?php $sumaYear = 0; foreach ($monthsOut as $vMonth) : ?>
						<td>
							<?php if (isset($vSalesByMonth[$vMonth])) : ?>
								<?php $sumaYear += $vSalesByMonth[$vMonth]; ?>
								<nobr><?php echo number_format($vSalesByMonth[$vMonth], 2, ',', ' '); ?></nobr>
							<?php else : ?>
								...
							<?php endif; ?>
						</td>
					<?php endforeach; ?>
					<td><nobr><?php echo number_format($sumaYear, 2, ',', ' '); ?></nobr></td>
				</tr>
			<?php endforeach; ?>
		<?php endforeach; ?>
		</table>

		<script src="stuff/RGraph/libraries/RGraph.common.core.js"></script>
		<script src="stuff/RGraph/libraries/RGraph.common.dynamic.js"></script>
		<script src="stuff/RGraph/libraries/RGraph.common.key.js"></script>
		<script src="stuff/RGraph/libraries/RGraph.drawing.rect.js"></script>
		<script src="stuff/RGraph/libraries/RGraph.common.tooltips.js"></script>
		<script src="stuff/RGraph/libraries/RGraph.bar.js"></script>
		<script src="stuff/RGraph/libraries/RGraph.line.js"></script>

<!--

<?php
	$wykresWidth = 940;
	$jsonLabels = array();
	$jsonColors = array();
	$jsonData = array();
	$jsonTooltips = array();

	$jsonColors = array('Gradient(#fe783e:#EC561B:#F59F7D)', 'Gradient(#99f:#27afe9:#058DC7:#058DC7)', 'Gradient(#94f776:#50B332:#B1E59F)', 'Gradient(#CC76F7:#8832B3:#CE9FE5)', 'Gradient(#768CF7:#3247B3:#9FABE5)', 'Gradient(#F77681:#B3323C:#E59FA5)');
	$vSalesByYear = reset($obroty);// only first company
	krsort($vSalesByYear);
	foreach ($vSalesByYear as $kYearId => $vSalesByMonth) {
		$jsonYearData = array();
		foreach ($monthsOut as $vMonth) {
			if (isset($vSalesByMonth[$vMonth])) {
				$jsonYearData["{$kYearId}-{$vMonth}"] = (float)str_replace('.', ',', $vSalesByMonth[$vMonth]);
			} else {
				$jsonYearData["{$kYearId}-{$vMonth}"] = 0;
			}
		}
		$jsonYearData = array_reverse($jsonYearData);
		//$jsonData[] = array_values($jsonYearData);
		foreach ($jsonYearData as $kLabel => $vValue) {
			$jsonLabels[] = $kLabel;
			$jsonData[]   = $vValue;
			$jsonTooltips[] = "Obrót " . number_format($vValue, 2, ',', ' ') . " w {$kLabel}";
		}
	}

	$wykresMinItemWidth = 30;
	$wykresTestWidth = count(array_keys($vSalesByYear)) * 12 * $wykresMinItemWidth;
	if ($wykresTestWidth > $wykresWidth - 60 - 20) {
		$wykresWidth = $wykresTestWidth + 60 + 20;
	}
?>
	<div style="width:100%; margin:10px 0; border:1px solid gray; overflow:auto">
		<canvas id="wykres1" width="<?php echo $wykresWidth; ?>" height="300">[No canvas support]</canvas>
	</div>
		<script>
jQuery(document).ready(function(){
//			.Set('hmargin', 0)
		var bar = new RGraph.Bar('wykres1', <?php echo json_encode($jsonData); ?>)
			.Set('labels', <?php echo json_encode($jsonLabels); ?>)
			.Set('colors', <?php echo json_encode($jsonColors); ?>)
			.Set('strokestyle', 'white')
			.Set('linewidth', 1)
			.Set('shadow', true)
			.Set('shadow.color', '#ccc')
			.Set('shadow.offsetx', 0)
			.Set('shadow.offsety', 0)
			.Set('shadow.blur', 10)
//			.Set('gutter.right', 20)
			.Set('gutter.bottom', 60)
			.Set('gutter.left', 60)
			.Set('text.angle', 90)
			.Set('tooltips', RGraph.ISOLD ? null : <?php echo json_encode($jsonTooltips); ?>)
			.Set('tooltips.event', 'mousemove')
			.Set('labels.above', true)
			.Draw();
});
		</script>


<?php
	$wykresWidth = 940;
	$jsonLabels = array();
	$jsonColors = array();
	$jsonData = array();
	$jsonTooltips = array();

	$jsonColors = array('Gradient(#fe783e:#EC561B:#F59F7D)', 'Gradient(#99f:#27afe9:#058DC7:#058DC7)', 'Gradient(#94f776:#50B332:#B1E59F)', 'Gradient(#CC76F7:#8832B3:#CE9FE5)', 'Gradient(#768CF7:#3247B3:#9FABE5)', 'Gradient(#F77681:#B3323C:#E59FA5)');
	$vSalesByYear = reset($obroty);// only first company
	krsort($vSalesByYear);
	foreach ($monthsOut as $vMonth) {
		$jsonYearData = array();
		foreach ($vSalesByYear as $kYearId => $vSalesByMonth) {
			if (isset($vSalesByMonth[$vMonth])) {
				$jsonYearData["{$kYearId}-{$vMonth}"] = (float)str_replace('.', ',', $vSalesByMonth[$vMonth]);
			} else {
				$jsonYearData["{$kYearId}-{$vMonth}"] = 0;
			}
		}

		//$jsonYearData = array_reverse($jsonYearData);
		//$jsonData[] = array_values($jsonYearData);
		foreach ($jsonYearData as $kLabel => $vValue) {
			$jsonLabels[] = $kLabel;
			$jsonData[]   = $vValue;
			$jsonTooltips[] = "Obrót " . number_format($vValue, 2, ',', ' ') . " w {$kLabel}";
		}
	}

	$wykresMinItemWidth = 30;
	$wykresTestWidth = count(array_keys($vSalesByYear)) * 12 * $wykresMinItemWidth;
	if ($wykresTestWidth > $wykresWidth - 60 - 20) {
		$wykresWidth = $wykresTestWidth + 60 + 20;
	}
?>
	<div style="width:100%; margin:10px 0; border:1px solid gray; overflow:auto">
		<canvas id="wykres2" width="<?php echo $wykresWidth; ?>" height="300">[No canvas support]</canvas>
	</div>
		<script>
jQuery(document).ready(function(){
//			.Set('hmargin', 15)
		var bar = new RGraph.Bar('wykres2', <?php echo json_encode($jsonData); ?>)
			.Set('labels', <?php echo json_encode($jsonLabels); ?>)
			.Set('colors', <?php echo json_encode($jsonColors); ?>)
			.Set('strokestyle', 'white')
			.Set('linewidth', 1)
			.Set('shadow', true)
			.Set('shadow.color', '#ccc')
			.Set('shadow.offsetx', 0)
			.Set('shadow.offsety', 0)
			.Set('shadow.blur', 10)
//			.Set('gutter.right', 20)
			.Set('gutter.bottom', 60)
			.Set('gutter.left', 60)
			.Set('text.angle', 90)
			.Set('tooltips', RGraph.ISOLD ? null : <?php echo json_encode($jsonTooltips); ?>)
			.Set('tooltips.event', 'mousemove')
			.Set('labels.above', true)
			.Draw();
});
		</script>
-->

<?php
	$wykresWidth = 940;
	$jsonLabels = array();
	$jsonColors = array();
	$jsonData = array();
	$jsonTooltips = array();

	$jsonColors = array('Gradient(#fe783e:#EC561B:#F59F7D)', 'Gradient(#99f:#27afe9:#058DC7:#058DC7)', 'Gradient(#94f776:#50B332:#B1E59F)', 'Gradient(#CC76F7:#8832B3:#CE9FE5)', 'Gradient(#768CF7:#3247B3:#9FABE5)', 'Gradient(#F77681:#B3323C:#E59FA5)');
	$vSalesByYear = reset($obroty);// only first company
	ksort($vSalesByYear);
	foreach ($vSalesByYear as $kYearId => $vSalesByMonth) {
		$jsonYearData = array();
		foreach ($monthsOut as $vMonth) {
			if (isset($vSalesByMonth[$vMonth])) {
				$jsonYearData["{$kYearId}-{$vMonth}"] = (float)str_replace('.', ',', $vSalesByMonth[$vMonth]);
			} else {
				$jsonYearData["{$kYearId}-{$vMonth}"] = 0;
			}
		}
		//$jsonYearData = array_reverse($jsonYearData);
		//$jsonData[] = array_values($jsonYearData);
		foreach ($jsonYearData as $kLabel => $vValue) {
			$jsonLabels[] = $kLabel;
		//	$jsonData[]   = $vValue;
			$jsonTooltips[] = "Obrót " . number_format($vValue, 2, ',', ' ') . " w {$kLabel}";
		}
		$jsonData[] = array_values($jsonYearData);
	}

	$wykresMinItemWidth = 20;
	$wykresTestWidth = count(array_keys($vSalesByYear)) * 12 * $wykresMinItemWidth;
	if ($wykresTestWidth > $wykresWidth - 60 - 20) {
		$wykresWidth = $wykresTestWidth + 60 + 20;
	}
	$jsonLabels = array_keys($vSalesByYear);
	$jsonColorsAll = array();
	for ($i = 0, $mi = 0, $mc = count($jsonColors); $i < 12; $i++) {
		$jsonColorsAll[] = $jsonColors[$mi];
		if (++$mi >= $mc) {
			$mi = 0;
		}
	}
	$jsonColors = $jsonColorsAll;
?>
	<div style="width:100%; margin:10px 0; border:1px solid gray; overflow:auto">
		<canvas id="wykres3" width="<?php echo $wykresWidth; ?>" height="300">[No canvas support]</canvas>
	</div>
		<script>
jQuery(document).ready(function(){
//			.Set('hmargin', 0)
		var bar = new RGraph.Bar('wykres3', <?php echo json_encode($jsonData); ?>)
			.Set('labels', <?php echo json_encode($jsonLabels); ?>)
			.Set('colors', <?php echo json_encode($jsonColors); ?>)
			.Set('strokestyle', 'white')
			.Set('linewidth', 1)
			.Set('shadow', true)
			.Set('shadow.color', '#ccc')
			.Set('shadow.offsetx', 0)
			.Set('shadow.offsety', 0)
			.Set('shadow.blur', 10)
//			.Set('gutter.right', 20)
			.Set('gutter.bottom', 30)
			.Set('gutter.left', 60)
//			.Set('text.angle', 90)
			.Set('tooltips', RGraph.ISOLD ? null : <?php echo json_encode($jsonTooltips); ?>)
			.Set('tooltips.event', 'mousemove')
			.Set('labels.above', true)
			.Set('hmargin', 20)
			.Draw();
});
		</script>


<?php
	$wykresWidth = 940;
	$jsonLabels = array();
	$jsonColors = array();
	$jsonData = array();
	$jsonTooltips = array();

	$jsonColors = array('Gradient(#fe783e:#EC561B:#F59F7D)', 'Gradient(#99f:#27afe9:#058DC7:#058DC7)', 'Gradient(#94f776:#50B332:#B1E59F)', 'Gradient(#CC76F7:#8832B3:#CE9FE5)', 'Gradient(#768CF7:#3247B3:#9FABE5)', 'Gradient(#F77681:#B3323C:#E59FA5)');
	$vSalesByYear = reset($obroty);// only first company
	ksort($vSalesByYear);
	foreach ($monthsOut as $vMonth) {
		$jsonYearData = array();
		foreach ($vSalesByYear as $kYearId => $vSalesByMonth) {
			if (isset($vSalesByMonth[$vMonth])) {
				$jsonYearData["{$kYearId}-{$vMonth}"] = (float)str_replace('.', ',', $vSalesByMonth[$vMonth]);
			} else {
				$jsonYearData["{$kYearId}-{$vMonth}"] = 0;
			}
		}

		//$jsonYearData = array_reverse($jsonYearData);
		//$jsonData[] = array_values($jsonYearData);
		foreach ($jsonYearData as $kLabel => $vValue) {
			$jsonLabels[] = $kLabel;
			$jsonTooltips[] = "Obrót " . number_format($vValue, 2, ',', ' ') . " w {$kLabel}";
		}
		$jsonData[] = array_values($jsonYearData);
	}

	$wykresMinItemWidth = 20;
	$wykresTestWidth = count(array_keys($vSalesByYear)) * 12 * $wykresMinItemWidth;
	if ($wykresTestWidth > $wykresWidth - 60 - 20) {
		$wykresWidth = $wykresTestWidth + 60 + 20;
	}
	$jsonLabels = array('styczeń','luty','marzec','kwiecień','maj','czerwiec','lipiec','sierpień','wrzesień','październik','listopad','grudzień');
	$jsonColorsAll = array();
	for ($i = 0, $mi = 0, $mc = count($jsonColors); $i < count($jsonData); $i++) {
		$jsonColorsAll[] = $jsonColors[$mi];
		if (++$mi >= $mc) {
			$mi = 0;
		}
	}
	$jsonColors = $jsonColorsAll;
?>
	<div style="width:100%; margin:10px 0; border:1px solid gray; overflow:auto">
		<canvas id="wykres4" width="<?php echo $wykresWidth; ?>" height="300">[No canvas support]</canvas>
	</div>
		<script>
jQuery(document).ready(function(){
//			.Set('hmargin', 15)
		var bar = new RGraph.Bar('wykres4', <?php echo json_encode($jsonData); ?>)
			.Set('labels', <?php echo json_encode($jsonLabels); ?>)
			.Set('colors', <?php echo json_encode($jsonColors); ?>)
			.Set('strokestyle', 'white')
			.Set('linewidth', 1)
			.Set('shadow', true)
			.Set('shadow.color', '#ccc')
			.Set('shadow.offsetx', 0)
			.Set('shadow.offsety', 0)
			.Set('shadow.blur', 10)
//			.Set('gutter.right', 20)
			.Set('gutter.bottom', 30)
			.Set('gutter.left', 60)
//			.Set('text.angle', 90)
			.Set('tooltips', RGraph.ISOLD ? null : <?php echo json_encode($jsonTooltips); ?>)
			.Set('tooltips.event', 'mousemove')
			.Set('labels.above', true)
			.Set('hmargin', 20)
			.Draw();
});
		</script>

	<?php endif; ?>

	</div>
	<?php
}
