<?php
require_once '../../engine/engine.php';

header('Content-Type: application/json');
header('Content-Disposition: attachment; filename="scan_results.json"');

// Bewertungsmethode aus URL übernehmen (optional)
$method = $_GET['method'] ?? null;

$params = [];
$methodFilterSQL = "";

if ($method) {
    $methodFilterSQL = "WHERE sm.method = :method";
    $params['method'] = $method;
}

// Nur neueste Einträge pro Ticker (aus letzter Bewertung)
$sql = "
    SELECT r.ticker, r.name, r.score
    FROM scan_results r
    JOIN scan_meta sm ON r.scan_id = sm.scan_id
    JOIN (
        SELECT ticker, MAX(id) AS max_id
        FROM scan_results
        GROUP BY ticker
    ) latest ON r.id = latest.max_id
    $methodFilterSQL
    ORDER BY r.name
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rawResults = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Felder umbenennen
$results = array_map(function($row) {
    return [
        'Code' => $row['ticker'],
        'Name' => $row['name'],
        'Score' => $row['score']
    ];
}, $rawResults);

echo json_encode($results, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
exit;
