<?php

function findLV($raw_immat)
{

  // format plaque
  $raw_immat = strtolower($raw_immat);
  $raw_immat = str_replace('-', '', $raw_immat);
  $raw_immat = str_replace('-', '', $raw_immat);
  $raw_immat = trim($raw_immat);

  $data = [
    'Marque' => 'N/A',
    'ModeleEtude' => 'N/A',
    'PuissFisc' => 'N/A',
    'CO2' => '',
    'Energie' => 'N/A',
    'GenreCG' => 'N/A',
    'DateMec' => 'N/A',
    'Immatriculation' => 'N/A',
  ];
  $extern_data = find_extern($raw_immat);
  if ($extern_data) {
    $data['Marque'] = $extern_data['vehiculeMarque'];
    $data['ModeleEtude'] = $extern_data['vehiculeModele'];
    $data['PuissFisc'] = $extern_data['vehiculePuissance'];
    $data['Energie'] = $extern_data['vehiculeEnergie'];
    $data['GenreCG'] = $extern_data['vehiculeType'];
    $data['DateMec'] = $extern_data['vehiculeMEC'];
    $data['Immatriculation'] = $extern_data['Immatriculation'];
  }

  return $data;
}

function find_extern($immat)
{

  $curl = curl_init();

  curl_setopt_array($curl, array(
    CURLOPT_URL => "http://www.cmacartegrise.com/wp-content/plugins/inneo-simu-siv/cross-api.php?immat=$immat",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
  ));

  $response = curl_exec($curl);
  curl_close($curl);
  if ($response) {
    $response = json_decode($response, true);
    if ($response['data']) {
      $response['data']['Immatriculation'] = $immat;
      return $response['data'];
    }
  }
  return false;
}
