<style>
  .select2-container--default .select2-selection--multiple .select2-selection__choice {
  background-color: #343a40;  /* bleu Bootstrap */
  color: white;
  border: 1px solid #0056b3;
  font-weight: bold;
}

.select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
  color: white;
}
.select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover {
  color: #ffdddd;
}

</style>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <h1>
      Gérer les
      <small>Motos</small>
    </h1>
    <ol class="breadcrumb">
      <li><a href="#"><i class="fa fa-dashboard"></i> Accueil</a></li>
      <li class="active">Motos</li>
    </ol>
  </section>

  <!-- Main content -->
  <section class="content">
    <!-- Small boxes (Stat box) -->
    <div class="row">
      <div class="col-md-12 col-xs-12">

        <div id="messages"></div>

        <?php if (session()->getFlashdata('success')): ?>
          <div class="alert alert-success alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <?php echo session()->getFlashdata('success'); ?>
          </div>
        <?php elseif (session()->getFlashdata('error')): ?>
          <div class="alert alert-error alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <?php echo session()->getFlashdata('error'); ?>
          </div>
        <?php endif; ?>


        <div class="box">
          <div class="box-header">
            <h3 class="box-title">Ajouter une Moto</h3>
          </div>
          <!-- /.box-header -->
          <form role="form" action="<?= base_url('products/create') ?>" method="post" enctype="multipart/form-data">
            <?php if (isset($validation) && $validation->getErrors()) : ?>
              <div class="alert alert-danger">
                <ul>
                  <?= $validation->listErrors() ?>
                </ul>
              </div>

            <?php endif; ?>
            <div class="box-body">

              <!-- validation -->
              <div class="form-group">

                <label for="product_image">Image</label>
                <div class="kv-avatar">
                  <div class="file-loading">
                    <input id="product_image" name="product_image" type="file" accept="image/*">
                  </div>
                </div>
              </div>

              <div class="form-group">
                <label for="product_name">Nom de Moto</label>
                <input type="text" class="form-control" id="product_name" name="nom_de_produit" placeholder="Nom du moto" autocomplete="off" value="<?= old('nom_de_produit') ?>"  required/>
              </div>

              <div class="form-group">
                <label for="marque">Marque</label>
                <select class="form-control" id="marque" name="marque" required>
                  <option value="">Sélectionnez une marque</option>
                  <?php foreach ($marque as $k => $v): ?>
                    <option value="<?php echo $v['id'] ?>"><?php echo $v['name'] ?></option>
                  <?php endforeach ?>
                </select>
              </div>


              <div class="form-group">
                <label for="moteur">Numéro de moteur</label>
                <input type="text" class="form-control" value="<?= old('numero_de_moteur') ?>"  id="moteur" name="numero_de_moteur" placeholder="Numéro de moteur" autocomplete="off" required/>
              </div>

              <div class="form-group">
                <label for="chassis">Châssis</label>
                <input type="text" class="form-control" id="chassis" name="chasis" value="<?= old('chasis') ?>" placeholder="Chassis" autocomplete="off" required/>
              </div>

              <div class="form-group">
                <label for="price">Prix d'achat</label>
                <input type="text" class="form-control" id="price_display" placeholder="Prix d'achat" autocomplete="off" value="<?= old('prix') ?>" required/>
                <input type="hidden" name="prix" id="price">
              </div>

              <div class="form-group">
                <label for="price_vente">Prix de Vente</label>
                <input type="text" class="form-control" id="price_vente_display" placeholder="Prix de vente" autocomplete="off" value="<?= old('price_vente') ?>" required/>
                <input type="hidden" name="price_vente" id="price_vente">
              </div>

              <div class="form-group">
                <label for="price_min">Prix de Minimal</label>
                <input type="text" class="form-control" id="price_min_display" placeholder="Prix de vente minimal autoriser" autocomplete="off" value="<?= old('price_min') ?>" required/>
                <input type="hidden" name="price_min" id="price_min">
              </div>

              <div class="form-group">
                <label for="datea">Date d'arrivage</label>
                <input type="date" class="form-control" id="datea" value="<?= old('datea') ?>" name="datea" autocomplete="off"/>
              </div>

              <div class="form-group"> 
                <label for="puissance">Puissances</label>
                <select class="form-control" id="puissance" name="puissance" required>
                  <option value="">Sélectionnez une puissance </option>
                  <option value="50">50</option>
                  <option value="100">100</option>
                  <option value="110">110</option>
                  <option value="115">115</option>
                  <option value="125">125</option>
                  <option value="150">150</option>
                  <option value="160">160</option>
                  <option value="155">155</option>
                  <option value="180">180</option>
                  <option value="200">200</option>
                  <option value="250">250</option>
                  <option value="300">300</option>
                  <option value="400">400</option>
                  <option value="1000">1000</option>
                </select>
              </div>


              <div class="form-group">
                <label for="cler">Clé</label>
                <select class="form-control" id="cler" name="cler">
                  <option value="1">Oui</option>
                  <option value="2">Non</option>
                </select>
              </div>

              <div class="form-group">
                <label for="description">Description</label>
                <textarea type="text" class="form-control" value="<?= old('description') ?>" id="description" name="description" placeholder="Description" autocomplete="off">
                  </textarea>
              </div>

              <div class="form-group">
                <label for="sku">Numéro de série</label>
                <input type="text" class="form-control" id="sku" value="<?= old('numero_de_serie') ?>" name="numero_de_serie" placeholder="Numéro de série" autocomplete="off"/>
              </div>

              <div class="form-group">
                <label for="categorie">Catégories</label>
                <select class="form-control select2" style="height: auto; min-height: 40px; max-height: 100px; overflow-y: auto;" id="categorie" name="categorie[]" multiple="multiple" required>
                <?php foreach ($categorie as $k => $v): ?>
                    <option value="<?php echo $v['id'] ?>"><?php echo $v['name'] ?></option>
                  <?php endforeach ?>
                </select>
              </div>

              <div class="form-group">
                <label for="store">Magasin (lieu de réception)</label>
                <select class="form-control" id="store" name="store" required>
                  <option value="">Sélectionnez un magasin</option>
                  <?php foreach ($stores as $k => $v): ?>
                    <option value="<?php echo $v['id'] ?>"><?php echo $v['name'] ?></option>
                  <?php endforeach ?>
                </select>
              </div>


              <div class="form-group">
                  <label for="store">Disponibilité</label>
                  <select class="form-control" id="availability" name="availability" required>
                      <option value="">Sélectionnez une disponibilité</option>
                      <option value="1">Oui</option>
                      <option value="0">Non</option> <!-- Changé de 2 à 0 -->
                  </select>
              </div>

              <div class="form-group">
                <label for="store">Etats</label>
                <select class="form-control" id="etat" name="etats" required>
                  <option value="" >selectionnez une Etat</option>
                  <option value="1">Kit</option>
                  <option value="2">Non kit</option>
                </select>
              </div>

              <div class="form-group">
                <label for="store">Type</label>
                <select class="form-control" id="type" name="type" required>
                  <option value="" >Veuillez choisir</option>
                  <option value="A">A</option>
                  <option value="B">B</option>
                  <option value="C">C</option>
                  <option value="D">D</option>
                </select>
              </div>

              <div class="form-group" id="boxsuplementairekit"></div>

              <div class="form-group">
                <label for="store">Pièce Manquant</label>
                <select class="form-control" id="info" name="info">
                  <option value="2" selected>Non</option>
                  <option value="1">Oui</option>
                </select>
              </div>

              <div class="form-group" id="boxsuplementaire"></div>
            </div>
            <!-- /.box-body -->

            <div class="box-footer">
              <button type="submit" class="btn btn-primary">Enregistrer</button>
              <a href="<?php echo base_url('products/') ?>" class="btn btn-warning">Retour</a>
            </div>
          </form>
          <!-- /.box-body -->
        </div>
        <!-- /.box -->
      </div>
      <!-- col-md-12 -->
    </div>
    <!-- /.row -->


  </section>
  <!-- /.content -->
</div>
<!-- /.content-wrapper -->

<script type="text/javascript">
  document.getElementById('price_display').addEventListener('input', function(e) {
                // Supprimer tous les espaces et caractères non numériques
                let val = e.target.value.replace(/\D/g, '');

                // Ajouter l'espace tous les 3 chiffres
                let formatted = val.replace(/\B(?=(\d{3})+(?!\d))/g, ' ');

                // Met à jour le champ visible avec la valeur formatée
                e.target.value = formatted;

                // Met à jour le champ caché avec la vraie valeur
                document.getElementById('price').value = val;
              });

      document.getElementById('price_vente_display').addEventListener('input', function(e) {
        let val = e.target.value.replace(/\D/g, '');

        let formatted = val.replace(/\B(?=(\d{3})+(?!\d))/g, ' ');

        e.target.value = formatted;

        document.getElementById('price_vente').value = val;
      });

      document.getElementById('price_min_display').addEventListener('input', function(e) {
        let val = e.target.value.replace(/\D/g, '');

        let formatted = val.replace(/\B(?=(\d{3})+(?!\d))/g, ' ');

        e.target.value = formatted;

        document.getElementById('price_min').value = val;
      });


  $(document).ready(function() {
    $(".select_group").select2();
    $('.select2').select2();
    $('.select2').select2({
  width: '100%' // force Select2 à prendre toute la largeur du parent
});
  
    $('#categorie').select2({
      placeholder: "Sélectionnez une ou plusieurs catégories",
      allowClear: true,
      width: '100%'
    });

    $("#description").wysihtml5();
     $('#marque, .select_group').select2({
    width: '100%'
  });

    $("#mainProductNav").addClass('active');
    $("#addProductNav").addClass('active');

    var btnCust = '<button type="button" class="btn btn-secondary" title="Add picture tags" ' +
      'onclick="alert(\'Call your custom code here.\')">' +
      '<i class="glyphicon glyphicon-tag"></i>' +
      '</button>';
    $("#product_image").fileinput({
      overwriteInitial: true,
      maxFileSize: 6500,
      showClose: false,
      showCaption: false,
      browseLabel: '',
      removeLabel: '',
      browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>',
      removeIcon: '<i class="glyphicon glyphicon-remove"></i>',
      removeTitle: 'Cancel or reset changes',
      elErrorContainer: '#kv-avatar-errors-1',
      msgErrorClass: 'alert alert-block alert-danger',
      // defaultPreviewContent: '<img src="/uploads/default_avatar_male.jpg" alt="Your Avatar">',
      layoutTemplates: {
        main2: '{preview} ' + btnCust + ' {remove} {browse}'
      },
      allowedFileExtensions: ["jpg", "png", "gif", "jpeg"]
    });

    const info = document.getElementById('info');
    const divSupp = document.getElementById('boxsuplementaire')
    const etat = document.getElementById('etat');
    const boxsuplementairekit = document.getElementById('boxsuplementairekit')

    info.addEventListener('change', () => {
      if (info.value == 1) {
        divSupp.innerHTML = `
            <label for="infoManque">Information</label>
            <textarea type="text" class="form-control" id="infoManque" name="infoManque" placeholder="Description sur des trucs manquants" autocomplete="off"></textarea>
        `;
      } else {
        divSupp.innerHTML ='';
      }
    })

    etat.addEventListener('change', () => {
      if (etat.value == 1) {
        boxsuplementairekit.innerHTML = `
            <label for="infoManquekit">Information sur le kit</label>
            <textarea type="text" class="form-control" id="infoManquekit" name="infoManquekit" placeholder="Description sur le kit" autocomplete="off"></textarea>
        `;
      } else {
        boxsuplementairekit.innerHTML ='';
      }
    })

  });
  // --- Vérification prix minimal vs prix de vente ---
const priceVenteInput = document.getElementById('price_vente');
const priceMinInput   = document.getElementById('price_min');

function verifierPrix() {
  const prixVente = parseFloat(priceVenteInput.value) || 0;
  const prixMin   = parseFloat(priceMinInput.value) || 0;

  if (prixMin > prixVente) {
    priceMinInput.style.borderColor = 'red';
    if (!document.getElementById('price_min_error')) {
      const small = document.createElement('small');
      small.id = 'price_min_error';
      small.style.color = 'red';
      small.textContent = 'Le prix minimal ne peut pas être supérieur au prix de vente';
      priceMinInput.parentNode.appendChild(small);
    }
  } else {
    priceMinInput.style.borderColor = '';
    const errorMsg = document.getElementById('price_min_error');
    if (errorMsg) errorMsg.remove();
  }
}

priceVenteInput.addEventListener('input', verifierPrix);
priceMinInput.addEventListener('input', verifierPrix);

// Vérification au submit
document.querySelector('form').addEventListener('submit', function(e) {
  const prixVente = parseFloat(priceVenteInput.value) || 0;
  const prixMin   = parseFloat(priceMinInput.value) || 0;

  if (prixMin > prixVente) {
    e.preventDefault();
    alert('❌ Le prix minimal ne peut pas être supérieur au prix de vente !');
    priceMinInput.focus();
  }
});



</script>