<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <h1>
      Gestion des
      <small>Utilisateurs</small>
    </h1>
    <ol class="breadcrumb">
      <li><a href="#"><i class="fa fa-dashboard"></i> Accueil</a></li>
      <li class="active">Utilisateurs</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-danger 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('createUser', $user_permission)): ?>
          <button class="btn btn-primary" id="create_user">Ajouter un utilisateur</button>
          <br /> <br />
        <?php endif; ?>
        <div class="box">
          <div class="box-header">
            <h3 class="box-title">Gérer les utilisateurs</h3>
          </div>

          <div class="box-body">
            <table id="manageTable" class="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>Nom</th>
                  <th>Prenom</th>
                  <th>Email</th>
                  <th>Phone</th>
                  <th>Point de vente</th>
                  <th>Role</th>
                  <?php if (in_array('updateUser', $user_permission) || in_array('deleteUser', $user_permission)): ?>
                    <th>Action</th>
                  <?php endif; ?>
                </tr>
              </thead>

            </table>
          </div>
        </div>
      </div>
    </div>
  </section>
</div>

  <!-- Remove Modal -->
<div class="modal fade" id="removeModal" tabindex="-1" role="dialog" aria-labelledby="removeModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="removeModalLabel">Confirmer la suppression</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Fermer">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        Êtes-vous sûr de vouloir supprimer cet utilisateur ?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
        <button type="button" id="confirmRemove" class="btn btn-danger">Supprimer</button>
      </div>
    </div>
  </div>
</div>

<!-- Profile Modal -->
<div class="modal fade" id="profileModal" tabindex="-1" role="dialog" aria-labelledby="profileModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">

      <div class="modal-header">
        <h5 class="modal-title" id="profileModalLabel">Profil utilisateur</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Fermer">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>

      <div class="modal-body">
        <!-- Le contenu HTML du profil sera injecté ici par AJAX -->
        <div>
          <section class="content">
            <!-- Small boxes (Stat box) -->
            <div class="row">
              <div class="col-md-12 col-xs-12">

                <div class="box">
                  <div class="box-header">
                    <h3 class="box-title">Profil XXX</h3>
                  </div>
                  <!-- /.box-header -->
                  <div class="box-body">
                    <table class="table table-bordered table-condensed table-hovered">
                      <tr>
                        <th>Nom d'utilisateur</th>
                        <td id="p_username"></td>
                      </tr>
                      <tr>
                        <th>Nom</th>
                        <td id="p_firstname"></td>
                      </tr>
                      <tr>
                        <th>Prénom</th>
                        <td id="p_lastname"></td>
                      </tr>
                      <tr>
                        <th>Email</th>
                        <td id="p_email"></td>
                      </tr>
                      <tr>
                        <th>Genre</th>
                        <td id="p_gender"></td>
                      </tr>
                      <tr>
                        <th>Téléphone</th>
                        <td id="p_phone"></td>
                      </tr>
                      <tr>
                        <th>Roles</th>
                        <td><span class="label label-info" id="p_role"></span></td>
                      </tr>
                      <tr>
                        <th>Point de vente</th>
                        <td><span id="p_store"></span></td>
                      </tr>
                    </table>
                  </div>
                  <!-- /.box-body -->
                </div>
                <!-- /.box -->
              </div>
              <!-- col-md-12 -->
            </div>
            <!-- /.row -->
          </section>
        </div>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
      </div>

    </div>
  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="assignUserModal" tabindex="-1" aria-labelledby="assignUserModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content rounded-3 shadow">
      <div class="modal-header text-white">
        <h5 class="modal-title" id="assignUserModalLabel">Affecter un utilisateur à un point de vente</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <form id="assignUserForm">
        <div class="modal-body">
          <input type="hidden" name="user_id" id="assign_user_id" />

          <div class="mb-3">
            <label for="assign_user_name" class="form-label">Nom de l'utilisateur</label>
            <input type="text" class="form-control" id="assign_user_name" readonly>
          </div>

          <div class="mb-3">
            <label for="assign_user_role" class="form-label">Rôle</label>
            <input type="text" class="form-control" id="assign_user_role" readonly>
          </div>

          <div class="mb-3">
            <label for="assign_current_store" class="form-label">Point de vente actuel</label>
            <input type="text" class="form-control" id="assign_current_store" readonly>
          </div>

          <div class="mb-3">
            <label for="assign_new_store" class="form-label">Nouveau point de vente</label>
            <select class="form-control" id="assign_new_store" name="store_id" required>
              <!-- Options injectées dynamiquement via JS -->
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-success">Affecter</button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
        </div>
      </form>
    </div>
  </div>
</div>


<script>
  $(document).ready(function() {
    $('#assignUserForm').on('submit', function (e) {
        e.preventDefault(); // Empêche le rechargement de la page

        const formData = {
          user_id: $('#assign_user_id').val(),
          store_id: $('#assign_new_store').val()
        };
     $.ajax({
      url: '<?= base_url('users/assign_store') ?>', 
      method: 'POST',
      data: formData,
      dataType: 'json',
      success: function (response) {
        if (response.success) {
          var manageTable = $('#manageTable');
          manageTable.DataTable().ajax.reload(null, false); 
          $('#assignUserModal').modal('hide');
          $('#messages').html(
            '<div class="alert alert-success alert-dismissible fade show" role="alert">' +
              '<strong>Succès !</strong> ' + response.message +
              '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>' +
            '</div>'
          );
        } else {
          $('#assignUserModal .modal-body').prepend(
            '<div class="alert alert-danger">' + response.message + '</div>'
          );
        }
      },
      error: function () {
        $('#assignUserModal .modal-body').prepend(
          '<div class="alert alert-danger">Erreur serveur lors de l\'affectation.</div>'
        );
      }
    });
  });
  
    $("#mainUserNav").addClass('active');

    // Rediriger proprement si l'URL contient "?_="
    if (window.location.search.startsWith("?_=")) {
      window.location.href = window.location.origin + window.location.pathname;
    }

    // Initialisation de DataTable

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

    var manageTable = $('#manageTable').DataTable({
      'ajax': {
        url: '<?= base_url('users/fetchUserData') ?>',
        type: 'GET',
        dataType: 'json',
      },
      'order': [],
      'columnDefs': [
        {
          targets: 1,
          className: 'text-right rowmontant'
        },
        {
          targets: 4,
          className: 'rowtype'
        },
        {
          targets: 5,
          className: 'rowdestination'
        }
      ]
    });

    // Bouton de création d'utilisateur
    $('#create_user').on('click', function() {
      window.location.href = '<?= base_url('users/create') ?>';
    });

    let removeUserId = null;

    // À l'ouverture de la modal de suppression, on récupère l'ID
    $('#removeModal').on('show.bs.modal', function(event) {
      const button = $(event.relatedTarget);
      removeUserId = button.data('id');
    });

    // Au clic sur "Supprimer" dans la modal
    $('#confirmRemove').on('click', function() {
      if (!removeUserId) return;

      $.ajax({
        url: '<?= base_url('users/delete') ?>/' + removeUserId,
        type: 'POST',
        dataType: 'json',
        success: function(response) {
          $('#removeModal').modal('hide');

          if (response.success) {
            $('#messages').html(
              '<div class="alert alert-success alert-dismissible" role="alert">' +
              '<button type="button" class="close" data-dismiss="alert">&times;</button>' +
              '<strong>Succès !</strong> ' + response.message +
              '</div>'
            );
            manageTable.ajax.reload(null, false);
          } else {
            $('#messages').html(
              '<div class="alert alert-warning alert-dismissible" role="alert">' +
              '<button type="button" class="close" data-dismiss="alert">&times;</button>' +
              '<strong>Attention !</strong> ' + response.message +
              '</div>'
            );
          }
        },
        error: function(xhr, status, error) {
          console.error("Erreur AJAX suppression :", error);
          $('#messages').html(
            '<div class="alert alert-danger alert-dismissible" role="alert">' +
            '<button type="button" class="close" data-dismiss="alert">&times;</button>' +
            '<strong>Erreur !</strong> Impossible de supprimer l\'utilisateur.' +
            '</div>'
          );
        }
      });
    });

  }); // <-- fin de $(document).ready

  // Fonctions globales

  function editFunc(id) {
    // navigation classique vers la page d'édition
    window.location.href = '<?= base_url('users/edit') ?>/' + id;
  }

  function loginFunc(id) {
    // navigation classique vers la page de login
    window.location.href = '<?= base_url('users/login') ?>/' + id;
  }

  function profileFunc(userId) {
    $.ajax({
      url: '<?= base_url('users/fetchProfile') ?>/' + userId,
      type: 'GET',
      success: function (response) {
        if (response && response[0]) {
          let data = response[0];
          // 2) Corrige les sélecteurs pour utiliser underscore
          $('#p_username').text(data.user_data.username);
          $('#p_email').text(data.user_data.email);
          $('#p_firstname').text(data.user_data.firstname);
          $('#p_lastname').text(data.user_data.lastname);
          $('#p_gender').text(data.user_data.gender == 1 ? 'Homme' : 'Femme');
          $('#p_phone').text(data.user_data.phone);
          $('#p_role').text(data.user_group.group_name);
          $('#p_store').text(data.store_name.name);
        } else {
          $('#profileModal .modal-body').html('<div class="alert alert-warning">Aucune donnée trouvée</div>');
        }
      },
      error: function (xhr) {
        $('#profileModal .modal-body').html(
          '<div class="alert alert-danger">Erreur ' + xhr.status + ' : impossible de charger le profil.</div>'
        );
      }
    });
  }

  function assignFunc(userId) {
  $.ajax({
    url: '<?= base_url('users/fetchUserForAssign') ?>',
    method: 'POST',
    data: { user_id: userId },
    dataType: 'json',
    success: function(response) {
      if (response.success) {
        const user = response.user;
        const stores = response.stores;

        $('#assign_user_id').val(user.id);
        $('#assign_user_name').val(user.name );
        $('#assign_user_role').val(user.role);
        $('#assign_current_store').val(user.current_store);

        const $select = $('#assign_new_store');
        $select.empty();
        stores.forEach(store => {
          $select.append(`<option value="${store.id}">${store.name}</option>`);
        });

        $('#assignUserModal').modal('show');
      } else {
        alert('Utilisateur introuvable');
      }
    }
  });
}

</script>