<?php
/**
 * GET /api/bnr-rate.php?date=YYYY-MM-DD&currency=EUR
 *
 * Cursul de referință BNR pentru ziua cerută. Doar citire (date publice),
 * de aceea nu cere CSRF. Poate primi mai multe monede: currency=EUR,USD
 */
require_once __DIR__ . '/../includes/orders.php';
require_once __DIR__ . '/../includes/bnr.php';

$date = trim((string)($_GET['date'] ?? ''));
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) $date = date('Y-m-d');

$wanted = array_filter(array_map(
    fn($c) => strtoupper(trim($c)),
    explode(',', (string)($_GET['currency'] ?? 'EUR'))
));
if (!$wanted) $wanted = ['EUR'];
$wanted = array_slice(array_unique($wanted), 0, 5);

try {
    $rates = [];
    foreach ($wanted as $cur) {
        $r = bnr_rate($date, $cur);
        if ($r) $rates[$cur] = $r;
    }
    json_response(['ok' => true, 'date' => $date, 'rates' => $rates]);
} catch (Throwable $ex) {
    error_log('[bnr-rate] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => $ex->getMessage()], 500);
}
