<?php
// execute/aktien-scanner/export_seasonal.php
// Export der saisonalen Ergebnisse als JSON/CSV/PDF

// === Bootstrap / DB ===
declare(strict_types=1);
header('X-Content-Type-Options: nosniff');

$METHODS_DEFAULT = ['saisonalitaet100'];
$table = 'saisonaleTable';

require_once __DIR__ . '/../../engine/engine.php';
$pdo = null;
	if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
	$pdo = $GLOBALS['pdo'];
} elseif (function_exists('db')) {
	$pdo = db();
}
if (!$pdo instanceof PDO) {
	http_response_code(500);
	echo 'DB connection not available';
exit;
}

// === Input ===
$format = strtolower($_GET['format'] ?? 'json');
$scanId = trim((string)($_GET['scan_id'] ?? ''));
$methodStr = trim((string)($_GET['method'] ?? ''));
$methods = $methodStr !== '' ? array_filter(array_map('trim', explode(',', $methodStr))) : $METHODS_DEFAULT;
if (empty($methods)) $methods = $METHODS_DEFAULT;

// === Query ===
$params = $methods;
$where = 'WHERE method IN (' . implode(',', array_fill(0, count($methods), '?')) . ')';
if ($scanId !== '') {
	$where .= ' AND scan_id = ?';
	$params[] = $scanId;
}
$sql = "SELECT id, ticker, name, exchange, score, method, created_at FROM {$table} {$where} ORDER BY score DESC, created_at DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

// === Dateiname ===
$stamp = date('Ymd_His');
$base = 'seasonal_results_' . $stamp;

switch ($format) {
	case 'json':
	header('Content-Type: application/json; charset=utf-8');
	header('Content-Disposition: attachment; filename="' . $base . '.json"');
	echo json_encode($rows, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
	break;
	
	case 'csv':
	header('Content-Type: text/csv; charset=utf-8');
	header('Content-Disposition: attachment; filename="' . $base . '.csv"');
}