<?php
require_once 'config.php';

/**
 * SAC 2025 - SAVE EXCHANGE RATE BATCH
 * Sincroniza masivamente el historial de tasas.
 */

checkAccess(['admin', 'programmer', 'board']);

$data = json_decode(file_get_contents("php://input"), true);

if (!$data || !isset($data['rates']) || !is_array($data['rates'])) {
    response(["error" => "Lote de datos inválido"], 400);
}

try {
    $pdo->beginTransaction();

    $sql = "INSERT INTO exchange_rates (date, am_value, pm_value, parallel_value) 
            VALUES (:date, :am, :pm, :parallel) 
            ON DUPLICATE KEY UPDATE am_value = :am_upd, pm_value = :pm_upd, parallel_value = :parallel_upd";
    $stmt = $pdo->prepare($sql);

    $count = 0;
    foreach ($data['rates'] as $rate) {
        if (!isset($rate['date'])) continue;

        $date = trim($rate['date']);
        // Validar formato fecha antes de insertar
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) continue;

        $am = round((float)($rate['amValue'] ?? 0), 2);
        $pm = round((float)($rate['pmValue'] ?? 0), 2);
        $parallel = round((float)($rate['parallelValue'] ?? $pm), 2);

        $stmt->execute([
            ':date' => $date,
            ':am' => $am,
            ':pm' => $pm,
            ':parallel' => $parallel,
            ':am_upd' => $am,
            ':pm_upd' => $pm,
            ':parallel_upd' => $parallel
        ]);
        $count++;
    }

    $pdo->commit();
    response(["success" => true, "count" => $count]);

} catch (PDOException $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    response(["error" => "Error interno al procesar el lote: " . $e->getMessage()], 500);
}
?>