<?php
$imgURL = get_site_url() . "/wp-content/plugins/wp_carte_grise/img/";

$all_apparence = get_option('all_apparence');
$wp_c_g_token = get_option('wp_c_g_token');

if ($wp_c_g_token == "") {
  $wp_c_g_token['token'] = "";
  $wp_c_g_token['active'] = 0;
  $wp_c_g_token['date_activation'] = 0;
}

@$all_apparence["form_title"] = stripslashes(@$all_apparence["form_title"]);
@$all_apparence["observation"] = stripslashes(@$all_apparence["observation"]);
@$all_apparence["costum_css"] = stripslashes(@$all_apparence["costum_css"]);
@$all_apparence["costum_js"] = stripslashes(@$all_apparence["costum_js"]);

$wp_c_g_token = get_option('wp_c_g_token');

$all_demarches_prix = get_option('all_demarches_prix');

$deps = [

  "false" => "Sélectionnez votre département",
  "01" => "01 - Ain ",
  "02" => "02 - Aisne ",
  "03" => "03 - Allier ",
  "04" => "04 - Alpes de Haute Provence ",
  "05" => "05 - Hautes Alpes ",
  "06" => "06 - Alpes Maritimes ",
  "07" => "07 - Ardèche ",
  "08" => "08 - Ardennes ",
  "09" => "09 - Ariège ",
  "10" => "10 - Aube ",
  "11" => "11 - Aude ",
  "12" => "12 - Aveyron ",
  "13" => "13 - Bouches du Rhône ",
  "14" => "14 - Calvados ",
  "15" => "15 - Cantal ",
  "16" => "16 - Charente ",
  "17" => "17 - Charente Maritime ",
  "18" => "18 - Cher ",
  "19" => "19 - Corrèze ",
  "2A" => "2A - Corse du Sud ",
  "2B" => "2B - Haute-Corse ",
  "21" => "21 - Côte d'Or ",
  "22" => "22 - Côtes d'Armor ",
  "23" => "23 - Creuse ",
  "24" => "24 - Dordogne ",
  "25" => "25 - Doubs ",
  "26" => "26 - Drôme ",
  "27" => "27 - Eure ",
  "28" => "28 - Eure et Loir ",
  "29" => "29 - Finistère ",
  "30" => "30 - Gard ",
  "31" => "31 - Haute Garonne ",
  "32" => "32 - Gers ",
  "33" => "33 - Gironde ",
  "34" => "34 - Hérault ",
  "35" => "35 - Ille et Vilaine ",
  "36" => "36 - Indre ",
  "37" => "37 - Indre et Loire ",
  "38" => "38 - Isère ",
  "39" => "39 - Jura ",
  "40" => "40 - Landes ",
  "41" => "41 - Loir et Cher ",
  "42" => "42 - Loire ",
  "43" => "43 - Haute Loire ",
  "44" => "44 - Loire Atlantique ",
  "45" => "45 - Loiret ",
  "46" => "46 - Lot ",
  "47" => "47 - Lot et Garonne ",
  "48" => "48 - Lozère ",
  "49" => "49 - Maine et Loire ",
  "50" => "50 - Manche ",
  "51" => "51 - Marne ",
  "52" => "52 - Haute Marne ",
  "53" => "53 - Mayenne ",
  "54" => "54 - Meurthe et Moselle ",
  "55" => "55 - Meuse ",
  "56" => "56 - Morbihan ",
  "57" => "57 - Moselle ",
  "58" => "58 - Nièvre ",
  "59" => "59 - Nord ",
  "60" => "60 - Oise ",
  "61" => "61 - Orne ",
  "62" => "62 - Pas de Calais ",
  "63" => "63 - Puy de Dôme ",
  "64" => "64 - Pyrénées Atlantiques ",
  "65" => "65 - Hautes Pyrénées ",
  "66" => "66 - Pyrénées Orientales ",
  "67" => "67 - Bas Rhin ",
  "68" => "68 - Haut Rhin ",
  "69" => "69 - Rhône",
  "70" => "70 - Haute Saône ",
  "71" => "71 - Saône et Loire ",
  "72" => "72 - Sarthe ",
  "73" => "73 - Savoie ",
  "74" => "74 - Haute Savoie ",
  "75" => "75 - Paris ",
  "76" => "76 - Seine Maritime ",
  "77" => "77 - Seine et Marne ",
  "78" => "78 - Yvelines ",
  "79" => "79 - Deux Sèvres ",
  "80" => "80 - Somme ",
  "81" => "81 - Tarn ",
  "82" => "82 - Tarn et Garonne ",
  "83" => "83 - Var ",
  "84" => "84 - Vaucluse ",
  "85" => "85 - Vendée ",
  "86" => "86 - Vienne ",
  "87" => "87 - Haute Vienne ",
  "88" => "88 - Vosges ",
  "89" => "89 - Yonne ",
  "90" => "90 - Territoire de Belfort ",
  "91" => "91 - Essonne ",
  "92" => "92 - Hauts de Seine ",
  "93" => "93 - Seine Saint Denis ",
  "94" => "94 - Val de Marne ",
  "95" => "95 - Val-d'Oise ",
  "971" => "971 - Guadeloupe ",
  "972" => "972 - Martinique ",
  "973" => "973 - Guyane ",
  "974" => "974 - Réunion ",
  "975" => "975 - Saint Pierre et Miquelon ",
  "976" => "976 - Mayotte ",
];

$demarche_id = "false";

if (isset($_GET['demarche_id'])) {
  $demarche_id = $_GET['demarche_id'];
}

$plaque = '';
if (isset($_GET['plaque'])) {
  $plaque = $_GET['plaque'];
}
$dep = 'false';
if (isset($_GET['dep'])) {
  $dep = $_GET['dep'];
}
$demarche = 'false';
if (isset($_GET['demarche'])) {
  $demarche = $_GET['demarche'];
}
?>
<!-- Prod -->
<!-- <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script> -->

<!-- Dev -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>


<script>
  var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
  console.log('Ajax url', ajaxurl);

  var all_demarches_prix = [];

  <?php foreach ($all_demarches_prix as $p) { ?>
    all_demarches_prix[<?= $p['id'] ?>] = "<?= $p['prix'] ?>";
  <?php } ?>

  var wp_c_g_url_api = "<?= plugin_dir_url(__FILE__) ?>callApi.php";
  var wp_c_g_token = "<?php echo @$wp_c_g_token['token'] ?>";
  var site_URL = '<?php echo get_site_url(); ?> ';

  wp_c_g_url_api = wp_c_g_url_api.trim();
  site_URL = site_URL.trim();
  wp_c_g_token = wp_c_g_token.trim();

  var demarche_id = "<?= $demarche_id ?>";
  console.log(demarche_id);

  console.log("Site_ URL IS :", site_URL);
</script>

<style>
  :root {
    --color: <?= @$all_apparence['main_color'] ?> !important;
    --color-2: <?= @$all_apparence['secoundary_color'] ?> !important;
    --white: #ffffff;
  }
</style>

<style>
  <?= @$all_apparence['costum_css'] ?>
</style>
<script>
  <?= @$all_apparence['costum_js'] ?>
</script>

<div class="simulator-container" id="app">
  <div class="loading" v-if="showProgress">
    <div class='uil-ring-css' style='transform:scale(0.79);'>
      <div></div>
    </div>
  </div>
  <?php if (!exists_w_c()) { ?>

    <div class="alert_woo">

      <a href="https://fr.wordpress.org/plugins/woocommerce/">
        <img src="https://ps.w.org/woocommerce/assets/icon-256x256.png?rev=2366418" style="width:100px;height:100px;">

        <span>Merci d'installer le plugin "woo commerce" ç'est obligatoire , cliquez <b>ici</b> pour installer</span>
      </a>
    </div>
  <?php } else { ?>

    <title> {{ title }} </title>
    <div class="card border-secondary mb-3">

      <div class="card-header mbg text-white">
        <!-- <img src="<?php echo $imgURL; ?>/fav2.png" class="header-simulator" alt="<?= @$all_apparence['form_title'] ?>"> -->
        <?= @$all_apparence['form_title'] ?>
      </div>


      <div class="card-body">
        <div class="card-text p-3">

          <!-- START FORM -->
          <form name="form-calculateur" data-myki-checked-cc="3" onsubmit="return false" @change="sync()">

            <div class="alert alert-danger" v-if="showError">
              {{errorMessage}}
            </div>

            <div class="demarches-list">
              <!-- isSIV  -->
              <input type="hidden" name="isSIV" value="1" v-model="isSIV">
              <!-- END isSIV  -->

              <!-- démarche  -->
              <div class="form-group mb-3 demarche">
                <label class="billing-step-title" for="demarche">
                  <span class="typcn typcn-th-list"></span> Sélectionnez votre démarche :
                </label>

                <select class="form-control" v-bind:class="{ has_error: demarche=='false' }" name="demarche" id="demarche" v-model="demarche">

                  <option value="false">Sélectionnez votre démarche </option>

                  <?php

                  $all_demarches_prix = get_option('all_demarches_prix');
                  if ($all_demarches_prix == "") {
                    $all_demarches_prix = array();
                  }

                  foreach ($all_demarches_prix as $d_p) {
                    $d_p["nom_demarche"] = stripslashes($d_p["nom_demarche"]);
                    if ($d_p["active"] == '') {
                      $d_p["active"] = 0;
                    }
                  ?>

                    <?php if ($d_p["active"] !== 0) { ?>
                      <!-- if demarch is active show -->
                      <option value="<?= $d_p['id'] ?>"><?= $d_p['nom_demarche'] ?>
                      </option>
                      <!-- if demarch is active show -->

                    <?php } ?>

                  <?php } ?>

                </select>

              </div>

              <!-- END démarche  -->

            </div>

            <!-- département -->

            <!-- false -->

            <div class="dep-box">
              <div class="form-group mb-3">
                <label for="dep" class="billing-step-title col-xs-offset-top-1">
                  <span class="typcn typcn-location"></span> Sélectionnez votre département
                </label>
                <div class="col-md-12 ">

                  <select class="form-control" v-bind:class="{ has_error: dep=='false'}" name="dep" id="dep" v-model="dep">
                    <?php foreach ($deps as $key => $value) { ?>
                      <option value="<?php echo $key ?>">
                        <?php echo $value ?>
                      </option>
                    <?php } ?>
                  </select>

                </div>
              </div>

            </div>
            <!-- END département -->

            <!-- START plaque immatriculation -->
            <div class="plus_de_3_changements_adresse  form-group mb-3" v-if="demarche == '2' ">
              <label class="checkbox-inline" for="plus_de_3_changements_adresse">
                <input type="checkbox" name="plus_de_3_changements_adresse" v-model="plus_de_3_changements_adresse" id="plus_de_3_changements_adresse">
                Plus de 3 changements de domicile sur cette carte grise ?
              </label>
            </div>

            <!-- START plaque immatriculation -->

            <div class="no_plaque  form-group mb-3" v-if="demarche !== '6' &&  demarche !== '10' && demarche !== '9' && demarche !== '20' && demarche !== '21' && demarche !== '22' && demarche !== '14'">
              <label class="checkbox-inline" for="no_plaque">
                <input type="checkbox" name="no_plaque" v-model="no_plaque" id="no_plaque">
                Je ne connais pas l'immatriculation
              </label>
            </div>

            <!-- END NO plaque immatriculation -->

            <!-- plaque immatriculation ppp -->

            <div class="form-group mb-3 plaque" v-show="needImmat  && !no_plaque">
              <label class="billing-step-title col-xs-offset-top-1">
                Indiquez le N° d'immatriculation
              </label>
              <div class="col-md-12 position-relative">
                <img src="<?php echo $imgURL; ?>/euro.png'" class="plaque-img" alt="">
                <input type="text" name="plaque" placeholder="AA-123-BC" class="plaque-field form-control text-left" v-model="plaque" value="<?= $plaque ?>">
              </div>
            </div>

            <!-- END plaque immatriculation -->

            <!-- ################## caractéristiques de votre véhicule -->
            <div class="vl-container" v-if="!needImmat ||   no_plaque">
              <div class="form-group mt-2 genre" v-if="genre_needs">
                <div class="col-md-12">

                </div>

                <!-- Genre -->
                <div class="label-desc genre">
                  <div class="row">
                    <label class="mt-3 mb-2 col-xs-5 col-sm-12">
                      <span class="typcn typcn-support"></span> Genre national (J.1)
                    </label>
                  </div>

                  <div class="col-md-12 genre ">
                    <select class="form-control " name="genre" id="genre" v-model="genre" v-bind:class="{ has_error: genre=='false' }">
                      <option value="false"> Sélectionnez le genre de véhicule </option>
                      <option value="1">Voiture (VP)</option>
                      <option value="2">Véhicule de société / Utilitaire (CTTE / Dériv-VP)</option>
                      <option value="6">Motocyclette (MTL / MTT1 / MTT2)</option>
                      <option value="7">Cyclomoteur et vélomoteur &lt; 50cm3 (CL)</option>
                      <option value="4">Camping-car et autre véhicule spécialisé (VASP)</option>
                      <option value="8">Tricycle à moteur (TM)</option>
                      <option value="10">Quadricycle à moteur (QM)</option>
                      <option value="9">Cyclomoteur carrossé à 3 roues (CYCL)</option>
                      <option value="13">Camion (CAM)</option>
                      <option value="14">Véhicule de transport en commun (TCP)</option>
                      <option value="15">Tracteur routier (TRR)</option>
                      <option value="5">Véhicule agricole (TRA / MAGA / REA / SREA / MIAR)</option>
                      <option value="16">Remorque ou semi-remorque (REM / SREM)</option>
                      <option value="17">Caravane tractée (RESP)</option>
                    </select>
                  </div>
                </div>

              </div>
              <!-- END Genre -->

              <!-- Poids Total Autorisé en Charge -->

              <div class="form-group mt-3 mb-3 ptac " v-if="genre== '13'">
                <div class="label-desc">
                  <div class="row">
                    <label class="col-xs-5 col-sm-12">
                      PTAC (Case F.2 de la carte grise)
                    </label>

                  </div>
                </div>
                <div class="col-md-12 ptac">
                  <select class="form-control" name="ptac" v-model="ptac">
                    <option value="2">&lt;= 3,5 tonnes</option>
                    <option value="5">&gt; 3,5 tonnes et &lt; 6 tonnes</option>
                    <option value="8">&gt;= 6 tonnes et &lt; 11 tonnes</option>
                    <option value="12">&gt;= 11 tonnes, tracteur routier, transport en commun de voyageurs</option>
                  </select>
                </div>
              </div>

              <!-- END Poids Total Autorisé en Charge -->

              <!-- véhicule neuf ou occasion -->

              <div class="row form-group mt-3 mb-3 neuf_occasion" v-if="demarche == '6'">
                <div class="neuf-occasion-label mb-2">
                  <label for="neuf_occasion" class="text-bold"> <span class="typcn typcn-th-list"></span>
                    Votre véhicule est-il : </label>
                </div>

                <div class="col-xs-12 col-sm-12 f-left">
                  <input type="radio" name="neuf_occasion" value="1" id="neuf" v-model="neuf_occasion">
                  <label class="radio-inline" for="neuf">Neuf</label>
                </div>

                <div class="col-xs-12 col-sm-12">
                  <input type="radio" name="neuf_occasion" value="3" id="occasion" v-model="neuf_occasion">
                  <label for="occasion" class="radio-inline"> Occasion </label>
                </div>
              </div>

              <!-- END véhicule neuf ou occasion -->

              <!-- véhicule demonstration-->

              <div class="row form-group mt-3 mb-3 demonstration" v-if="genre == '1' && neuf_occasion=='neuf'">
                <div class="neuf-occasion-label mb-2">
                  <label for="demonstration" class="text-bold"> <span class="typcn typcn-th-list"></span>
                    * Véhicule de démonstration ? : </label>
                </div>

                <div class="col-xs-12 col-sm-12 f-left">
                  <input type="radio" name="demonstration" value="true" id="demonstration_oui" v-model="demonstration">
                  <label class="radio-inline" for="demonstration_oui">Oui</label>
                </div>

                <div class="col-xs-12 col-sm-12">
                  <input type="radio" name="demonstration" value="false" v-model="demonstration" id="demonstration_non">
                  <label for="demonstration_non" class="radio-inline">Non</label>
                </div>
              </div>

              <!-- END véhicule demonstration-->


              <!-- véhicule plus de 5 places-->

              <div class="row form-group mt-3 mb-3 plus5" v-if="genre == '2'">
                <div class="neuf-occasion-label mb-2">
                  <label for="plus5" class="text-bold"> <span class="typcn typcn-th-list"></span>
                    Votre véhicule comprend-il au moins cinq places assises (S1 = 5) ? : </label>
                </div>

                <div class="col-xs-12 col-sm-12 f-left">
                  <input type="radio" name="plus5" value="true" id="plus5_oui" v-model="plus5">
                  <label class="radio-inline" for="plus5_oui">Oui</label>
                </div>

                <div class="col-xs-12 col-sm-12">
                  <input type="radio" name="plus5" value="false" v-model="plus5" id="plus5_non">
                  <label for="plus5_non" class="radio-inline">Non</label>
                </div>
              </div>

              <!-- END véhicule plus de 5 places-->

              <!-- véhicule de collection-->

              <div class="row form-group mt-3 mb-3 collection" v-if="genre == '2' || genre == '13' || genre == '15'">
                <div class="neuf-occasion-label mb-2">
                  <label for="collection" class="text-bold"> <span class="typcn typcn-th-list"></span>
                    Votre véhicule comprend-il au moins cinq places assises (S1 = 5) ? : </label>
                </div>

                <div class="col-xs-12 col-sm-12 f-left">
                  <input type="radio" name="collection" value="true" id="collection_oui" v-model="collection">
                  <label class="radio-inline" for="collection_oui">Oui</label>
                </div>

                <div class="col-xs-12 col-sm-12">
                  <input type="radio" name="collection" value="false" v-model="collection" id="collection_non">
                  <label for="collection_non" class="radio-inline">Non</label>
                </div>
              </div>

              <!-- END véhicule véhicule de collection-->

              <div class="row">

                <div class="col col-md-4 col-sm-12 mt-3">
                  <!-- Véhicule adapté au handicap -->
                  <div class="form-check  handicape " v-if="handicape_needs && genre =='1'">
                    <input type="checkbox" class="form-check-input" id="handicape" name="handicape" value="1" v-model="handicape">
                    <!-- value="2">Non -->
                    <label class="form-check-label" for="handicape">
                      Carrosserie handicap / Carte d'invalidité
                    </label>
                  </div>
                  <!-- END Véhicule adapté au handicap -->
                </div>

                <div class="col col-md-6 col-sm-12 mt-3">
                  <!-- véhicule objet d'une réception communautaire -->
                  <div class="form-check  reception" v-if="reception_needs">
                    <input checked type="checkbox" class="form-check-input" id="reception" name="reception" value="1" v-model="reception">
                    <!-- value="2">Non -->
                    <label class="form-check-label" for="reception">
                      Le véhicule a fait l'objet d'une réception communautaire ?

                    </label>
                  </div>
                  <!-- END véhicule objet d'une réception communautaire -->
                </div>
              </div>



              <br>

              <!-- Emission de CO2 -->

              <div class="form-group mb-3 co2" v-if="co2_needs">
                <div class="label-desc">
                  <div class="row">
                    <label class="col-xs-5 col-sm-12">
                      <span class="typcn typcn-feather"></span> Taux d'émission CO2 (V.7) mettre « 0 » si inconnu
                    </label>

                  </div>
                </div>
                <div class="col-md-12">
                  <input type="number" name="co2" class="form-control text-left" placeholder="Emission de CO2 (Colonne V.7 de votre carte grise / mettre « 0 » si inconnu)" v-model="co2" v-bind:class="{ has_error: co2=='' }">
                </div>
              </div>

              <!-- END Emission de CO2 -->

              <!-- véhicule Energie -->

              <div class="form-group mb-3 energie" v-if="energie_needs">
                <div class="label-desc">
                  <div class="row">
                    <label class="col-xs-5 col-sm-12">
                      <span class="typcn typcn-lightbulb"></span> Energie (P.3)
                    </label>
                  </div>
                </div>

                <div class="col-md-12 ">
                  <select class="form-control " name="energie" v-model="energie" v-bind:class="{ has_error: energie=='false' }">
                    <option value="false" selected="selected"> Sélectionnez l'énergie de véhicule</option>
                    <option value="1">Essence (ES) / Diesel (GO)</option>
                    <option value="2">GPL (GP) / GNV (GN) / PE</option>
                    <option value="3">Hybride (EE, GL, GH, EH, NE, FL)</option>
                    <option value="4">Superéthanol E85 (FE)</option>
                    <option value="6">Electricité (EL), Hydrogène (H2) ou mixte (HE, HH)</option>
                    <option value="5">Bicarburation (EG, EN, FG, FN)</option>
                    <option value="7">Autres carburants (ET, GA, GZ, GG, GE, PL, AC) </option>
                  </select>
                </div>
              </div>

              <!-- véhicule Energie -->

              <!-- POOID DU VIHECULE -->

              <!-- mom_kg -->
              <div class="form-group mb-3 cv" v-if="demarche==10 || demarche==6">

                <div class="label-desc">
                  <div class="row">
                    <label class="col-xs-5 col-sm-12">
                      <span class="typcn typcn-flash"></span> Poids du véhicule (Kg)
                    </label>
                  </div>
                  <div class="col-md-12">
                    <input type="number" name="mom_kg" class="form-control  text-left" placeholder="Poids du véhicule" v-model="mom_kg" v-bind:class="{ has_error: mom_kg=='' }">
                  </div>
                </div>
              </div>
              <!-- POOID DU VIHECULE -->
              <!-- Puissance fiscale -->

              <div class="form-group mb-3 cv" v-if="cv_needs">

                <div class="label-desc">
                  <div class="row">
                    <label class="col-xs-5 col-sm-12">
                      <span class="typcn typcn-flash"></span> Puissance administrative nationale (P.6)
                    </label>
                  </div>
                  <div class="col-md-12">
                    <input type="number" name="cv" class="form-control  text-left" placeholder="Puissance fiscale (Colonne P.6 de votre carte grise)" v-model="cv" v-bind:class="{ has_error: cv=='' }">
                  </div>
                </div>
              </div>

              <!-- END Puissance fiscale -->



              <!-- Date de 1er Mise en circulation -->

              <div class="form-group mb-3 first_immat" v-if="first_immat_needs">
                <div class="label-desc">
                  <div class="row">
                    <label class="col-xs-5 col-sm-12">
                      <span class="typcn typcn-calendar"></span> Date de mise en circulation (B) :
                    </label>

                  </div>
                </div>
                <div class="col-md-12" v-bind:class="{ has_error: first_immat=='' }">
                  <input type="date" name="first_immat" class="parsed_date form-control text-left" v-model="first_immat" placeholder="Mise en circulation (Colonne B de votre carte grise) : JJ/MM/AAAA">
                </div>
              </div>

              <!-- END Date de 1er Mise en circulation -->

            </div>
            <!-- END  caractéristiques de votre véhicule -->



            <!-- SUBMIT  -->

            <div class="submit-container ">
              <div class="d-flex justify-content-end align-items-center submit-panel">
                <!-- <div class="text-danger small"> Champs à remplir obligatoirement.</div> -->
                <button class="btn btn-danger  px-2 " type="reset" name="effacer">
                  <span class="typcn typcn-trash"></span> Effacer formulaire</button>
                <div class="mr-4"></div>
                <div class="px-3"></div>
                <button @click="calculer()" type="submit" class="px-3 btn btn-primary btn-block btn-calculez mbg">
                  <span class="typcn typcn-calculator"></span> Calculer le prix
                </button>

              </div>
            </div>

            <!-- SUBMIT  -->

          </form>

        </div>

      </div>
    </div>

    <div class="card border-secondary" v-if="showResult">

      <div class="card-text p-3">

        <div class="row">
          <div id="tax" class="col-md-6 ">
            <table class="table table table-sm table-responsive">
              <thead>
                <tr>
                  <th colspan="2" class="mbg text-white"> Démarche : {{selected_demarche}}</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>Y1 - Taxe régionale :</td>
                  <td>{{ y1 }} €</td>
                </tr>

                <tr>
                  <td>Y2 - Majoration véhicule de transport :</td>
                  <td>{{ y2 }} €</td>
                </tr>

                <tr>
                  <td>Y3 - Malus CO² et TMOM (Taxe au poids ) </td>
                  <td>{{ y3 }} €</td>
                </tr>

                <tr>
                  <td>Y4 - Taxe fixe :</td>
                  <td>{{ y4 }} €</td>
                </tr>

                <tr>
                  <td>Y5 - Redevance d'acheminement :</td>
                  <td>{{ y5 }} €</td>
                </tr>

                <tr class="sub-total">
                  <td>Y6 - Taxes à payer : </td>
                  <td>{{ total }} €</td>
                </tr>

                <tr>
                  <td>Frais de traitement du dossier : </td>
                  <td>{{f_dossier}} €</td>
                </tr>

                <tr class="total">
                  <td> TOTAL : </td>
                  <td>{{total_g}} €</td>
                </tr>

              </tbody>
            </table>
          </div>

          <br>
          <div class="mt-3"></div>
          <br>
          <div id="vl" class="col-md-6 " v-if="showVLInfo">
            <table class="table table table-sm table-responsive">
              <thead>
                <tr>
                  <th colspan="2" class="mbg text-white"> Immatriculation : {{vl_immat}} </th>
                </tr>
              </thead>
              <tbody>
                <tr v-if="vl_marque">
                  <td>Marque et modele :</td>
                  <td>{{ vl_marque }} {{vl_modele}} </td>
                </tr>

                <tr v-if="vl_cv">
                  <td>Puissance administrative nationale :</td>
                  <td>{{ vl_cv }} </td>
                </tr>

                <tr v-if="vl_co2">
                  <td>Taux d'émission de CO2 : </td>
                  <td>{{ vl_co2 }} </td>
                </tr>

                <tr v-if="vl_energie">
                  <td>Energie :</td>
                  <td>{{ vl_energie }} </td>
                </tr>

                <tr v-if="vl_genre">
                  <td>Genre :</td>
                  <td>{{ vl_genre }} </td>
                </tr>

                <tr v-if="vl_firs_immat">
                  <td>Date de mise en circulation : </td>
                  <td>{{ vl_firs_immat }}</td>
                </tr>

              </tbody>
            </table>
          </div>
        </div>

        <?php $all_apparence['observation'] = trim($all_apparence['observation']); ?>
        <p class="observation info <?php echo $all_apparence['observation'] == '' ? 'hidden' : '' ?>">
          <?= $all_apparence['observation'] ?>
        </p>

        <div class="submit-container ">
          <div class="d-flex justify-content-end align-items-center submit-panel">
            <button class="px-3 btn btn-primary btn-block btn-calculez mbg" @click="addToCart">
              <span class="typcn typcn-shopping-cart"></span> Ajouter au panier
            </button>
          </div>
        </div>

      </div>

    </div>

    <div class="footer">
      Simulateur et taxes mis à jour par ©
      <a href="https://mh-data.com/produit/plugin-carte-grise-avec-wordpress-et-woocommerce-wp-carte-grise/">
        <?= WP_CARTE_DEVLOPPERS ?> - v <?= WP_CARTE_GRISE_VERSION ?>
      </a>
      - Source : Ministère del'Intérieur - <?= date("Y") ?>
    </div>
  <?php } ?>

</div>
<script>
  var app = new Vue({
    el: '#app',

    data: {
      //  baseURL:"http://localhost:8888/WPCG-VUEJS/",
      baseURL: 'https://mh-data.com/',
      title: 'WP CARTE GRISE SIMULATEUR',
      isSIV: 1,
      needImmat: true,
      plus5: false,
      fees: null,
      showResult: false,
      showVLInfo: false,
      showError: false,
      showProgress: true,
      errorMessage: '',
      demonstration: false,
      collection: false,
      first_immat_fr: 1,
      neuf_occasion: 3,
      ptac: 2,
      plus_de_3_changements_adresse: false,

      plaque: "",
      demarche: "",
      dep: "",

      cv: '',
      co2: '',
      mom_kg: '',
      reception: 1,
      genre: 'false',
      first_immat: '',
      energie: 'false',
      handicape: false,

      y1: 0,
      y2: 0,
      y3: 0,
      y4: 0,
      y5: 0,
      total: 0,
      selected_demarche: '',
      vl_marque: false,
      vl_modele: false,
      vl_cv: false,
      vl_co2: false,
      vl_energie: false,
      vl_genre: false,
      vl_immat: false,
      no_plaque: false,
      vl_firs_immat: false,

      cv_needs: false,
      co2_needs: false,
      reception_needs: false,
      genre_needs: false,
      first_immat_needs: false,
      energie_needs: false,
      handicape_needs: false,

      f_dossier: 0,
      total_g: 0,
    },
    mounted: function() {

      window.addEventListener('load', () => {
        // run after everything is in-place
        this.showProgress = false;
        this.demarche = demarche_id;
        this.demarche = "<?= $demarche ?>";
        this.dep = "<?= $dep ?>";
        this.plaque = "<?= $plaque ?>";
        this.sync();
        this.sync();
      });
    },
    methods: {
      cv_needsF() {
        this.cv_needs = ['10', '6', '8', '1'].includes(this.demarche);
      },
      co2_needsF() {
        this.co2_needs =
          (['10', '6'].includes(this.demarche) && this.reception) || ['8', '1'].includes(this.demarche);
      },
      reception_needsF() {
        this.reception_needs = ['10', '6'].includes(this.demarche);
      },
      genre_needsF() {
        this.genre_needs = [
          '10',
          '6',
          '8',
          '1',
          '4',
          '5',
          '2',
          '3',
          '12',
          '13',
          '14',
          '15',
          '16',
          '9',
        ].includes(this.demarche);
      },
      first_immat_needsF() {
        this.first_immat_needs = ['6', '8', '1'].includes(this.demarche);
      },
      energie_needsF() {
        this.energie_needs = ['10', '6', '8', '1', '4', '5'].includes(
          this.demarche,
        );
      },
      handicape_needsF() {
        this.handicape_needs = ['10', '6'].includes(this.demarche);
      },
      needImmatF() {
        this.needImmat = [
          '1',
          '2',
          '4',
          '8',
          '16',
          '15',
          '12',
          '3',
          '5',
          '20',
          '21',
          '22',
          '14',
        ].includes(this.demarche);
      },
      clearValues() {
        // initialise value
        this.showError = false;
        this.showResult = false;
        this.showVLInfo = false;
        this.errorMessage = '';
      },
      sync: function() {
        // initialise value
        this.cv_needsF();
        this.co2_needsF();
        this.reception_needsF();
        this.genre_needsF();
        this.first_immat_needsF();
        this.energie_needsF();
        this.handicape_needsF();
        this.needImmatF();
        this.clearValues();
      },
      calculer: function(e) {
        if (e) {
          e.preventDefault();
        }
        this.clearValues();
        this.y1 = this.y2 = this.y3 = this.y4 = this.y5 = this.total = 0;

        // show progress bar
        this.showProgress = true;

        data = {};

        data.wp_c_g_token = wp_c_g_token;
        data.no_plaque = this.no_plaque;
        data.isSIV = this.isSIV;
        data.demarche = this.demarche;
        data.plaque = this.plaque;
        data.reception = this.reception == true ? 1 : 2;
        data.energie = this.energie;
        data.cv = this.cv;
        data.co2 = this.co2;
        data.mom_kg = this.mom_kg;
        data.first_immat = this.first_immat;
        data.first_immat_fr = this.first_immat_fr == true ? 1 : 2;
        data.dep = this.dep;
        data.genre = this.genre;
        data.handicape = this.handicape;
        data.plus_de_3_changements_adresse = this.plus_de_3_changements_adresse;
        data.neuf_occasion = this.neuf_occasion;
        data.plus5 = this.plus5;
        data.collection = this.collection;
        data.demonstration = this.demonstration;
        data.host = window.location.host;

        var myHeaders = new Headers();
        myHeaders.append('content-type', 'application/json');
        myHeaders.append('accept', '*/*');

        // Default options are marked with *
        // fetch(`${this.baseURL}api/simulateur_prix_carte_grise/`, {
        fetch(wp_c_g_url_api, {
            method: 'POST',
            headers: myHeaders,
            redirect: 'follow',
            body: JSON.stringify(data),
          })
          .then((response) => console.log(response))
          .then((response) => response.json())
          .then((json) => (this.fees = json))
          .then((d) => {
            if (d.error == 1) {
              this.showError = true;
              this.errorMessage = d.message;
              this.showProgress = false;
              if (d.with_plaque) {
                this.no_plaque = true;
                this.errorMessage =
                  "Erreur inattendue dans votre numéro d'immatriculation, essayer la méthode manuelle";
                console.log(d.message);
              }
            }

            if (d.error_msg) {
              this.showError = true;
              this.errorMessage = d.error_msg;
              this.showProgress = false;
              return;
            }

            if (d.error == undefined) {
              this.showError = true;
              this.errorMessage =
                'OUps ! Une erreur inattendue : veuillez vérifier tous les champs du formulaire de votre demande et réessayer';
              this.showProgress = false;
              return;
            }

            if (d.error == 0) {
              this.showResult = true;
              this.selected_demarche = d.demarche;
              this.y1 = d.y1;
              this.y2 = d.y2;
              this.y3 = d.y3;
              this.y4 = d.y4;
              this.y5 = d.y5;
              this.total = +d.total;

              if (all_demarches_prix[this.demarche] !== undefined) {
                this.f_dossier = +all_demarches_prix[this.demarche];
              }
              this.total_g = this.total + this.f_dossier;
              this.total_g = this.total_g;

              // show vl INFO

              // if (["1", "2", "4", "8", "16", "15", "12", "3"].includes(this.demarche)) {
              if (true) {
                this.showVLInfo = true;
                this.vl_marque = d.vl_data.Marque;
                this.vl_modele = d.vl_data.ModeleEtude;
                this.vl_cv = d.vl_data.PuissFisc;
                this.vl_co2 = d.vl_data.CO2;
                this.vl_energie = d.vl_data.Energie;
                this.vl_genre = d.vl_data.GenreCG;
                this.vl_firs_immat = d.vl_data.DateMec;
                this.vl_immat = d.vl_data.Immatriculation;
              }
            }
          })
          .then(() => {
            var tax = document.getElementById('tax')
            if (tax != null) {

              document.getElementById('tax').scrollIntoView();
            }

            this.showProgress = false;
          })
          .catch((err) => {
            // this.showError = true;
            console.log('Error SERVER 500 ', err);
            console.log(err.message);
            this.showProgress = false;
            // this.calculer();

          });
      },

      addToCart: function() {
        this.showProgress = true;

        var myHeaders = new Headers();

        myHeaders.append('accept', '*/*');
        myHeaders.append(
          'content-type',
          'application/x-www-form-urlencoded; charset=UTF-8',
        );
        myHeaders.append('Accept-Language', 'en-US,en;q=0.9');
        myHeaders.append('Accept', 'application/json');
        myHeaders.append('Sec-Fetch-Site', 'same-site');
        // myHeaders.append('Sec-Fetch-Mode', 'cors');
        myHeaders.append('Sec-Fetch-Dest', 'empty');

        var raw = `action=my_ajax_request&post_type=POST&demarche_id=${this.demarche}&demarche_name=${this.selected_demarche}&plaque=${this.plaque}&marque=${this.vl_marque}&modele=${this.vl_modele}&cv=${this.vl_cv}&co2=${this.vl_co2}&energie=${this.vl_energie}&genre=${this.vl_genre}&firs_immat=${this.vl_firs_immat}&immat=${this.vl_immat}&y1=${this.y1}&y2= ${this.y2}&y3=${this.y3}&y4=${this.y4}&y5=${this.y5}&total=${this.total}&plus_de_3_changements_adresse=${this.plus_de_3_changements_adresse}`;

        var requestOptions = {
          method: 'POST',
          headers: myHeaders,
          body: raw,
          redirect: 'follow',
        };

        fetch(ajaxurl, requestOptions)
          .then((response) => response.json())
          .then((result) => {
            console.log(result);
            if (result.error == false) {
              console.log('Success', result);
              window.location.href = result.redirect;
            }

            // AN ERROR SHOW MESSAGE
            if (result.error == true) {
              this.showProgress = false;
              this.errorMessage = result.message;
              this.showError = true;
              return;
            }

            // IMMAT NOT FOUND

            if (result == undefined) {
              this.showProgress = false;
              this.errorMessage = 'Immat not found 404';
              this.showError = true;
              return;
            }
          })
          .catch((error) => {
            this.showProgress = false;
            this.showError = true;
            this.errorMessage = 'Local error cannot add to cart';
            console.log('Error debug js : ', error);
          });
      },
    },
  });
</script>
<style>
  @media only screen and (max-width: 600px) {
    .simulator-container {
      background: white;
      padding: 0;
    }

    button.btn.btn-danger.px-2 {
      cursor: pointer;
      width: 100%;
    }

    button.px-3.btn.btn-primary.btn-block.btn-calculez.mbg {
      cursor: pointer;
      width: 100%;
    }

    .d-flex.justify-content-end.align-items-center.submit-panel {
      width: 90%;
      margin: 0 auto;
      text-align: center;
      display: flex;
    }

    .submit-container {
      background: #eeeeee;
      padding: 0;
      border-radius: 0;
      margin: 0 auto;
      clear: both;
      float: none;
      display: flex;
      flex-direction: column;
      text-align: center;
      justify-content: center;
      align-items: center;
    }
  }
</style>