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

  <!-- Main content -->
  <section class="content">
    <!-- Small boxes (Stat box) -->
    <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 endif; ?>

        <?php if (in_array('createOrder', $user_permission)): ?>
          <a href="<?php echo base_url('orders/create') ?>" class="btn btn-primary">Ajouter un commande</a>
          <br /> <br />
        <?php endif; ?>

        <div class="box">
          <div class="box-header">
            <h3 class="box-title">Gérer les Commandes</h3>
          </div>
          <!-- /.box-header -->
          <div class="box-body">
            <table id="manageTable" class="table table-bordered table-striped">
              <thead>
              <tr>
                <?php
                  $session = session();
                  $users = $session->get('user');
                  $groupName = $users['group_name'];
                  if (in_array($groupName, ['SuperAdmin', 'Direction', 'DAF', 'Administrator'])) {
                ?>
                    <th>Facture n°</th>
                    <th>Nom du client</th>
                    <th>Téléphone du client</th>
                    <th>Date et Heure</th>
                    <th>Prix demandé</th>
                    <th>Prix de vente</th>
                    <th>Status</th>
                    <?php if (
                      in_array('updateOrder', $user_permission)
                      || in_array('viewOrder',   $user_permission)
                      || in_array('deleteOrder', $user_permission)
                    ) { ?>
                      <th>Action</th>
                    <?php } ?>
                <?php } elseif ($groupName === 'SECURITE') { ?>
                    <th>Nom du produit</th>
                    <th>Commerciale</th>
                    <th>Date et Heure</th>
                    <th>Marque</th>
                    <th>Numéro de Série</th>
                    <th>Status</th>
                    <?php if (
                      in_array('viewOrder', $user_permission)
                      || in_array('updateOrder', $user_permission)
                    ) { ?>
                      <th>Action</th>
                    <?php } ?>
                <?php } else { // COMMERCIALE, Caissière, Cheffe d'Agence, et tous les autres rôles ?>
                    <th>Nom du produit</th>
                    <th>Commerciale</th>
                    <th>Date et Heure</th>
                    <th>Prix demandé</th>
                    <th>Prix de vente</th>
                    <th>Status</th>
                    <?php if (
                      in_array('viewOrder', $user_permission)
                      || in_array('updateOrder', $user_permission)
                    ) { ?>
                      <th>Action</th>
                    <?php } ?>
                <?php } ?>
              </tr>


              </thead>

            </table>
          </div>
          <!-- /.box-body -->
        </div>
        <!-- /.box -->
      </div>
      <!-- col-md-12 -->
    </div>
    <!-- /.row -->


  </section>
  <!-- /.content -->
</div>
<!-- /.content-wrapper -->

<?php if (in_array('deleteOrder', $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 une commande</h4>
        </div>

        <form role="form" action="<?php echo base_url('orders/remove') ?>" method="post" id="removeForm">
          <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; ?>


<!-- Modal -->
<!-- Modal -->
<div class="modal fade" id="viewOrderModal" tabindex="-1" role="dialog" aria-labelledby="viewOrderModalLabel">
  <div class="modal-dialog modal-lg" role="document"> 
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
        <h4 class="modal-title">Détails de la commande</h4>
      </div>
      <div class="modal-body">

        <!-- Messages de la modal -->
        <div id="modal-messages"></div>

        <!-- Ligne Date / Heure -->
        <div class="row">
          <div class="col-md-6 form-group">
            <label>Date :</label>
            <span class="form-control-static" id="order_date"></span>
          </div>
        </div>

        <!-- Infos client -->
        <div class="row">
          <div class="col-md-6 form-group">
            <label>Nom client :</label>
            <span class="form-control-static" id="customer_name"></span>
          </div>
        </div>
        <div class="row">
          <div class="col-md-6 form-group">
            <label>Adresse :</label>
            <span class="form-control-static" id="customer_address"></span>
          </div>
        </div>
        <div class="row">
          <div class="col-md-6 form-group">
            <label>Téléphone :</label> <span class="form-control-static" id="customer_phone"></span>
          </div>
        </div>
        <div class="row">
          <div class="col-md-6 form-group">
            <label>CIN :</label>
            <span class="form-control-static" id="customer_cin"></span>
          </div>
        </div>

        <!-- Tableau produits avec toutes les infos sur une ligne -->
        <h4>Informations de la commande</h4>
              <table class="table table-bordered table-striped" id="view_products_table">
                <thead>
                  <tr id="table_headers">
                    <!-- Les en-têtes seront générés dynamiquement par JavaScript -->
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>
        
        <?php 
        $session = session();
        $users = $session->get('user');
        if ($users['group_name'] === 'SECURITE'): ?>
          <button type="button" class="btn btn-success" id="btn-mark-delivered" style="display:none;">
            <i class="fa fa-truck"></i> Marquer comme Livré
          </button>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>


<script type="text/javascript">
  var manageTable;
  var base_url = "<?php echo base_url(); ?>";
  var currentOrderId = null; // Variable globale pour stocker l'ID de la commande actuelle

  $(document).ready(function() {

    $("#mainOrdersNav").addClass('active');
    $("#manageOrdersNav").addClass('active');

    // initialize the datatable 
    $.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"
            }
        }
    });

    manageTable = $('#manageTable').DataTable({
      'ajax': base_url + 'orders/fetchOrdersData',
      'order': [],
      'columnDefs': [{
          targets: 6,
          className: 'text-right'
        }]
    });

    // Gestionnaire pour le bouton "Marquer comme Livré"
    $('#btn-mark-delivered').on('click', function() {
      if (!currentOrderId) {
        alert('Erreur : ID de commande introuvable.');
        return;
      }

      if (confirm('Êtes-vous sûr de vouloir marquer cette commande comme livrée ?')) {
        // Désactiver le bouton pendant le traitement
        $('#btn-mark-delivered').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Traitement...');
        
        $.ajax({
          url: base_url + 'orders/markAsDelivered',
          type: 'POST',
          data: { order_id: currentOrderId },
          dataType: 'json',
          success: function(response) {
            if (response.success === true) {
              // Afficher un message de succès dans la modal
              $("#modal-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>'
              );

              // Mettre à jour le statut dans toutes les lignes du tableau
              $('#view_products_table tbody tr').each(function() {
                $(this).find('td:last').html('<span class="label label-info">Payé et Livré</span>');
              });
              
              // Cacher le bouton "Livré"
              $('#btn-mark-delivered').hide();

              // Recharger la table immédiatement
              manageTable.ajax.reload(null, false);

            } else {
              // Afficher un message d'erreur
              $("#modal-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> ' + response.messages +
                '</div>'
              );
              
              // Réactiver le bouton
              $('#btn-mark-delivered').prop('disabled', false).html('<i class="fa fa-truck"></i> Marquer comme Livré');
            }
          },
          error: function(xhr, status, error) {
            console.error('Erreur AJAX:', xhr.responseText);
            $("#modal-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 de communication avec le serveur.<br>' +
              'Détails: ' + (xhr.responseText || error) +
              '</div>'
            );
            
            // Réactiver le bouton
            $('#btn-mark-delivered').prop('disabled', false).html('<i class="fa fa-truck"></i> Marquer comme Livré');
          }
        });
      }
    });

  });

  // remove functions 
  function removeFunc(id) {
    if (id) {
      $("#removeForm").on('submit', function() {
        var form = $(this);
        $(".text-danger").remove();

        $.ajax({
          url: form.attr('action'),
          type: form.attr('method'),
          data: { order_id: id },
          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>'
              );
              $("#removeModal").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>'
              );
            }
          }
        });

        return false;
      });
    }
  }

  // ✅ FONCTION MODIFIÉE POUR AFFICHER LES NOUVELLES COLONNES
// ✅ FONCTION MODIFIÉE POUR AFFICHER LA QUANTITÉ
$(document).on('click', '.btn-view', function(e) {
  e.preventDefault();
  var orderId = $(this).data('order-id');
  currentOrderId = orderId;
  var url = base_url + 'orders/lookOrder/' + orderId;

  $('#modal-messages').empty();

  $.getJSON(url, function(response) {
    var d = response.order_data.order;
    
    // Remplir les champs de la modal
    $('#order_date').text(d.date_time || '');
    $('#customer_name').text(d.customer_name);
    $('#customer_address').text(d.customer_address);
    $('#customer_phone').text(d.customer_phone);
    $('#customer_cin').text(d.customer_cin);

    // Déterminer le statut une seule fois
    var statutHtml = '';
    if (d.paid_status == 1) {
      statutHtml = '<span class="label label-success">Payé</span>';
      <?php if ($users['group_name'] === 'SECURITE'): ?>
        $('#btn-mark-delivered').show();
      <?php endif; ?>
    } else if (d.paid_status == 2) {
      statutHtml = '<span class="label label-warning">En Attente</span>';
      $('#btn-mark-delivered').hide();
    } else if (d.paid_status == 3) {
      statutHtml = '<span class="label label-info">Payé et Livré</span>';
      $('#btn-mark-delivered').hide();
    } else {
      statutHtml = '<span class="label label-danger">Refusé</span>';
      $('#btn-mark-delivered').hide();
    }

    // ✅ GÉNÉRER LES EN-TÊTES SELON LE RÔLE
    var $headers = $('#table_headers');
    $headers.empty();
    
    <?php if ($users['group_name'] === 'SECURITE'): ?>
      // En-têtes pour SECURITE
      $headers.append(
        '<th>Marque</th>' +
        '<th>Désignation</th>' +
        '<th>Numéro de Série</th>' +
        '<th>N° de Moteur</th>' +
        '<th>Châssis</th>' +
        '<th>Quantité</th>' +  // ✅ AJOUT
        '<th>N° Facture</th>' +
        '<th>Statut</th>'
      );
    <?php else: ?>
      // En-têtes pour les autres rôles
      $headers.append(
        '<th>Marque</th>' +
        '<th>Désignation</th>' +
        '<th>Quantité</th>' +  // ✅ AJOUT
        '<th>Prix unitaire</th>' +  // ✅ MODIFIÉ
        '<th>Montant</th>' +  // ✅ AJOUT (prix × quantité)
        '<th>Prix demandé</th>' +
        '<th>Remise</th>' +
        '<th>Statut</th>'
      );
    <?php endif; ?>

    // ✅ GÉNÉRER LES LIGNES DU TABLEAU SELON LE RÔLE
    var $tb = $('#view_products_table tbody');
    $tb.empty();
    
    $.each(response.order_data.order_item, function(_, item) {
      var product = null;
      $.each(response.products, function(_, p) {
        if (p.id == item.product_id) {
          product = p;
          return false;
        }
      });

      if (product) {
        var brandName = '';
        $.each(response.brands, function(_, brand) {
          if (brand.id == product.marque) {
            brandName = brand.name;
            return false;
          }
        });

        // ✅ RÉCUPÉRATION DE LA QUANTITÉ
        var qty = parseInt(item.qty) || 1;

        <?php if ($users['group_name'] === 'SECURITE'): ?>
          // ✅ AFFICHAGE POUR SECURITE
          $tb.append(
            '<tr>' +
            '<td>' + (brandName || 'Aucune marque') + '</td>' +
            '<td>' + (product.name || '') + '</td>' +
            '<td>' + (product.sku || '') + '</td>' +
            '<td>' + (product.numero_de_moteur || 'N/A') + '</td>' +
            '<td>' + (product.chasis || 'N/A') + '</td>' +
            '<td>' + qty + '</td>' +  // ✅ AJOUT
            '<td>' + (d.bill_no || 'N/A') + '</td>' +
            '<td>' + statutHtml + '</td>' +
            '</tr>'
          );
        <?php else: ?>
          // ✅ AFFICHAGE POUR LES AUTRES RÔLES
          var prixUnitaire = parseFloat(item.rate || 0);  // Prix unitaire depuis l'item
          var montant = prixUnitaire * qty;  // ✅ CALCUL DU MONTANT TOTAL
          var prixDemande = parseFloat(d.discount || 0);
          var remise = parseFloat(d.net_amount || 0);
          
          $tb.append(
            '<tr>' +
            '<td>' + (brandName || 'Aucune marque') + '</td>' +
            '<td>' + (product.name || '') + '</td>' +
            '<td>' + qty + '</td>' +  
            '<td>' + prixUnitaire.toLocaleString('fr-FR') + ' Ar</td>' +  // ✅ PRIX UNITAIRE
            '<td>' + montant.toLocaleString('fr-FR') + ' Ar</td>' +  // ✅ MONTANT TOTAL
            '<td>' + prixDemande.toLocaleString('fr-FR') + ' Ar</td>' +
            '<td>' + remise.toLocaleString('fr-FR') + ' Ar</td>' +
            '<td>' + statutHtml + '</td>' +
            '</tr>'
          );
        <?php endif; ?>
      }
    });

    // Afficher la modal
    $('#viewOrderModal').modal('show');
  });
});
</script>