<?php
use \sven\sys\core as CORE;
CORE::setLogin(true);
CORE::addReplacement('head', 'TITLE', 'ABC/XYZ Analyse');

$mysql = new \sven\sys\mysql\mysql();
$fluent = $mysql->getBuilder();


function lastElement($array) {return end($array);}


$options = "";
if($auth->loggedIn()) {
	$query_2 = $fluent->from('t_artikel')->select('t_artikel.Name, t_artikel.ID');
	$rows_2 = $query_2->fetchAll();
	$names = [];
	foreach ($rows_2 as $id => $row) {
		$names[$row->ID] = $row->Name;
	}

	$query = $fluent->from('t_verkaufszahlen')->select('t_verkaufszahlen.*');
	$rows = $query->fetchAll();

	$data = [
		'abc' => [
			'mengen' => [],
			'werte' =>  []
		],
		'xyz' => [],
		'sorted_abc' => [0 => [], 1 => [], 2 => []],
		'sorted_xyz' => [0 => [], 1 => [], 2 => []]
	];
	$output = "";
	foreach ($rows as $id => $row) {
		if($id > 0) $data['abc']['mengen'][$id] = [ ($row->Menge+$data['abc']['mengen'][$id-1][0]), $row->f_Artikel_ID];
		else $data['abc']['mengen'][$id] = [$row->Menge+0, $row->f_Artikel_ID];

		if($id > 0) $data['abc']['werte'][$id] = [($row->Verkaufspreis+$data['abc']['werte'][$id-1][0]), $row->f_Artikel_ID];
		else $data['abc']['werte'][$id] = [$row->Verkaufspreis+0, $row->f_Artikel_ID];

		$output .= "<tr>";
			$output .="<td>{$names[$data['abc']['mengen'][$id][1]]}</td>";
			$output .="<td>{$data['abc']['mengen'][$id][0]}</td>";
			$output .="<td>{$data['abc']['werte'][$id][0]}</td>";
		$output .="</tr>";
	}
	
	// ABC Zuordnung
	foreach ($data['abc']['mengen'] as $key => $value) {
		$value = $data['abc']['werte'][$key][0] / lastElement($data['abc']['werte'])[0];

		//var_dump([$value > 0.8, 0.8 < $value && $value > 0.95, 0.95 < $value]);
		if($value > 0.95) array_push($data['sorted_abc'][2], $names[$data['abc']['werte'][$key][1]]);
		else if(0.8 > $value && $value < 0.95) array_push($data['sorted_abc'][1], $names[$data['abc']['werte'][$key][1]]);
		else if($value < 0.8) array_push($data['sorted_abc'][0], $names[$data['abc']['werte'][$key][1]]);
		//var_dump($value);
	}
	$XA = var_export($data['sorted_abc'][0], true);
	$XB = var_export($data['sorted_abc'][1], true);
	$XC = var_export($data['sorted_abc'][2], true);

	$YA = "";
	$YB = "";
	$YC = "";

	$ZA = "";
	$ZB = "";
	$ZC = "";
}

CORE::addReplacement('main', 'FILE', <<<EOF
<div class="container" id="calc-page">
				<div class="row">
					<div class="col-md-12">
						<h2>ABC/XYZ Analyse</h2>
						<table>
							<thead>
								<tr>
									<td>Verbrauchsmenge</td>
									<td>A</td>
									<td>B</td>
									<td>C</td>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td>X</td>
									<td>{$XA}</td>
									<td>{$XB}</td>
									<td>{$XC}</td>
								</tr>
								<tr>
									<td>Y</td>
									<td>{$YA}</td>
									<td>{$YB}</td>
									<td>{$YC}</td>
								</tr>
								<tr>
									<td>Z</td>
									<td>{$ZA}</td>
									<td>{$ZB}</td>
									<td>{$ZC}</td>
								</tr>
							</tbody>
						</table>
					</div>
				</div>
			</div>
EOF
);
?>
