<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <h1>
      Gestions des
      <small>Remises</small>
    </h1>
    <ol class="breadcrumb">
      <li><a href="#"><i class="fa fa-dashboard"></i> Accueil</a></li>
      <li class="active">Remise</li>
    </ol>
  </section>

  <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; ?>

        <div class="box">
          <div class="box-header">
            <h3 class="box-title">Gérer les remises</h3>
          </div>

            <table id="manageTable" class="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Produit</th>
                  <th>Prix total</th>
                  <th>Demande</th>
                  <th>Statut</th>
                  <?php if (in_array('validateRemise', $user_permission) || in_array('refusedRemise', $user_permission)): ?>
                    <th>Action</th>
                  <?php endif; ?>
                </tr>
              </thead>
            </table>
        </div>
      </div>
    </div>
  </section>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<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"
        }
      }
    });

    $("#remise_menu").addClass('active');

    // Check if the URL contains the _ parameter
    if (window.location.search.startsWith("?_=")) {
      window.location.href = window.location.origin + window.location.pathname;
    }

    manageTable = $('#manageTable').DataTable({
      ajax: '<?= base_url('remise/fetchRemiseData') ?>',
      order: [],
      columns: [
        { data: 0 },
        { data: 1 },
        { data: 2 },
        { data: 3 },
        { data: 4 },
        { data: 5 }
      ],
    });

  })

    // Fonction pour refuser une demande de remise
    function refuseFunc(id) {
    Swal.fire({
      title: 'Confirmation',
      text: 'Êtes-vous sûr de vouloir refuser cette demande de remise ?',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Oui, refuser',
      cancelButtonText: 'Annuler',
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6'
    }).then((result) => {
      if (result.isConfirmed) {
        $.ajax({
          url: '<?= base_url('remise/updateRemise') ?>/' + id,
          type: 'POST',
          data: { 'demande_status': 'Refusé' },
          dataType: 'json',
          success: function(response) {
            manageTable.ajax.reload(null, false);

            if (response.success === true) {
              Swal.fire({
                icon: 'warning',
                title: 'Refusé',
                text: response.messages,
                showConfirmButton: false,
                timer: 2000
              });
            } else {
              Swal.fire({
                icon: 'error',
                title: 'Erreur',
                text: response.messages
              });
            }
          },
          error: function() {
            Swal.fire({
              icon: 'error',
              title: 'Erreur',
              text: 'Une erreur est survenue lors du traitement de la demande.'
            });
          }
        });
      }
    });
  }

  // Fonction pour valider une demande de remise
  function valideFunc(id) {
    Swal.fire({
      title: 'Confirmation',
      text: 'Êtes-vous sûr de vouloir accepter cette demande de remise ?',
      icon: 'question',
      showCancelButton: true,
      confirmButtonText: 'Oui, accepter',
      cancelButtonText: 'Annuler',
      confirmButtonColor: '#28a745',
      cancelButtonColor: '#3085d6'
    }).then((result) => {
      if (result.isConfirmed) {
        $.ajax({
          url: '<?= base_url('remise/updateRemise') ?>/' + id,
          type: 'POST',
          data: { 'demande_status': 'Accepté' },
          dataType: 'json',
          success: function(response) {
            manageTable.ajax.reload(null, false);

            if (response.success === true) {
              Swal.fire({
                icon: 'success',
                title: 'Accepté',
                text: response.messages,
                showConfirmButton: false,
                timer: 2000
              });
            } else {
              Swal.fire({
                icon: 'warning',
                title: 'Attention',
                text: response.messages
              });
            }
          },
          error: function() {
            Swal.fire({
              icon: 'error',
              title: 'Erreur',
              text: 'Une erreur est survenue lors du traitement de la demande.'
            });
          }
        });
      }
    });
  }
  
</script>