<?php

require_once __DIR__ . '/../../core/config.php';
require_once __DIR__ . '/../../core/session.php';
require_once __DIR__ . '/../../core/database.php';
require_once __DIR__ . '/../../core/auth.php';
require_once __DIR__ . '/../../core/permissions.php';
require_once __DIR__ . '/../../services/finance/ExchangeRateService.php';

require_login();
csrf_require_valid_request();
header('Content-Type: application/json; charset=utf-8');

if (!user_can('module.billing') && !user_can('billing.prepare') && !user_can('billing.manual.prepare') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success' => false, 'message' => 'No tienes permisos para consultar tipos de cambio.'));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(array('success' => false, 'message' => 'Método no permitido.'));
    exit;
}

try {
    $currency = strtoupper(trim((string)($_POST['currency_code'] ?? 'USD')));
    $date = trim((string)($_POST['date'] ?? $_POST['issue_date'] ?? date('Y-m-d')));
    $service = new ExchangeRateService(db());
    $result = $service->resolve($currency, $date, true, 7);
    if (empty($result['ok'])) {
        http_response_code(422);
        echo json_encode(array('success' => false, 'message' => $result['message'] ?? 'No fue posible resolver el tipo de cambio.', 'result' => $result), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
    echo json_encode(array('success' => true, 'result' => $result), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(400);
    echo json_encode(array('success' => false, 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
