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

  <section class="content">
    <div id="messages"></div>

    <?php if (in_array('createAvance', $user_permission)): ?>
      <button class="btn btn-primary" data-toggle="modal" data-target="#createModal">AJOUTER UNE AVANCE</button>
      <br /><br />
    <?php endif; ?>
    
    <div class="row">
      <div class="col-md-3">
        <button id="avance_no_order" class="btn btn-warning w-100 rounded-pill shadow-sm py-2">
          <i class="fas fa-hourglass-half me-2"></i> Avances Incomplètes
        </button>
      </div>
      <div class="col-md-3">
        <button id="avance_order" class="btn btn-success w-100 rounded-pill shadow-sm py-2">
          <i class="fas fa-check-circle me-2"></i> Avances Complètes
        </button>
      </div>
      <div class="col-md-3">
        <button id="avance_expired" class="btn btn-outline-danger w-100 rounded-pill shadow-sm py-2 fw-bold border-2">
          <i class="fas fa-exclamation-circle me-2"></i> Avances Expirées
        </button>

      </div>
    </div>
    <br>
    
    <div class="box">
      <div class="box-header"><h3 class="box-title">Liste des avances</h3></div>
      <div class="box-body">
        <table id="avanceTable" class="table table-bordered table-striped">
          <thead>
            <?php  $session = session();
              $users   = $session->get('user');
              $isAdmin = in_array($users['group_name'], ['Conseil', 'Direction']);
              $isCommerciale = in_array($users['group_name'], ['COMMERCIALE']);
              $isCaissier = in_array($users['group_name'], ['Caissier']);
                if ($isAdmin): ?>
                <tr>
                  <th>Client</th>
                  <th>Téléphone</th>
                  <th>Adresse</th>
                  <th>Produit</th>
                  <th>Prix</th>
                  <th>Avance</th>
                  <th>Reste à payer</th>
                  <th>Date</th>
                  <?php if (in_array('updateAvance', $user_permission) || in_array('deleteAvance', $user_permission)): ?>
                    <th>Action</th>
                  <?php endif;?>
                </tr>
            <?php endif;?>
            <?php  $session = session();
              $users   = $session->get('user');
              $isAdmin = in_array($users['group_name'], ['Conseil', 'Direction']);
              $isCommerciale = in_array($users['group_name'], ['COMMERCIALE']);
              $isCaissier = in_array($users['group_name'], ['Caissier']);
                if ($isCommerciale || $isCaissier): ?>
                <tr>
                  <th>#</th>
                  <th>Produit</th>
                  <th>Avance</th>
                  <th>Reste à payer</th>
                  <th>Date</th>
                  <?php if (in_array('updateAvance', $user_permission) || in_array('deleteAvance', $user_permission) ||in_array('viewAvance', $user_permission)): ?>
                    <th>Action</th>
                  <?php endif;?>
                </tr>
            <?php endif;?>   
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div>
  </section>
</div>

<!-- Modal Création -->
<?php if (in_array('createAvance', $user_permission)): ?>
<div class="modal fade" id="createModal" tabindex="-1" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="create_avance_form">
        <div class="modal-header">
          <h4 class="modal-title"> Ajouter une avance  </h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        
        <div class="modal-body">
          <div class="row">
            <!-- type d'avance  -->
         <!-- <div class="form-group col-md-6">
            <label for="id_product" class="form-label">Type d'avance</label>
              <select name="id_product" id="id_product" class="form-control " required>
                     <option value="" disabled selected>Sélectionnez un type d'avance </option>
                     <option value="terre">Avance sur terre</option>
                    <option value="mere">Avance sur mère</option>
              </select>
       </div> -->
       <div class="form-group col-md-6">
          <label for="type_avance" class="form-label">Type d'avance</label>
          <select name="type_avance" id="type_avance" class="form-control" required>
              <option value="" disabled selected>Sélectionnez un type d'avance</option>
              <option value="terre">Avance sur terre</option>
              <option value="mere">Avance sur mère</option>
          </select>
      </div>
            <!-- Nom client -->
            <div class="form-group col-md-6">
              <label>Nom du client</label>
              <input type="text" name="customer_name_avance" id="customer_name_avance" class="form-control" required>
            </div>
            <!-- Téléphone client -->
            <div class="form-group col-md-6">
              <label>Téléphone du client</label>
              <input type="text" name="customer_phone_avance" id="customer_phone_avance" class="form-control" required>
            </div>
          </div>

          <div class="row">
            <!-- Adresse client -->
            <div class="form-group col-md-6">
              <label>Adresse du client</label>
              <input type="text" name="customer_address_avance" id="customer_address_avance" class="form-control" required>
            </div>
            <!-- CIN client -->
            <div class="form-group col-md-6">
              <label>CIN du client</label>
              <input type="text" name="customer_cin_avance" id="customer_cin_avance" class="form-control" required>
            </div>
          </div>

          <div class="row">
            <!-- Produit -->
            <div class="form-group col-md-6">
                <label for="id_product" class="form-label">Produit</label>
                <select name="id_product" id="id_product" class="form-control" onchange="getProductDataCreate()" required>
                    <option value="">Sélectionnez un produit</option>
                    <?php foreach($products as $p): ?>
                        <option value="<?= $p['id'] ?>" <?= $p['product_sold'] ? 'disabled' : '' ?>>
                            <?= esc($p['name']) ?> <?= $p['product_sold'] ? '(Rupture)' : '' ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <!-- Prix brut -->
            <div class="form-group col-md-6">
              <label>Prix du produit</label>
              <input type="text" name="gross_amount" id="gross_amount" class="form-control" readonly>
            </div>
          </div>

          <div class="row">
            <!-- Avance -->
            <div class="form-group col-md-6">
              <label>Avance</label>
              <input type="number" name="avance_amount" id="avance_amount" class="form-control" onkeyup="updateDueCreate()" required>
            </div>
            <!-- Reste à payer -->
            <div class="form-group col-md-6">
              <label>Reste à payer</label>
              <input type="text" name="amount_due" id="amount_due" class="form-control" readonly>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-primary">Enregistrer</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php endif; ?>

<!-- Modal Modification -->
<?php if (in_array('updateAvance', $user_permission)): ?>
<div class="modal fade" id="updateModal" tabindex="-1" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="update_avance_form" method="post">
        <input type="hidden" name="id" id="avance_id_edit">
        <div class="modal-header">
          <h4 class="modal-title">Modifier une avance</h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body">
          <div class="row">
            <!-- Type d'avance -->
            <div class="form-group col-md-6">
              <label for="type_avance_edit" class="form-label">Type d'avance</label>
              <select name="type_avance_edit" id="type_avance_edit" class="form-control" required>
                  <option value="" disabled>Sélectionnez un type d'avance</option>
                  <option value="terre">Avance sur terre</option>
                  <option value="mere">Avance sur mère</option>
              </select>
            </div>

            <!-- Nom client -->
            <div class="form-group col-md-6">
              <label>Nom du client</label>
              <input type="text" name="customer_name_avance_edit" id="customer_name_avance_edit" class="form-control" required>
            </div>

            <!-- Téléphone client -->
            <div class="form-group col-md-6">
              <label>Téléphone du client</label>
              <input type="text" name="customer_phone_avance_edit" id="customer_phone_avance_edit" class="form-control" required>
            </div>

            <!-- Adresse client -->
            <div class="form-group col-md-6">
              <label>Adresse du client</label>
              <input type="text" name="customer_address_avance_edit" id="customer_address_avance_edit" class="form-control" required>
            </div>

            <!-- CIN client -->
            <div class="form-group col-md-6">
              <label>CIN du client</label>
              <input type="text" name="customer_cin_avance_edit" id="customer_cin_avance_edit" class="form-control" required>
            </div>

            <!-- Produit -->
            <div class="form-group col-md-6">
              <label class="form_label">Produit</label>
              <select name="id_product_edit" id="id_product_edit" class="form-control" onchange="getProductDataUpdate()" required>
                <option value="">Sélectionnez un produit</option>
                <?php foreach($products as $p): ?>
                  <option value="<?= $p['id'] ?>" <?= $p['product_sold'] ? 'disabled' : '' ?>>
                    <?= esc($p['name']) ?> <?= $p['product_sold'] ? '(Rupture)' : '' ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>

            <!-- Prix du produit -->
            <div class="form-group col-md-6">
              <label>Prix du produit</label>
              <input type="text" name="gross_amount_edit" id="gross_amount_edit" class="form-control" readonly>
            </div>

            <!-- Avance -->
            <div class="form-group col-md-6">
              <label>Avance</label>
              <input type="number" name="avance_amount_edit" id="avance_amount_edit" class="form-control" onkeyup="updateDueEdit()" required>
            </div>

            <!-- Reste à payer -->
            <div class="form-group col-md-6">
              <label>Reste à payer</label>
              <input type="text" name="amount_due_edit" id="amount_due_edit" class="form-control" readonly>
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button type="submit" class="btn btn-success">Modifier</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php endif;?>


<?php if (in_array('deleteAvance', $user_permission)): ?>
  <!-- remove brand modal -->
  <div class="modal fade" tabindex="-1" role="dialog" id="removeModal">
    <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">Supprimer cette avance</h4>
        </div>
        <form role="form" action="<?php echo base_url('avances/deleteAvance') ?>" method="post" id="removeForm">
          <input type="hidden" name="avance_id" value="">
          <input type="hidden" name="product_id" value="">
          <div class="modal-body">
            <p>Voulez-vous vraiment supprimer ?</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>
            <button type="submit" class="btn btn-primary">Oui</button>
          </div>
        </form>
      </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
  </div><!-- /.modal -->
<?php endif; ?>

  
<script>
var base_url = "<?= base_url() ?>", brutCreate = 0, brutEdit = 0;

$(document).ready(function() {

    $('#avance_menu').addClass("active");
    $('.select2').select2();

    // 📌 Configuration langue FR
    var datatableLangFr = {
        lengthMenu: "Afficher _MENU_ enregistrements par page",
        zeroRecords: "Aucun résultat trouvé",
        info: "Affichage de _START_ à _END_ sur _TOTAL_ enregistrements",
        infoEmpty: "Aucun enregistrement disponible",
        infoFiltered: "(filtré depuis _MAX_ enregistrements au total)",
        search: "Rechercher :",
        paginate: {
            first:    "Premier",
            last:     "Dernier",
            next:     "Suivant",
            previous: "Précédent"
        }
    };

    // 📌 Fonction pour initialiser la DataTable
    function initAvanceTable(url, columns) {
        if ($.fn.DataTable.isDataTable('#avanceTable')) {
            $('#avanceTable').DataTable().destroy();
        }
        return $('#avanceTable').DataTable({
            ajax: url,
            columns: columns,
            language: datatableLangFr
        });
    }

    // 🔄 FONCTION DE MISE À JOUR DYNAMIQUE DE LA DATATABLE
    function refreshDataTable() {
        if (typeof manageTable !== 'undefined' && manageTable) {
            manageTable.ajax.reload(null, false); // Recharger seulement les données de la table
        }
    }

    <?php if ($isAdmin): ?>
        var adminColumns = [
            { title: "Client" },
            { title: "Téléphone" },
            { title: "Adresse" },
            { title: "Produit" },
            { title: "Prix" },
            { title: "Avance" },
            { title: "Reste à payer" },
            { title: "Date" }
            <?php if (in_array('updateAvance', $user_permission) || in_array('deleteAvance', $user_permission)): ?>
                ,{ title: "Action", orderable: false, searchable: false }
            <?php endif; ?>
        ];

        var manageTable = initAvanceTable('fetchAvanceData', adminColumns);

        $('#avance_order').on('click', function () {
            manageTable = initAvanceTable('fetchAvanceBecameOrder', adminColumns);
        });

        $('#avance_expired').on('click', function () {
            manageTable = initAvanceTable('fetchExpiredAvance', adminColumns);
        });

        $('#avance_no_order').on('click', function () {
            manageTable = initAvanceTable('fetchAvanceData', adminColumns);
        });
    <?php endif; ?>

    <?php if ($isCaissier || $isCommerciale): ?>
        var userColumns = [
            { title: "#" },
            { title: "Produit" },
            { title: "Avance" },
            { title: "Reste à payer" },
            { title: "Date" }
            <?php if (in_array('updateAvance', $user_permission) || in_array('deleteAvance', $user_permission)): ?>
                ,{ title: "Action", orderable: false, searchable: false }
            <?php endif; ?>
        ];

        var manageTable = initAvanceTable('fetchAvanceData', userColumns);

        $('#avance_order').on('click', function () {
            manageTable = initAvanceTable('fetchAvanceBecameOrder', userColumns);
        });

        $('#avance_no_order').on('click', function () {
            manageTable = initAvanceTable('fetchAvanceData', userColumns);
        });
    <?php endif; ?>

    // ✅ CRÉATION avec actualisation automatique
    $('#create_avance_form').on('submit', function(e) {
        e.preventDefault();
        const $form = $(this);
        var brut = parseFloat($('#gross_amount').val()) || 0;
        var avance = parseFloat($('#avance_amount').val()) || 0;
        var minAvance = brut * 0.25;

        if (avance < minAvance) {
            $("#messages").html(`
                <div class="alert alert-danger 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>
                    L'avance doit être au minimum de 25% du prix du produit (${minAvance.toFixed(2)} Ar).
                </div>
            `);
            return;
        }

        // Désactiver le bouton de soumission
        $form.find('button[type="submit"]').prop('disabled', true).text('Enregistrement...');

        $.post('/avances/createAvance', $form.serialize(), function(res) {
            if (res.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> ${res.messages}
                    </div>
                `);
                $("#createModal").modal('hide');
                $form[0].reset(); // Reset le formulaire
                
                // 🔄 MISE À JOUR DYNAMIQUE après ajout
                refreshDataTable();
                
                // Auto-masquer le message après 3 secondes
                setTimeout(function() {
                    $("#messages .alert").fadeOut();
                }, 3000);
                
            } else {
                $("#createModal").modal('hide');
                $("#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> ${res.messages}
                    </div>
                `);
                // Réactiver le bouton en cas d'erreur
                $form.find('button[type="submit"]').prop('disabled', false).text('Enregistrer');
            }
        }, 'json');
    });

    // 🔥 SUPPRESSION avec actualisation automatique
    window.removeFunc = function(id, product_id) {
        $('#removeModal').modal('show');
        $('#removeForm input[name="avance_id"]').val(id);
        $('#removeForm input[name="product_id"]').val(product_id);
    };

    $('#removeForm').on('submit', function(e) {
        e.preventDefault();

        var form = $(this);
        var submitButton = form.find('button[type="submit"]');
        
        // Désactiver le bouton
        submitButton.prop('disabled', true).text('Suppression...');
        
        $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: form.serialize(),
            dataType: 'json',
            success: function(response) {
                if (response.success === true) {
                    $('#removeModal').modal('hide');
                    
                    $("#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>
                    `);
                    
                    // 🔄 MISE À JOUR DYNAMIQUE après suppression
                    refreshDataTable();
                    
                    // Auto-masquer le message après 3 secondes
                    setTimeout(function() {
                        $("#messages .alert").fadeOut();
                    }, 3000);
                    
                } else {
                    $('#removeModal').modal('hide');
                    $("#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>
                    `);
                }
            },
            error: function(xhr, status, error) {
                console.log('Erreur AJAX:', error);
                $('#removeModal').modal('hide');
                
                $("#messages").html(`
                    <div class="alert alert-danger 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> Une erreur est survenue lors de la suppression.
                    </div>
                `);
            },
            complete: function() {
                submitButton.prop('disabled', false).text('Oui');
            }
        });

        return false;
    });

    // Réinitialiser le modal à la fermeture
    $('#removeModal').on('hidden.bs.modal', function() {
        $('#removeForm')[0].reset();
        $('#removeForm button[type="submit"]').prop('disabled', false).text('Oui');
    });

}); // Fin document.ready

// --- Fonctions utilitaires ---
function getProductDataCreate() {
    var id = $('#id_product').val();
    if (!id) {
        brutCreate = 0;
        $('#gross_amount,#amount_due,#avance_amount').val('');
        return;
    }
    $.post(base_url + 'orders/getProductValueById', { product_id: id }, function(r) {
        brutCreate = parseFloat(r.prix_vente) || 0;
        $('#gross_amount').val(brutCreate.toFixed(2));
        var avance25 = brutCreate * 0.25;
        $('#avance_amount').val(avance25.toFixed(2));
        $('#amount_due').val((brutCreate - avance25).toFixed(2));
        updateDueCreate();
    }, 'json');
}

function updateDueCreate() {
    var av = parseFloat($('#avance_amount').val()) || 0;
    var brutAmount = parseFloat($('#gross_amount').val()) || 0;
    $('#amount_due').val(Math.max(brutAmount - av, 0));
}

function getProductDataUpdate() {
    var id = $('#id_product_edit').val();
    console.log('getProductDataUpdate appelée avec ID:', id); // Pour déboguer
    
    if (!id) {
        brutEdit = 0;
        $('#gross_amount_edit,#amount_due_edit,#avance_amount_edit').val('');
        return;
    }
    
    $.ajax({
        url: base_url + 'orders/getProductValueById',
        type: 'POST',
        data: { product_id: id },
        dataType: 'json',
        success: function(r) {
            console.log('Données produit reçues:', r); // Pour déboguer
            
            brutEdit = parseFloat(r.prix_vente) || 0;
            $('#gross_amount_edit').val(brutEdit.toFixed(2));
            var avance25 = brutEdit * 0.25;
            $('#avance_amount_edit').val(avance25.toFixed(2));
            $('#amount_due_edit').val((brutEdit - avance25).toFixed(2));
            updateDueEdit();
        },
        error: function(xhr, status, error) {
            console.log('Erreur lors de la récupération des données produit:', error);
        }
    });
}

function updateDueEdit() {
    var av = parseFloat($('#avance_amount_edit').val()) || 0;
    $('#amount_due_edit').val(Math.max(brutEdit - av, 0).toFixed(2));
}

// ✅ MODIFICATION avec mise à jour dynamique - CORRIGÉ
function editFunc(id) {
    // Réinitialiser d'abord le formulaire
    $('#update_avance_form')[0].reset();
    
    $.getJSON(base_url + 'avances/fetchSingleAvance/' + id, function(r) {
        console.log('Données récupérées:', r); // Pour déboguer
        
        // Pré-remplir le formulaire de modification avec les BONS IDs
        $('#avance_id_edit').val(r.id || id); // Le champ caché pour l'ID
        $('#customer_name_avance_edit').val(r.customer_name || '');
        $('#customer_phone_avance_edit').val(r.customer_phone || '');
        $('#customer_address_avance_edit').val(r.customer_address || r.customer_adress || '');
        $('#customer_cin_avance_edit').val(r.customer_cin || '');
        $('#type_avance_edit').val(r.type_avance || '');
        $('#gross_amount_edit').val(r.gross_amount || '');
        $('#avance_amount_edit').val(r.avance_amount || '');
        $('#amount_due_edit').val(r.amount_due || '');
        
        // 🔥 CORRECTION PRINCIPALE - Sélection du produit avec toutes les variantes possibles
        var productId = r.product_id || r.id_product || r.productId || r.idProduct;
        console.log('Product ID trouvé:', productId); 
        console.log('Options disponibles:', $('#id_product_edit option').length);
        
        brutEdit = parseFloat(r.gross_amount || 0); // Utiliser gross_amount directement
        
        // Réinitialiser le bouton
        $('#update_avance_form button[type="submit"]').prop('disabled', false).text('Modifier');
        
        // Ouvrir le modal
        $('#updateModal').modal('show');
        
        // 🔥 SÉLECTION DU PRODUIT après ouverture complète du modal
        $('#updateModal').on('shown.bs.modal', function() {
            if (productId) {
                console.log('Tentative de sélection du produit ID:', productId);
                
                // Méthode 1: Sélection standard
                $('#id_product_edit').val(productId);
                console.log('Après sélection standard:', $('#id_product_edit').val());
                
                // Méthode 2: Si la sélection standard ne marche pas
                if ($('#id_product_edit').val() != productId) {
                    $('#id_product_edit option').each(function() {
                        if ($(this).val() == productId) {
                            $(this).prop('selected', true);
                            console.log('Produit sélectionné via boucle:', $(this).val(), $(this).text());
                        }
                    });
                }
                
                // Déclencher l'événement change pour mettre à jour le prix
                $('#id_product_edit').trigger('change');
                console.log('Valeur finale du select:', $('#id_product_edit').val());
            }
            
            // Détacher l'événement pour éviter les appels multiples
            $('#updateModal').off('shown.bs.modal');
        });

        // 🔥 Détacher tous les anciens événements et attacher le nouveau
        $('#update_avance_form').off('submit').on('submit', function(e) {
            e.preventDefault();
            
            var $form = $(this);
            var $submitBtn = $form.find('button[type="submit"]');
            var avance = parseFloat($('#avance_amount_edit').val()) || 0;
            var minAvance = brutEdit * 0.25;

            // Validation 25%
            if (avance < minAvance) {
                $("#messages").html(`
                    <div class="alert alert-danger 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>
                        L'avance doit être au minimum de 25% du prix du produit (${minAvance.toFixed(2)} Ar).
                    </div>
                `);
                return;
            }

            // Désactiver le bouton pendant l'opération
            $submitBtn.prop('disabled', true).text('Modification...');

            $.ajax({
                url: base_url + 'avances/updateAvance/' + id,
                type: 'POST',
                data: $form.serialize(),
                dataType: 'json',
                success: function(res) {
                    if (res.success === true) {
                        // Fermer le modal
                        $('#updateModal').modal('hide');
                        
                        // Message de succès
                        $("#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> ${res.messages}
                            </div>
                        `);
                        
                        // 🔄 MISE À JOUR IMMÉDIATE de la DataTable
                        refreshDataTable();
                        
                        // Auto-masquer le message
                        setTimeout(function() {
                            $("#messages .alert").fadeOut();
                        }, 3000);
                        
                    } else {
                        $("#messages").html(`
                            <div class="alert alert-danger 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> ${res.messages}
                            </div>
                        `);
                    }
                },
                error: function(xhr, status, error) {
                    console.log('Erreur lors de la modification:', error);
                    $("#messages").html(`
                        <div class="alert alert-danger 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> Erreur lors de la modification.
                        </div>
                    `);
                },
                complete: function() {
                    // Réactiver le bouton dans tous les cas
                    $submitBtn.prop('disabled', false).text('Modifier');
                }
            });
        });
    }).fail(function() {
        console.log('Erreur lors du chargement des données');
        $("#messages").html(`
            <div class="alert alert-danger 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> Erreur lors du chargement des données.
            </div>
        `);
    });

    // Réinitialiser le modal à la fermeture
    $('#updateModal').on('hidden.bs.modal', function() {
        $('#update_avance_form')[0].reset();
        $('#update_avance_form button[type="submit"]').prop('disabled', false).text('Modifier');
    });
}
</script>