<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');

require_once '../../engine/engine.php';

// === Parameter auslesen ===
$scanId = $_GET['scan_id'] ?? '';
$hasScanId = $scanId && preg_match('/^scan_/', $scanId);
$searchValue = trim($_GET['search']['value'] ?? '');
$draw = intval($_GET['draw'] ?? 1);
$start = intval($_GET['start'] ?? 0);
$length = intval($_GET['length'] ?? 50);
$orderColumnIndex = intval($_GET['order'][0]['column'] ?? 0);
$orderDir = ($_GET['order'][0]['dir'] ?? 'asc') === 'desc' ? 'DESC' : 'ASC';

// === Spaltenmapping ===
$columns = ['ticker', 'name', 'exchange', 'score', 'method', 'created_at', 'id'];
$orderColumn = $columns[$orderColumnIndex] ?? 'created_at';

// === WHERE-Bedingung dynamisch aufbauen ===
$whereParts = [];
$params = [];

if ($hasScanId) {
	$params[':scan_id'] = trim((string)$scanId);
	$whereParts[] = 'scan_id = :scan_id';
}
if ($searchValue !== '') {
	$params[':search'] = "%$searchValue%";
	$whereParts[] = "(ticker LIKE :search OR name LIKE :search OR method LIKE :search)";
}

$whereClause = !empty($whereParts) ? 'WHERE ' . implode(' AND ', $whereParts) : '';

try {
	// === Anzahl aller Ergebnisse ohne Filter ===
	$totalStmt = $pdo->query("SELECT COUNT(*) FROM scan_results");
	$totalCount = (int)$totalStmt->fetchColumn();

	// === Anzahl gefilterter Ergebnisse ===
	$countFilteredStmt = $pdo->prepare("SELECT COUNT(*) FROM scan_results $whereClause");
	$countFilteredStmt->execute($params);
	$filteredCount = (int)$countFilteredStmt->fetchColumn();

	// === Datenabfrage mit Limit + Sortierung ===
	$dataStmt = $pdo->prepare("SELECT id, ticker, name, exchange, score, method, created_at
		FROM scan_results
		$whereClause
		ORDER BY $orderColumn $orderDir
		LIMIT :start, :length");
	$dataStmt->bindValue(':start', $start, PDO::PARAM_INT);
	$dataStmt->bindValue(':length', $length, PDO::PARAM_INT);
	foreach ($params as $key => $val) {
		$dataStmt->bindValue($key, $val);
	}
	$dataStmt->execute();
	$data = $dataStmt->fetchAll(PDO::FETCH_ASSOC);

	if (json_last_error() !== JSON_ERROR_NONE) {
		echo json_last_error_msg();
		exit;
	}

	echo json_encode([
		'draw' => $draw,
		'recordsTotal' => $filteredCount,
		'recordsTotalGlobal' => $totalCount,
		'recordsFiltered' => $filteredCount,
		'data' => $data
	]);
} catch (Throwable $e) {
	http_response_code(500);
	echo json_encode(['error' => $e->getMessage()]);
	exit;
}