<?php

function getCost($mom_kg = '1800', $demarche = '', $cp = '', $plaque = 'ZZ-000-ZZ', $reception = 2, $energie = '', $cv = '', $co2 = '', $first_immat = '', $marque = '', $dep = '', $genre = '1', $handicape = 2, $neuf_occasion = '', $host = "", $no_plaque = false)
{

  try {

    // ERROR LIMITATIONS

    if ($co2 < 0) {
      $co2 = 0;
    }

    if($plaque == ''){
        $no_plaque = true;
    }


    // INITIALISE DATA TO EXPORT

    $raw = '';
    include "call_official_api.php";

    $DataToExport = [];

    // REFERENCHES ENERGIE
    $energie_ref = [];
    $energie_ref["1"] = "Essence (ES) / Diesel (GO)";
    $energie_ref["2"] = "GPL (GP) / GNV (GN) / PE";
    $energie_ref["3"] = "Hybride (EE, GL, GH, EH, NE, FL)";
    $energie_ref["4"] = "Superéthanol E85 (FE)";
    $energie_ref["6"] = "Electricité (EL), Hydrogène (H2) ou mixte (HE, HH)";
    $energie_ref["5"] = "Bicarburation (EG, EN, FG, FN)";
    $energie_ref["7"] = "Autres carburants (ET, GA, GZ, GG, GE, PL, AC) ";


    // REFERENCHES GENRE

    $genre_ref = [];
    $genre_ref["1"]  = "Voiture (VP)";
    $genre_ref["2"]  = "Véhicule de société / Utilitaire (CTTE / Dériv-VP)";
    $genre_ref["6"]  = "Motocyclette (MTL / MTT1 / MTT2)";
    $genre_ref["7"]  = "Cyclomoteur et vélomoteur &lt; 50cm3 (CL)";
    $genre_ref["4"]  = "Camping-car et autre véhicule spécialisé (VASP)";
    $genre_ref["5"]  = "Véhicule agricole (TRA / MAGA / REA / SREA / MIAR)";
    $genre_ref["8"]  = "Tricycle à moteur (TM)";
    $genre_ref["10"] = "Quadricycle à moteur (QM)";
    $genre_ref["9"]  = "Cyclomoteur carrossé à 3 roues (CYCL)";
    $genre_ref["13"] = "Camion (CAM)";
    $genre_ref["14"] = "Véhicule de transport en commun (TCP)";
    $genre_ref["15"] = "Tracteur routier (TRR)";
    $genre_ref["16"] = "Remorque ou semi-remorque (REM / SREM)";
    $genre_ref["17"] = "Caravane tractée (RESP)</></select>";

    // LOCAL VL DATA INFO

    $vl_data = [];
    $vl_data["Immatriculation"] = "N/A";
    $vl_data["PuissFisc"] = $cv;
    $vl_data["CO2"] = $co2;
    $vl_data["Energie"] =  @$energie_ref[$energie];
    $vl_data["GenreCG"] =  @$genre_ref[$genre];
    $vl_data["DateMec"] =  @$first_immat;


    $DataToExport['vl_data'] = $vl_data;

    // DATE CONFIG
    $timestamp = strtotime($first_immat);
    $first_immat = date("d/m/Y", $timestamp);



    // FIND POSTAL CODE

    $cities = file_get_contents("./cities.json");
    $cities = json_decode($cities, true);

    foreach ($cities as $city) {

      if ($city["department_code"] == $dep) {
        $cp = $city["zip_code"];
        break;
      }
    }

    $target_url = "https://www.cartegrise.com/default/calculateur/index/ngc/";

    $damarchArray = [];

    $damarchArray[1]  =  "Changement de propriétaire d'un véhicule d'occasion français";
    $damarchArray[2]  =  "Changement d'adresse";
    $damarchArray[3]  =  "Changement de statut matrimonial (mariage, divorce, veuvage)";
    $damarchArray[4]  =  "Duplicata";
    $damarchArray[5]  =  "Duplicata - véhicule FNI (ancienne immatriculation de type '1234 AB 01')";
    $damarchArray[8]  =  "Changement de locataire (véhicule en leasing)";
    $damarchArray[12] =  "Changement de dénomination sociale d’une entreprise / association (même N° de SIREN)";
    $damarchArray[14] =  "Enregistrement de la vente de mon véhicule ";
    $damarchArray[13] =  "Certificat de situation administrative détaillée (NON GAGE) ";
    $damarchArray[15] =  "Modification des caractéristiques techniques ";
    $damarchArray[16] =  "Passage en véhicule de collection";
    $damarchArray[9]  =  "WW provisoire";
    $damarchArray[10] =  "Immatriculation d'un véhicule neuf ";
    $damarchArray[6]  =  "Immatriculation d’un véhicule en provenance de l'étranger ";

    // Douveaux demarches
    $damarchArray[20]  =  "Fiche d’identification d’un véhicule";
    $damarchArray[21]  =  "Correction erreur carte grise";
    $damarchArray[22]  =  "Heritage";
    $damarchArray[23]  =  "je suis un professionnel de l’achat/revente et je souhaite faire ma déclaration d’achat (D.A)";
    $damarchArray[24]  =  "Je suis un professionnel de l’achat/revente, je souhaite renouveler ou faire ma première demande de w garage";
    $damarchArray[26]  =  "Commander mon quitus fiscale";

    // OPERATION MANUEL WITHOUT IMMATRICULATION

    if ($demarche == 1  || $demarche == 2  || $demarche == 4  || $demarche == 8  || $demarche == 16 || $demarche == 15 || $demarche == 12 || $demarche == 3) {

      if ($no_plaque) {

        $DataToExport['manual'] = true;
        $target_url = "https://www.cartegrise.com/france/calculateur/index/ajaxPostCalculateurEtat/";

        $raw = "demarche=1&cp=$cp&genre=$genre&energie=$energie&cv=$cv&co2=$co2&first_immat=$first_immat&plaque=zz-000-zz&marque=ok&dep=$dep";

        if ($demarche == 1) {

          // $damarchArray[1] => "Changement de propriétaire d'un véhicule d'occasion français";
          $raw = "demarche=1&cp=$cp&genre=$genre&energie=$energie&cv=$cv&co2=$co2&first_immat=$first_immat&plaque=zz-000-zz&marque=ok&dep=$dep";
        }

        if ($demarche == 2) {

          // $damarchArray[2] => "Changement d'adresse";
          $raw = "demarche=2&cp=$cp&genre=$genre&plaque=zz-000-zz&marque=ok&dep=$dep";
        }

        if ($demarche == 3) {
          // $damarchArray[3] => "Changement de statut matrimonial (mariage, divorce, veuvage)";
          $raw = "demarche=3&cp=$cp&genre=$genre&plaque=zz-000-zz&marque=ok&dep=$dep";
        }

        if ($demarche == 4) {

          // $damarchArray[4] = "Duplicata";
          $raw = "demarche=4&cp=$cp&genre=$genre&energie=$energie&plaque=zz-000-zz&marque=ok&dep=$dep";
        }

        if ($demarche == 5) {
          // $damarchArray[5] => "Duplicata - véhicule FNI (ancienne immatriculation de type '1234 AB 01')
          $raw = "demarche=4&cp=$cp&genre=$genre&energie=$energie&plaque=zz-000-zz&marque=ok&dep=$dep";
        }

        if ($demarche == 8) {
          // $damarchArray[8] => "Changement de locataire (véhicule en leasing)";
          $raw = "demarche=8&cp=$cp&genre=$genre&energie=$energie&cv=$cv&co2=$co2&first_immat=$first_immat&plaque=zz-000-zz&marque=ok&dep=$dep";
        }

        if ($demarche == 12) {

          // $damarchArray[12] => "Changement de dénomination sociale d’une entreprise / association (même N° de SIREN)";
          $raw = "demarche=12&cp=$cp&genre=$genre&plaque=zz-000-zz&marque=ok&dep=$dep";
        }

        if ($demarche == 15) {

          // $damarchArray[15] => "Modification des caractéristiques techniques ";

          $raw = "demarche=15&cp=$cp&genre=$genre&plaque=zz-000-zz&marque=ok&dep=$dep";
        }
        if ($demarche == 16) {

          // $damarchArray[16] => "Passage en véhicule de collection";

          $raw = "demarche=16&cp=$cp&genre=$genre&plaque=zz-000-zz&marque=ok&dep=$dep";
        }
      } else {

        // STANDARD REQUEST WITH IMMATRICULATION

        $DataToExport['with_plaque'] = true;

        $raw = "isSIV=1&demarche=$demarche&cp=$cp&plaque=$plaque&dep=$dep";


        // INJECT  VL INFORMATIONS



        // include "find_VL.php";

        // $vl_data = findLV($plaque);
        // if ($vl_data) {
        //   $DataToExport['vl_data'] = $vl_data;
        // }

        // END STANDARD REQUEST WITH IMMATRICULATION
      }
    }


    if ($demarche == 13) {

      // https://www.cartegrise.com/default/calculateur/index/ngc/

      // $damarchArray[13] => "Certificat de situation administrative détaillée (NON GAGE) ";

    $target_url = "https://www.cartegrise.com/default/calculateur/index/ngc/";
    $raw = "isSIV=1&demarche=13&cp=$cp&genre=$genre&plaque=$plaque&marque=ok&dep=$dep";
      
    }

    // CAL SULE SPECIAL

    if ($demarche == 9) {
      ## WW PROVIOIR __________________________________________________


      $raw = "demarche=9&cp=$cp&plaque=zz-000-zz&dep=$dep&genre=$genre";


      $target_url = "https://www.cartegrise.com/france/calculateur/index/ajaxPostCalculateurEtat/";
    }


    if ($demarche == 10) {
      ## Immatriculation d'un véhicule neuf ________________________________

      $raw = "mom_kg=$mom_kg&isSIV=0&demarche=10&cp=$cp&genre=$genre&energie=$energie&cv=$cv&co2=$co2&marque=ok&dep=$dep";


      // Pour un vehicule n'ayant pas fait l'objet d'une reception communautaire,
      //le malus depend de la puissance administrative du vehicule, exprimee en chevaux-vapeur (CV).

      if ($reception == 2) {

        // Importer la fonction externe
        include "correction_pas_de_reception_communauraire.php";

        // correction de resultat
        $DataToExport = correction_pas_de_reception_communauraire($cv, $DataToExport);
      }
      
       $target_url =  "https://www.cartegrise.com/france/calculateur/index/ajaxPostCalculateurEtat/";
    }

    if ($demarche == 6) {
      ## Immatriculation d’un véhicule en provenance de l'étranger _________


      $raw = "isSIV=1&demarche=6&cp=$cp&genre=$genre&first_immat_fr=1&reception=$reception&energie=$energie&cv=$cv&mom_kg=$mom_kg&co2=$co2&first_immat=$first_immat&plaque=zz000zz&marque=ok&dep=$dep";

      // if ($neuf_occasion == 3) {
      //   $raw = "isSIV=0&demarche=6&cp=$cp&genre=$genre&first_immat_fr=1&reception=$reception&energie=$energie&cv=$cv&co2=$co2&first_immat=$first_immat&dep=$dep&handicape=$handicape&mom_kg=$mom_kg&marque=ok";
      // }

      $target_url =  "https://www.cartegrise.com/france/calculateur/index/ajaxPostCalculateurEtat/";
    }

    if ($demarche == 5) {
      ## Duplicata - véhicule FNI (ancienne immatriculation de type "1234 AB 01")_________

      $DataToExport['with_plaque'] = true;


      $raw = "isSIV=2&demarche=4&cp=$cp&genre=$genre&energie=$energie&plaque=$plaque&marque=ok&dep=$dep";

      $target_url =  "https://www.cartegrise.com/france/calculateur/index/ajaxPostCalculateurEtat/";
    }


    ###### FIND VL INFO -------------------------------------------

    if ($plaque != '') {
      include "api_plaque_2.php";
      $vl_data = api_plaque_2($plaque);
      if ($vl_data) {
        $DataToExport['vl_data'] = $vl_data;
      }
    }

    ###### FIND VL INFO -------------------------------------------


    ###### CALL OFFICIAL API -------------------------------------------

    $response = call_official_api($target_url, $raw);

    $data = json_decode($response);
    $data2 = $data;
    
       // $DataToExport["data2"]=$data2;

    $DataToExport["demarche"] = $damarchArray[$demarche];




    if (isset($data2->taxe->total)) {

      // Afficher  resulat
      $DataToExport['error'] = 0;
      $DataToExport['raw'] = $raw;
      $DataToExport['plaque'] = "";
      $DataToExport['message'] = "succes";

      if (isset($data2->taxe->error_msg)) {
        $DataToExport['error_msg'] = $data2->taxe->error_msg;
      }
      $DataToExport['y1'] = $data2->taxe->y1 ? round($data2->taxe->y1, 2) : 0;
      $DataToExport['y2'] = $data2->taxe->y2 ? round($data2->taxe->y2, 2) : 0;
      $DataToExport['y3'] = $data2->taxe->y3 ? round($data2->taxe->y3, 2) : 0;
      $DataToExport['y4'] = $data2->taxe->y4 ? round($data2->taxe->y4, 2) : 0;
      $DataToExport['y5'] = $data2->taxe->y5 ? round($data2->taxe->y5, 2) : 0;
      if (isset($data2->taxe->total)) {

        $DataToExport['total'] = round($data2->taxe->total, 2);
      } else {

        $DataToExport['total'] = round($data2->taxe->total, 2);
      }
      $DataToExport['SERVER_NAME'] = $_SERVER["SERVER_NAME"];
      $DataToExport['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
      $DataToExport['REQUEST_TIME'] = $_SERVER['REQUEST_TIME'];
      $DataToExport['js_host'] = $host;
      $DataToExport['no_plaque'] = $no_plaque;
      $DataToExport['plaque'] = $plaque;
      $DataToExport['raw'] = $raw;
    } else {

      $DataToExport['error'] = 1;
      $DataToExport['message'] = "Oups ! Une erreur inattendue : veuillez vérifier tous les champs du formulaire de votre demande et réessayer, si vous avez eu le même problème, mettez simplement à jour le plugin.";

      if (isset($data2->error_msg)) {

        $DataToExport['message'] = $data2->error_msg;

        if ($demarche == 6) {
          $DataToExport['error'] = 0;
          $DataToExport['message'] = '';
        }
      }
      $DataToExport['no_plaque'] = $no_plaque;
      $DataToExport['raw'] = $raw;
      if (isset($data2->taxe)) {

        $DataToExport['total'] = round($data2->taxe->total, 2);
      }


      if (isset($data2->taxe->y5)) {

        $DataToExport['y5'] = $data2->taxe->y5 ? round($data2->taxe->y5, 2) : 0;
      }
    }

    ## DEMARCHES GRATUITS

    if ($demarche == 20 || $demarche == 21 || $demarche == 22 || $demarche == 14 || $demarche == 23) {
      // Douveaux demarches

      $DataToExport['y1'] = 0;
      $DataToExport['y2'] = 0;
      $DataToExport['y3'] = 0;
      $DataToExport['y4'] = 0;
      $DataToExport['y5'] = 0;
      $DataToExport['y6'] = 0;
      $DataToExport['total'] = 0;
      $DataToExport['SERVER_NAME'] = $_SERVER["SERVER_NAME"];
      $DataToExport['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
      $DataToExport['REQUEST_TIME'] = $_SERVER['REQUEST_TIME'];
      $DataToExport['js_host'] = $host;
      $DataToExport['no_plaque'] = $true;
      $DataToExport['plaque'] = $plaque;
      $DataToExport['raw'] = 'no raw';
      $DataToExport['error'] = 0;
      $DataToExport['message'] = "";
    }

    if ($demarche == 24) {
      $DataToExport['y1'] = 7;
      $DataToExport['y2'] = 0;
      $DataToExport['y3'] = 0;
      $DataToExport['y4'] = 4;
      $DataToExport['y5'] = 2.76;
      $DataToExport['total'] = 13.76;
      $DataToExport['SERVER_NAME'] = $_SERVER["SERVER_NAME"];
      $DataToExport['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
      $DataToExport['REQUEST_TIME'] = $_SERVER['REQUEST_TIME'];
      $DataToExport['js_host'] = $host;
      $DataToExport['no_plaque'] = $true;
      $DataToExport['plaque'] = $plaque;
      $DataToExport['raw'] = 'no raw';
      $DataToExport['error'] = 0;
      $DataToExport['message'] = "";
    }
    
    // Certificat de situation administrative détaillée (NON GAGE)
      if ($demarche == 13) {
      $DataToExport['y1'] = 0;
      $DataToExport['y2'] = 0;
      $DataToExport['y3'] = 0;
      $DataToExport['y4'] = 0;
      $DataToExport['y5'] = 0;
      $DataToExport['total'] = 0;
           $DataToExport['error'] = 0;
      $DataToExport['message'] = "";
    }
    if ($demarche == 15) {
      $DataToExport['y1'] = 0;
      $DataToExport['y2'] = 0;
      $DataToExport['y3'] = 0;
      $DataToExport['y4'] = 0;
      $DataToExport['y5'] = 0;
      $DataToExport['total'] = 0;
    }
    //Commander mon quitus fiscale

    if ($demarche == 26) {
      $DataToExport['y1'] = 0;
      $DataToExport['y2'] = 0;
      $DataToExport['y3'] = 0;
      $DataToExport['y4'] = 0;
      $DataToExport['y5'] = 0;
      $DataToExport['total'] = 0;
      $DataToExport['raw'] = 'no raw';
      $DataToExport['error'] = 0;
      $DataToExport['message'] = "";
    }


    if(isset($DataToExport['total'])){
    
    $DataToExport['total']=round( $DataToExport['total'], 2);
    }

    // RETURN  DATA AS ARRAY
    $DataToExport['raw'] = $raw;
    return $DataToExport;


    // ERROR SERVER 500
  } catch (Exception $e) {

    $DataToExport['error'] = 1;
    $DataToExport['message'] = "Error Server 500";
    $DataToExport['message_debug'] = $e->getMessage();

    if (isset($data2->error_msg)) {

      $DataToExport['message'] = $data2->error_msg;
    }
    $DataToExport['no_plaque'] = $no_plaque;
    $DataToExport['server_message'] = $e->getMessage();
    header('Content-Type: application/json; charset=utf-8');

    echo json_encode($DataToExport);
  }
}
