<?php
/**
 * Mini-projet 02 — Convertisseur Universel
 * ?cat=temp|dist|poids&from=UNITE&to=UNITE&val=NOMBRE
 * Démarrage : php -S localhost:8000
 */

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

function erreur(string $msg, int $code = 400): never {
    http_response_code($code);
    echo json_encode(['erreur' => $msg]);
    exit;
}

if (!isset($_GET['cat'], $_GET['from'], $_GET['to'], $_GET['val'])) {
    erreur("Paramètres requis : cat, from, to, val");
}

$cat = strtolower($_GET['cat']);
$from = strtolower($_GET['from']);
$to   = strtolower($_GET['to']);
$val  = floatval($_GET['val']);

// ── Table de dispatch : categorie → [from_to => fn] ───────
// On stocke les fonctions de conversion dans un tableau associatif
// Clé : "from_to", Valeur : fonction de conversion
$conversions = [
    'temp' => [
        // Celsius comme pivot : d'abord en Celsius, puis vers la cible
        'celsius_fahrenheit' => fn($v): float => $v * 9/5 + 32,
        'fahrenheit_celsius' => fn($v): float => ($v - 32) * 5/9,
        'celsius_kelvin'     => fn($v): float => $v + 273.15,
        'kelvin_celsius'     => fn($v): float => $v - 273.15,
        'fahrenheit_kelvin'  => fn($v): float => ($v - 32) * 5/9 + 273.15,
        'kelvin_fahrenheit'  => fn($v): float => ($v - 273.15) * 9/5 + 32,
    ],
    'dist' => [
        'km_miles' => fn($v): float => $v * 0.621371,
        'miles_km' => fn($v): float => $v * 1.60934,
        'km_m'     => fn($v): float => $v * 1000,
        'm_km'     => fn($v): float => $v / 1000,
        'm_cm'     => fn($v): float => $v * 100,
        'cm_m'     => fn($v): float => $v / 100,
        'miles_m'  => fn($v): float => $v * 1609.34,
        'm_miles'  => fn($v): float => $v / 1609.34,
    ],
    'poids' => [
        'kg_lb'  => fn($v): float => $v * 2.20462,
        'lb_kg'  => fn($v): float => $v / 2.20462,
        'kg_g'   => fn($v): float => $v * 1000,
        'g_kg'   => fn($v): float => $v / 1000,
        'g_lb'   => fn($v): float => $v / 1000 * 2.20462,
        'lb_g'   => fn($v): float => $v / 2.20462 * 1000,
        'kg_oz'  => fn($v): float => $v * 35.274,
        'oz_kg'  => fn($v): float => $v / 35.274,
    ],
];

if (!isset($conversions[$cat])) {
    erreur("Catégorie '$cat' inconnue. Disponibles : temp, dist, poids");
}

// Même unité → pas de conversion
if ($from === $to) {
    echo json_encode(['result' => $val, 'from' => $from, 'to' => $to, 'val' => $val]);
    exit;
}

$cle = "{$from}_{$to}";
if (!isset($conversions[$cat][$cle])) {
    $dispo = implode(', ', array_keys($conversions[$cat]));
    erreur("Conversion '$from → $to' non disponible pour '$cat'. Disponibles : $dispo");
}

// Appel de la fonction de conversion stockée dans le tableau
$fn     = $conversions[$cat][$cle];
$result = round($fn($val), 4);

echo json_encode([
    'cat'    => $cat,
    'from'   => $from,
    'to'     => $to,
    'val'    => $val,
    'result' => $result,
], JSON_PRETTY_PRINT);
