<?php
include '../managers/dbconn.php';

function splitSetitem_id($item_id) {
	if (strpos($item_id, '+') === false) {
		return null;
	}

	$parts = explode('+', $item_id, 2);
	$first = trim($parts[0]);
	$second = trim($parts[1]);

	$prefix = '';
	$first_numeric = $first;
	if (preg_match('/^([^0-9]{1,2})(.*)$/', $first, $matches)) {
		$prefix = $matches[1];
		$first_numeric = $matches[2];
	} else {
		$first_numeric = (string)intval($first);
	}

	$item1 = $prefix . $first_numeric;

	$second_numeric = $second;
	if ($prefix === '') {
		$second_numeric = (string)intval($second);
	}
	$item2 = $prefix . $second_numeric;

	return ['item1' => $item1, 'item2' => $item2];
}

$format = isset($_GET['format']) ? strtolower($_GET['format']) : 'json';
$itemIdFilter = isset($_GET['item_id']) ? trim($_GET['item_id']) : null;

$sql = "SELECT s.item_id, s.saleable_quantity
FROM statistics_daily s
INNER JOIN pr_parameters p ON s.item_id = p.item_id
WHERE p.data_status IN (1, -1)
";

$result = $conn->query($sql);

if (!$result) {
	die('Lekérdezési hiba: ' . $conn->error);
}

$data = [];
$dataMap = [];

while ($row = $result->fetch_assoc()) {
	$data[] = $row;
	$dataMap[$row['item_id']] = $row['saleable_quantity'];
}

if ($itemIdFilter !== null) {
	$data = array_filter($data, function($row) use ($itemIdFilter) {
		return $row['item_id'] === $itemIdFilter;
	});
	$data = array_values($data);
}

switch ($format) {
	case 'csv':
		header('Content-Type: text/csv; charset=utf-8');
		header('Content-Disposition: attachment; filename="export.csv"');
		$output = fopen('php://output', 'w');
		if (!empty($data)) {
			fputcsv($output, array_keys($data[0]));
			foreach ($data as $row) {
				fputcsv($output, $row);
			}
		}
		fclose($output);
		break;

	case 'xml':
		header('Content-Type: application/xml; charset=utf-8');
		$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><items/>');
		foreach ($data as $row) {
			$item = $xml->addChild('item');
			foreach ($row as $key => $value) {
				$item->addChild($key, htmlspecialchars($value));
			}
		}
		echo $xml->asXML();
		break;

	case 'json':
	default:
		header('Content-Type: application/json; charset=utf-8');
		echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
		break;
}

$conn->close();
?>
