<?php

function convertCurrency($amount, $from, $to) {

    // ?? FORCE UPPERCASE
    $from = strtoupper($from);
    $to   = strtoupper($to);

    // ? SAME CURRENCY ? NO CONVERSION
    if ($from === $to) {
        return round($amount, 2);
    }

    // ?? ALLOWED CURRENCIES (IMPORTANT)
    $allowed = ["USD","ZAR","NGN","EUR","GBP","CHF","CAD","AUD","INR"];

    if (!in_array($to, $allowed)) {
        return "INVALID ($to)";
    }

    // ?? CACHE
    $cache_file = __DIR__ . "/currency_cache_{$from}.json";
    $cache_time = 60 * 60; // 1 hour

    // ? USE CACHE
    if (file_exists($cache_file) && (time() - filemtime($cache_file)) < $cache_time) {
        $data = json_decode(file_get_contents($cache_file), true);
    } else {

        // ?? API REQUEST
        $url = "https://api.exchangerate-api.com/v4/latest/$from";
        $response = @file_get_contents($url);

        if ($response !== false) {
            file_put_contents($cache_file, $response);
            $data = json_decode($response, true);
        } else {
            return "API ERROR";
        }
    }

    // ? INVALID RATE
    if (!isset($data['rates'][$to])) {
        return "RATE NOT FOUND ($to)";
    }

    $rate = $data['rates'][$to];

    return round($amount * $rate, 2);
}