 <!-- CDN SweetAlert2 -->
 <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <h1>
      Gestion des
      <small>Décaissement</small>
    </h1>
    <ol class="breadcrumb">
      <li><a href="#"><i class="fa fa-dashboard"></i> Accueil</a></li>
      <li class="active">Décaissement</li>
    </ol>
  </section>

  <!-- Main content -->
  <section class="content">
    <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 elseif (session()->getFlashdata('errors')): ?>
          <div class="alert alert-warning 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('errors'); ?>
          </div>
        <?php endif; ?>

        <?php if (in_array('createSortieCaisse', $user_permission)): ?>
          <button class="btn btn-primary" data-toggle="modal" data-target="#createModal">Décaissement</button>
          <br><br>
        <?php endif; ?>

        
      <!-- FILTRES EN DESSUS DU TABLEAU -->
      <div class="row mb-3">
        <div class="col-md-2">
          <label for="startDate" class="form-label">Date de début</label>
          <input type="date" id="startDate" class="form-control">
        </div>
        <div class="col-md-2">
          <label for="endDate" class="form-label">Date de fin</label>
          <input type="date" id="endDate" class="form-control">
        </div>
        <div class="col-md-2">
          <label for="pvente" class="form-label">Point de vente</label>
          <select id="pvente" class="form-control">
            <option value="TOUS">TOUS</option>
            <?php foreach ($stores as $value): ?>
              <option value="<?= $value['name']; ?>"><?= $value['name']; ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-2">
          <label for="s_statut" class="form-label">Statut du décaissement</label>
          <select id="s_statut" class="form-control">
            <option value="TOUS">TOUS</option>
            <option value="Valider">Valider</option>
            <option value="En attente">En attente</option>
            <option value="Refuser">Refuser</option>
          </select>
        </div>
        <div class="col-md-1">
          <br>
          <button id="filteredB1" class="btn btn-primary w-100">Filtrer 🔍</button>
        </div>

        <div class="col-md-1">
          <br>
          <?php $session = session();
                $users = $session->get('user');
                $isAdmin = $users['group_name'] == "Direction" || $users['group_name'] == "Conseil";
                $isCaissier = $users['group_name'] == "Caissière";
                if($isAdmin): ?>
              <button id="validate_filtered" class="btn btn-primary w-100">A valider</button>
        <?php endif; ?>
        </div>
      </div>
      <br>

        <div class="box">
          <div class="box-header">
            <h3 class="box-title">Gérer les Décaissements</h3>
          </div>
          <div class="box-body">
            <table id="manageTable" class="table table-bordered table-striped">
              <thead>
                <tr>
                  <?php 
                    $session = session();
                    $users = $session->get('user');

                    if ($users['group_name'] === 'Caissière') {
                  ?>
                      <th>#</th>
                      <th>Montant</th>
                      <th>Date</th>
                      <th>Caissier</th>
                      <th>Motif</th>
                      <th>Statut</th>
                      <?php if (in_array('updateSortieCaisse', $user_permission)) { ?>
                        <th>Action</th>
                      <?php } ?>
                  <?php 
                    } elseif ($users['group_name'] === 'Direction' || $users['group_name'] === 'Conseil') {
                  ?>
                      <th>#</th>
                      <th>Montant</th>
                      <th>Date</th>
                      <th>Caissier</th>
                      <th>Motif</th>
                      <th>Source de fond</th>
                      <th>Initiateur de demande</th>
                      <th>Point de vente</th>
                      <th>Commentaire</th>
                      <th>Statut</th>
                      <?php if (in_array('updateSortieCaisse', $user_permission) || in_array('validateSortieCaisse', $user_permission)) { ?>
                        <th>Action</th>
                      <?php } ?>
                  <?php 
                    } else {
                  ?>
                      <th>#</th>
                      <th>Montant</th>
                      <th>Date</th>
                      <th>Caissier</th>
                      <th>Motif</th>
                      <th>Statut</th>
                      <th>Raison de validation</th>
                      <?php if (in_array('updateSortieCaisse', $user_permission)) { ?>
                        <th>Action</th>
                      <?php } ?>
                  <?php } ?>
                </tr>
              </thead>
            </table>
          </div>
        </div>

      </div>
    </div>
  ection>
</div>
  <!-- Modal pour la Création -->
  <?php if (in_array('createSortieCaisse', $user_permission)): ?>
    <!-- remove brand modal -->
    <div class="modal fade" tabindex="-1" role="dialog" id="createModal">
      <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title">Ajouter un décaissement</h4>
          </div>

          <form role="form"   id="create_form_sortie" enctype="multipart/form-data">
          <div class="modal-body"> 
            <div class="row">
              <div class="col-md-4 mb-3">
                <label for="montant_retire" class="form-label">Montant à retirer</label>
                <input type="text" class="form-control" id="montant_retire" name="montant_retire" placeholder="Montant à rétirer" autocomplete="off" required>
              </div>

              <div class="col-md-4 mb-3">
                <label for="motif_select" class="form-label">Motif</label>
                <select class="form-control" id="motif_select" name="motif_select" required>
                  <?php
                    $session = session();
                    $users = $session->get('user');
                    $isAdmin = $users['group_name'] == "Direction" || $users['group_name'] == "Conseil";
                    $isCaissier = $users['group_name'] == "Caissière";
                    $options = $isAdmin ? $admin_options : $caissier_options;
                    foreach ($options as $option) {
                      echo "<option value=\"" . htmlspecialchars($option) . "\">" . htmlspecialchars($option) . "</option>\n";
                    }
                  ?>
                  <option value="" selected>Veuiller slectionner une raison</option>
                </select>
              </div>

              <div class="col-md-4 mb-3">
                <label for="sortie_commentaire" class="form-label">Commentaire</label>
                <textarea class="form-control" id="sortie_commentaire" name="sortie_commentaire" rows="3" style="resize: vertical;" placeholder="Votre commentaire" autocomplete="off"></textarea>
              </div>
            </div>

            <div class="row">
              <div class="col-md-4 mb-3">
                <label for="sortie_fournisseur" class="form-label">Fournisseur & Prestataire</label>
                <input type="text" class="form-control" id="sortie_fournisseur" name="sortie_fournisseur" placeholder="Entrer le fournisseur ou le prestataire" autocomplete="off">
              </div>

              <div class="col-md-4 mb-3">
                <label for="sortie_nif" class="form-label">NIF & CIN</label>
                <input type="text" class="form-control" id="sortie_nif" name="sortie_nif" placeholder="NIF ou CIN" autocomplete="off">
              </div>

              <div class="col-md-4 mb-3">
                <label for="sortie_statistique" class="form-label">Statistique</label>
                <input type="text" class="form-control" id="sortie_statistique" name="sortie_statistique" placeholder="Statistique du décaissement" autocomplete="off">
              </div>
            </div>

            <div class="row " style="margin-top: 25px;">
              <div class="col-md-4 mb-3">
                <label for="sortie_phone" class="form-label">Numéro téléphone</label>
                <input type="text" class="form-control" id="sortie_phone" name="sortie_phone" placeholder="Entrer le numéro de téléphone" autocomplete="off" required>
              </div>

              <div class="col-md-4 mb-3">
                <label for="sortie_adresse" class="form-label">Code postal</label>
                <input type="text" class="form-control" id="sortie_adresse" name="sortie_adresse" placeholder="Entrer le code postal" autocomplete="off">
              </div>

              <div class="col-md-4 mb-3">
                <label for="sortie_preuve" class="form-label">Preuve d'achat</label>
                <input type="file" accept=".pdf, .txt, .xls, .xlsx, .csv" class="form-control" id="sortie_preuve" name="sortie_preuve">
              </div>
            </div>
          </div>


            <!-- Boutons avec espacement -->
            <div class="modal-footer text-right" style="margin-top: 15px;">
              <button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>
              <button type="submit" class="btn btn-primary" >Enregistrer</button>
            </div>
          </form>

        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

  <?php endif; ?>

  <!-- Modal for updatting a recouvrement -->
  <?php if (in_array('updateSortieCaisse', $user_permission)): ?>
    
    <div class="modal fade" tabindex="-1" role="dialog" id="updateModal">
      <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title">Modifier un décaissement</h4>
          </div>

          <form role="form" id="update_form" enctype="multipart/form-data">
            <div class="modal-body"> 
              <div class="row">
                <div class="col-md-4 mb-3">
                  <label for="montant_retire_edit" class="form-label">Montant à retirer</label>
                  <input type="text" class="form-control" id="montant_retire_edit" name="montant_retire_edit" placeholder="Montant à rétirer" autocomplete="off">
                </div>

                
              <div class="col-md-4 mb-3">
                <label for="motif_select" class="form-label">Motif</label>
                <select class="form-control" id="motif_select_edit" name="motif_select_edit">
                  <?php
                    $options = $isAdmin ? $admin_options : $caissier_options;
                    foreach ($options as $option) {
                      echo "<option value=\"" . htmlspecialchars($option) . "\">" . htmlspecialchars($option) . "</option>\n";
                    }
                  ?>
                  <option value="" selected>Veuiller slectionner une raison</option>
                </select>
              </div>

                <div class="col-md-4 mb-3">
                  <label for="sortie_commentaire_edit" class="form-label">Commentaire</label>
                  <textarea class="form-control" id="sortie_commentaire_edit" name="sortie_commentaire_edit" rows="3" style="resize: vertical;" placeholder="Votre commentaire" autocomplete="off"></textarea>
                </div>
              </div>

              <div class="row">
                <div class="col-md-4 mb-3">
                  <label for="sortie_fournisseur_edit" class="form-label">Fournisseur & Prestataire</label>
                  <input type="text" class="form-control" id="sortie_fournisseur_edit" name="sortie_fournisseur_edit" placeholder="Entrer le fournisseur ou le prestataire" autocomplete="off">
                </div>

                <div class="col-md-4 mb-3">
                  <label for="sortie_nif_edit" class="form-label">NIF & CIN</label>
                  <input type="text" class="form-control" id="sortie_nif_edit" name="sortie_nif_edit" placeholder="NIF ou CIN" autocomplete="off">
                </div>

                <div class="col-md-4 mb-3">
                  <label for="sortie_statistique_edit" class="form-label">Statistique</label>
                  <input type="text" class="form-control" id="sortie_statistique_edit" name="sortie_statistique_edit" placeholder="Statistique du décaissement" autocomplete="off">
                </div>
              </div>

              <div class="row" style="margin-top: 25px;">
                <div class="col-md-4 mb-3">
                  <label for="sortie_phone_edit" class="form-label">Numéro téléphone</label>
                  <input type="text" class="form-control" id="sortie_phone_edit" name="sortie_phone_edit" placeholder="Entrer le numéro de téléphone" autocomplete="off">
                </div>

                <div class="col-md-4 mb-3">
                  <label for="sortie_adresse_edit" class="form-label">Code postal</label>
                  <input type="text" class="form-control" id="sortie_adresse_edit" name="sortie_adresse_edit" placeholder="Entrer le code postal" autocomplete="off" required>
                </div>

                <div class="col-md-4 mb-3">
                  <label for="sortie_preuve_edit" class="form-label">Preuve d'achat</label>
                  <input type="file" accept=".pdf, .txt, .xls, .xlsx, .csv"  class="form-control" id="sortie_preuve_edit" name="sortie_preuve_edit">
                </div>
              </div>
            </div>

            <div class="modal-footer text-right" style="margin-top: 15px;">
              <button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>
              <button type="submit" class="btn btn-primary">Enregistrer</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  <?php endif; ?>




<!-- Modal for validating a recouvrement -->
<?php if (in_array('validateSortieCaisse', $user_permission)): ?>
    <div class="modal fade" tabindex="-1" role="dialog" id="validateModal">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">Valider un décaissement</h4>
          </div>

          <form role="form" action="<?php echo base_url('sortieCaisse/validateSortieCaisse') ?>" method="post" id="validate_form">
            <div class="modal-body">
              <div class="row form-group">
                <div class="col-lg-6">
                  <label for="validation" class="control-label">statut :</label>
                </div>

                <div class="col-lg-6">
                  <div class="form-group">
                    <label for="admin_raison">Raison de validation</label>
                    <input type="text" class="form-control" id="admin_raison" name="admin_raison">
                  </div>
                  <div class="form-group">
                    <label for="statut">Statut du décaissement</label>
                    <select name="statut" id="statut" class="form-control">
                      <option value="En attente" selected>En attente</option>
                      <option value="Valider">✔ Valider</option>
                      <option value="Refuser">✖ Refuser</option>
                    </select>
                  </div>
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>
              <button type="submit" class="btn btn-primary">Enregistrer</button>
            </div>
          </form>
        </div>
      </div>
    </div>
<?php endif; ?>




<script>
  $(document).ready(function() {
    // datatable-fr.js
            $.extend(true, $.fn.dataTable.defaults, {
                language: {
                    sProcessing:   "Traitement en cours...",
                    sSearch:       "Rechercher&nbsp;:",
                    sLengthMenu:   "Afficher _MENU_ &eacute;l&eacute;ments",
                    sInfo:         "Affichage de l'&eacute;lement _START_ &agrave; _END_ sur _TOTAL_ &eacute;l&eacute;ments",
                    sInfoEmpty:    "Affichage de l'&eacute;lement 0 &agrave; 0 sur 0 &eacute;l&eacute;ment",
                    sInfoFiltered: "(filtr&eacute; de _MAX_ &eacute;l&eacute;ments au total)",
                    sLoadingRecords: "Chargement en cours...",
                    sZeroRecords:  "Aucun &eacute;l&eacute;ment &agrave; afficher",
                    sEmptyTable:   "Aucune donn&eacute;e disponible dans le tableau",
                    oPaginate: {
                        sFirst:    "Premier",
                        sPrevious: "Pr&eacute;c&eacute;dent",
                        sNext:     "Suivant",
                        sLast:     "Dernier"
                    },
                    oAria: {
                        sSortAscending:  ": activer pour trier la colonne par ordre croissant",
                        sSortDescending: ": activer pour trier la colonne par ordre d&eacute;croissant"
                    }
                }
            });

    $("#sortie_caisse_menu").addClass('active');
    manageTable = $('#manageTable').DataTable({
    ajax: '<?= base_url('sortieCaisse/fetchSortieCaisseData') ?>',

    order: [],
    
    columnDefs: [
      { targets: 1, className: 'text-right rowmontant' }
      
    ]
  });
  
      $("#sortie_caisse_menu").addClass('active');

    });

    $('#filteredB1').on('click', function () {
            const startDate = $('#startDate').val();
            const endDate = $('#endDate').val();
            const pvente = $('#pvente').val();
            const s_statut = $('#s_statut').val();

            manageTable.ajax.url('<?= base_url('sortieCaisse/fetchSortieCaisseData') ?>').load(function () {
                const filteredData = [];

                manageTable.rows().every(function () {
                    const data = this.data();
                    const SortieDate = data[2].split(' ')[0]; 
                    const sortie_statut1 = data[9].split(' ')[0]; 
                  <?php if($isAdmin): ?>  const store = data[7];
                    <?php endif;?>
                    // Filter logic
                    const dateMatch = (!startDate && !endDate) ||
                        (startDate && endDate && SortieDate >= startDate && SortieDate <= endDate) ||
                        (startDate && !endDate && SortieDate >= startDate) ||
                        (!startDate && endDate && SortieDate <= endDate);

                    const storeMatch = (pvente === 'TOUS' || pvente === store);

                    const statutMatch = (s_statut === 'TOUS' || s_statut === sortie_statut1);
                    
                    if (dateMatch && storeMatch && statutMatch) {
                        filteredData.push(data);
                    }
                });

                // Clear and reload table with filtered data
                manageTable.clear().rows.add(filteredData).draw();
            });
        });


        $('#validate_filtered').on('click', function () {
            const startDate = $('#startDate').val();
            const endDate = $('#endDate').val();
            const pvente = $('#pvente').val();
            const s_statut = $('#s_statut').val();

            manageTable.ajax.url('<?= base_url('sortieCaisse/fetchSortieCaisseData1') ?>').load(function () {
                const filteredData = [];

                manageTable.rows().every(function () {
                    const data = this.data();
                    const SortieDate = data[2].split(' ')[0]; 
                    const sortie_statut1 = data[9].split(' ')[0]; 
                  <?php if($isAdmin): ?>  const store = data[7];
                    <?php endif;?>
                    // Filter logic
                    const dateMatch = (!startDate && !endDate) ||
                        (startDate && endDate && SortieDate >= startDate && SortieDate <= endDate) ||
                        (startDate && !endDate && SortieDate >= startDate) ||
                        (!startDate && endDate && SortieDate <= endDate);

                    const storeMatch = (pvente === 'TOUS' || pvente === store);

                    const statutMatch = (s_statut === 'TOUS' || s_statut === sortie_statut1);
                    
                    if (dateMatch && storeMatch && statutMatch) {
                        filteredData.push(data);
                    }
                });

                // Clear and reload table with filtered data
                manageTable.clear().rows.add(filteredData).draw();
            });
        });


  $("#create_form_sortie").unbind('submit').on('submit', function() {
      var form = $(this);

      // remove the text-danger
      $(".text-danger").remove();

      var form = $('#create_form_sortie')[0]; 
      var formData = new FormData(form);

      $.ajax({
        url: '<?= base_url('sortieCaisse/createSortieCaisse') ?>',
        type: 'post',
        data: formData,
        processData: false, 
        contentType: false, 
        dataType: 'json',
        success: function(response) {

          manageTable.ajax.reload(null, false);

          if (response.success === true) {
            $("#messages").html('<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>' +
              '<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>' + response.messages +
              '</div>');


            // hide the modal
            $("#createModal").modal('hide');

            // reset the form
            $("#create_form_sortie")[0].reset();
            $("#create_form_sortie .form-group").removeClass('has-error').removeClass('has-success');

          } else {

            if (response.messages instanceof Object) {
              $.each(response.messages, function(index, value) {
                var id = $("#" + index);

                id.closest('.form-group')
                  .removeClass('has-error')
                  .removeClass('has-success')
                  .addClass(value.length > 0 ? 'has-error' : 'has-success');

                id.after(value);
                $("#createModal").modal('hide');
              });
              $("#createModal").modal('hide');
            } else {
              $("#messages").html('<div class="alert alert-warning alert-dismissible" role="alert">' +
                '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
                '<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>' + response.messages +
                '</div>');
            }
            $("#createModal").modal('hide');
          }
        }
      });

      return false;
    });


  // update function
  function editFunc(id) {
  $.ajax({
    url: '<?= base_url('sortieCaisse/fetchSortieCaisseSingle') ?>/' + id,
    type: 'post',
    dataType: 'json',
    success: function(response) {
      // Remplir les champs avec les données récupérées
      $("#montant_retire_edit").val(response.montant_retire);
      $("#sortie_commentaire_edit").val(response.commentaire);
      $("#sortie_fournisseur_edit").val(response.fournisseur);
      $("#sortie_nif_edit").val(response.nif_cin);
      $("#sortie_statistique_edit").val(response.statistique);
      $("#sortie_phone_edit").val(response.phone);
      $("#sortie_adresse_edit").val(response.adresse);

      // Sélectionner la bonne option du motif (si elle existe)
      const motif = response.motif;
      const motifSelect = $("#motif_select_edit");
      const optionExists = motifSelect.find('option').filter(function() {
        return $(this).val().trim().toLowerCase() === motif.trim().toLowerCase();
      }).length > 0;

      if (optionExists) {
        motifSelect.val(motif);
      } else {
        motifSelect.val(""); // Aucun motif valide trouvé, on laisse la sélection vide
      }

      // Gestion du formulaire d'envoi
      $("#update_form").unbind('submit').bind('submit', function() {
        var form = $(this);
        $(".text-danger").remove();

        var formData = new FormData(this);

        $.ajax({
          url: form.attr('action') + '/' + id,
          type: form.attr('method'),
          data: formData,
          processData: false,
          contentType: false,
          dataType: 'json',
          success: function(response) {
            manageTable.ajax.reload(null, false);

            if (response.success === true) {
              $("#messages").html(
                '<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>' +
                '<strong><span class="glyphicon glyphicon-ok-sign"></span></strong> ' +
                response.messages + '</div>'
              );
              $("#updateModal").modal('hide');
              $("#update_form .form-group").removeClass('has-error has-success');
            } else {
              if (response.messages instanceof Object) {
                $.each(response.messages, function(index, value) {
                  var id = $("#" + index);
                  id.closest('.form-group')
                    .removeClass('has-error has-success')
                    .addClass(value.length > 0 ? 'has-error' : 'has-success');
                  id.after(value);
                });
              } else {
                $("#messages").html(
                  '<div class="alert alert-warning alert-dismissible" role="alert">' +
                  '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
                  '<span aria-hidden="true">&times;</span></button>' +
                  '<strong><span class="glyphicon glyphicon-exclamation-sign"></span></strong> ' +
                  response.messages + '</div>'
                );
              }
            }
          }
        });

        return false;
      });
    }
  });
}

function validateFunc(id) {
  $.ajax({
    url: '<?= base_url('sortieCaisse/fetchSortieCaisseSingle') ?>/' + id,
    type: 'post',
    dataType: 'json',
    success: function(response) {
      var statut = response.statut;

      if (statut === "En attente" || statut === "Refuser") {

        // Remplir les champs
        $("#statut").val(response.statut);
        $("#admin_raison").val(response.admin_raison);
        // Afficher le modal de validation
        $("#validateModal").modal('show');

        // Soumission du formulaire
        $("#validate_form").unbind('submit').bind('submit', function(e) {
          e.preventDefault();

          var form = $(this);
          $(".text-danger").remove();

          $.ajax({
            url: form.attr('action').replace(/\/?$/, '/') + id,
            type: form.attr('method'),
            data: form.serialize(),
            dataType: 'json',
            success: function(response) {
              manageTable.ajax.reload(null, false);

              if (response.success === true) {
                $("#messages").html('<div class="alert alert-success alert-dismissible" role="alert">' +
                  '<button type="button" class="close" data-dismiss="alert">&times;</button>' +
                  '<strong><span class="glyphicon glyphicon-ok-sign"></span></strong> ' + response.messages +
                  '</div>');

                $("#validateModal").modal('hide');
                $("#validate_form .form-group").removeClass('has-error has-success');
              } else {
                if (typeof response.messages === 'object') {
                  $.each(response.messages, function(index, value) {
                    var input = $("#" + index);
                    input.closest('.form-group')
                      .removeClass('has-error has-success')
                      .addClass(value.length > 0 ? 'has-error' : 'has-success');
                    input.after('<span class="text-danger">' + value + '</span>');
                  });
                } else {
                  $("#messages").html('<div class="alert alert-warning alert-dismissible" role="alert">' +
                    '<button type="button" class="close" data-dismiss="alert">&times;</button>' +
                    '<strong><span class="glyphicon glyphicon-exclamation-sign"></span></strong> ' + response.messages +
                    '</div>');
                }
              }
            }
          });
        });

      } else {
        // Afficher un message si le décaissement est déjà validé
        Swal.fire({
          icon: 'info',
          title: '<span style="font-size: 24px;">Déjà validé</span>',
          html: '<p style="font-size: 16px;">Ce décaissement est déjà validé et ne peut pas être modifié.</p>',
          confirmButtonText: 'OK',
          width: '500px',
          position: 'top-center'
        });


      }
    },
    error: function() {
      Swal.fire({
        icon: 'error',
        title: 'Erreur',
        text: 'Une erreur est survenue lors de la récupération des données.',
        confirmButtonText: 'OK'
      });
    }
  });
}

</script>