<!-- 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="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'], ['Direction', 'SuperAdmin']);
              $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'], ['Direction', 'SuperAdmin']);
              $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">
          <!-- Nom client -->
          <div class="form-group">
            <label>Nom du client</label>
            <input type="text" name="customer_name_avance" id="customer_name_avance" class="form-control" required>
          </div>
          <!-- Produit -->
          <div class="form-group">
            <label>Produit</label>
            <select name="id_product" id="id_product" class="form-control select2" 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">
            <label>Prix du produit</label>
            <input type="text" id="gross_amount" class="form-control" readonly>
          </div>
          <!-- Avance -->
          <div class="form-group">
            <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">
            <label>Reste à payer</label>
            <input type="text" name="amount_due" id="amount_due" class="form-control" readonly>
          </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">
          <!-- Nom client -->
          <div class="form-group">
            <label>Nom du client</label>
            <input type="text" name="customer_name" id="customer_name_avance_edit" class="form-control" required>
          </div>
          <!-- Téléphone client -->
          <div class="form-group">
            <label>Téléphone du client</label>
            <input type="text" name="customer_phone_edit" id="customer_phone_avance_edit" class="form-control" required>
          </div>
          <!-- Adresse client -->
          <div class="form-group">
            <label>Adresse du client</label>
            <input type="text" name="customer_adress_avance_edit" id="customer_adress_avance_edit" class="form-control" required>
          </div>
          <!-- Avance -->
          <div class="form-group">
            <label>Avance</label>
            <input type="number" name="avance_amount" id="avance_amount_edit" class="form-control" onkeyup="updateDueEdit()" required>
          </div>
          <!-- Reste à payer -->
          <div class="form-group">
            <label>Reste à payer</label>
            <input type="text" name="amount_due" id="amount_due_edit" class="form-control" readonly>
          </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;?>

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

  $(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"
        }
    }
});

    $('avance_menu').addClass("active");
    $('.select2').select2();
    manageTable = $('#avanceTable').DataTable({
      ajax: '<?= base_url('avance/fetchAvanceData')?>',
      columns: []
    });

    // Création AJAX
    $('#create_avance_form').on('submit', function(e) {
      e.preventDefault();
      const $form = $(this);
      $.post($form.attr('action'), $form.serialize(), function(res) {
        if (res.success === true) {
          
          manageTable.ajax.reload(null, false);

          $("#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>`
          );

          // Cacher le modal de création
          $("#createModal").modal('hide');

          
          $form[0].reset();
        } 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>`
          );
        }
      }, 'json');
    });

  });

  // Récupère prix pour création
  function getProductDataCreate(){
    var id = $('#id_product').val();
    if(!id){ brutCreate=0; $('#gross_amount_create,#amount_due_create').val(''); return; }
    $.post(base_url+'orders/getProductValueById',{product_id:id}, function(r){
      brutCreate = parseFloat(r.prix_vente)||0;
      $('#gross_amount_create').val(brutCreate);
      updateDueCreate();
    },'json');
  }
  function updateDueCreate(){
    var av = parseFloat($('#avance_amount_create').val())||0;
    $('#amount_due_create').val(Math.max(brutCreate-av,0));
  }

  // Prépare et affiche modal édition
  function editFunc(id) {
  // Récupération des données de l'avance
  $.getJSON(base_url + 'avances/fetchSingleAvance/' + id, function(r) {
    // Préremplissage du modal
    $('#customer_name_avance_edit').val(r.customer_name);
    $('#customer_phone_avance_edit').val(r.customer_phone);
    $('#customer_adress_avance_edit').val(r.customer_adress);
    $('#avance_amount_edit').val(r.avance_amount);
    $('#amount_due_edit').val(r.amount_due);

    // Calcul du montant brut initial
    brutEdit = parseFloat(r.avance_amount) + parseFloat(r.amount_due);

    // Affiche le modal
    $('#updateModal').modal('show');

    $('#update_avance_form').off('submit');

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

      const actionUrl = $(this).attr('action').replace(/\/$/, '') + '/' + id;

      // Envoi AJAX
      $.post(actionUrl, $(this).serialize(), function(res) {
        if (res.success) {
       
          $('#updateModal').modal('hide');
          manageTable.ajax.reload(null, false);
            $("#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>`
            );
        } else {
          $("#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>`
            );
          alert(res.messages || 'Erreur lors de la modification.');
        }
      }, 'json');
    });
  });
}

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

</script>
