<?php include('config/connexion.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
  <?php include('includes/head.php'); ?>
  <!-- DataTables CSS -->
  <link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">
</head>
<body id="page-top">
  <div id="wrapper">
    <!-- Sidebar -->
    <?php include('includes/sidebar.php'); ?>
    <!-- Sidebar -->
    <div id="content-wrapper" class="d-flex flex-column">
      <div id="content">
        <!-- TopBar -->
        <?php include('includes/topbar.php'); ?>
        <!-- Topbar -->

        <!-- Container Fluid-->
        <div class="container-fluid" id="container-wrapper">
          <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h3 mb-0 text-gray-800">Liste des Marques de Transport</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Accueil</a></li>
              <li class="breadcrumb-item">Marques</li>
              <li class="breadcrumb-item active" aria-current="page">Liste des Marques</li>
            </ol>
          </div>

          <!-- Add button -->
          <div class="row mb-3">
            <div class="col-12">
              <a href="add_marque.php" class="btn btn-primary">
                <i class="fas fa-plus"></i> Ajouter une nouvelle marque
              </a>
            </div>
          </div>

          <!-- Marques Table -->
          <div class="card mb-4">
            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
              <h6 class="m-0 font-weight-bold text-primary">Marques de Transport</h6>
            </div>
            <div class="table-responsive p-3">
              <table class="table align-items-center table-flush" id="dataTable">                <thead class="thead-light">
                  <tr>
                    <th>#</th>
                    <th>Marque</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tfoot>
                  <tr>
                    <th>#</th>
                    <th>Marque</th>
                    <th>Actions</th>
                  </tr>
                </tfoot>
                <tbody>
                  <?php
                  $query = "SELECT id, marque FROM marques_transport ORDER BY marque ASC";
                  $result = $conn->query($query);

                  if ($result && $result->num_rows > 0) {
                    while ($row = $result->fetch_assoc()) {
                      echo "<tr>
                              <td>" . htmlspecialchars($row['id']) . "</td>
                              <td><strong>" . htmlspecialchars($row['marque']) . "</strong></td>
                              <td>
                                <a href='edit_marque.php?id=" . $row['id'] . "' class='btn btn-sm btn-warning' title='Modifier'>
                                  <i class='fas fa-edit'></i>
                                </a>
                                <button class='btn btn-sm btn-danger delete-marque-btn' data-id='" . $row['id'] . "' data-marque='" . htmlspecialchars($row['marque']) . "' title='Supprimer'>                                  <i class='fas fa-trash'></i>
                                </button>
                              </td>
                            </tr>";
                    }
                  } else {
                    echo "<tr><td colspan='3' class='text-center'>Aucune marque trouvée</td></tr>";
                  }
                  // Connection is managed globally; do not close it here.
                  ?>
                </tbody>
              </table>
            </div>
          </div>
          <!-- End Marques Table -->

        </div>
        <!---Container Fluid-->
      </div>
      <!-- Footer -->
      <?php include('includes/footer.php'); ?>
      <!-- Footer -->
    </div>
  </div>
  <!-- Delete Modal -->
  <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="deleteModalLabel">Confirmer la suppression</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <p>Êtes-vous sûr de vouloir supprimer cette marque ?</p>
          <div class="alert alert-warning">
            <strong>Marque:</strong> <span id="delete-marque-name"></span>
          </div>
          <p class="text-danger"><strong>Cette action est irréversible.</strong></p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
          <button type="button" class="btn btn-danger" id="confirm-delete">Supprimer</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Success Modal -->
  <div class="modal fade" id="successModal" tabindex="-1" role="dialog" aria-labelledby="successModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header bg-success text-white">
          <h5 class="modal-title" id="successModalLabel">
            <i class="fas fa-check-circle mr-2"></i>Suppression réussie
          </h5>
          <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="text-center">
            <i class="fas fa-check-circle text-success" style="font-size: 3rem;"></i>
            <h4 class="mt-3 text-success">Marque supprimée avec succès !</h4>
            <p class="mt-2">La marque "<strong><span id="success-marque-name"></span></strong>" a été supprimée de la base de données.</p>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-success" id="reload-page">
            <i class="fas fa-refresh mr-1"></i>OK
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- Scroll to top -->
  <a class="scroll-to-top rounded" href="#page-top">
    <i class="fas fa-angle-up"></i>
  </a>
  
  <script src="vendor/jquery/jquery.min.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
  <script src="js/ruang-admin.min.js"></script>
  <script src="vendor/datatables/jquery.dataTables.min.js"></script>
  <script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
  <script>
    $(document).ready(function () {
      // Initialiser DataTables avec configuration française
      $('#dataTable').DataTable({
        "language": {
          "url": "//cdn.datatables.net/plug-ins/1.10.25/i18n/French.json"
        },
        "pageLength": 10,        "order": [[ 1, "asc" ]],
        "columnDefs": [
          { "orderable": false, "targets": 2 } // Désactiver le tri sur la colonne Actions
        ]
      });
        // Utiliser la délégation d'événements pour les boutons de suppression
      $(document).on('click', '.delete-marque-btn', function() {
        const marqueId = $(this).data('id');
        const marqueName = $(this).data('marque');
        
        console.log('Tentative de suppression - ID:', marqueId, 'Marque:', marqueName);
        
        $('#delete-marque-name').text(marqueName);
        $('#deleteModal').modal('show');
        
        // Stocker l'ID de la marque à supprimer
        $('#deleteModal').data('marque-id', marqueId);
      });
        // Handle confirm delete
      $('#confirm-delete').on('click', function() {
        const marqueId = $('#deleteModal').data('marque-id');
        const marqueName = $('#delete-marque-name').text();
        
        console.log('Confirmation de suppression pour ID:', marqueId);
        
        // Désactiver le bouton pendant la requête
        $(this).prop('disabled', true).text('Suppression...');
        
        $.ajax({
          url: 'delete_marque.php',
          method: 'POST',
          data: { id: marqueId },
          dataType: 'json',
          success: function(response) {
            console.log('Réponse du serveur:', response);
            if (response.success) {
              // Fermer la modal de confirmation
              $('#deleteModal').modal('hide');
              
              // Afficher la modal de succès
              $('#success-marque-name').text(marqueName);
              $('#successModal').modal('show');
            } else {
              alert('Erreur: ' + response.message);
            }
          },
          error: function(xhr, status, error) {
            console.error('Erreur AJAX:', {xhr: xhr, status: status, error: error});
            console.error('Réponse brute:', xhr.responseText);
            alert('Erreur lors de la suppression: ' + error + '\nRéponse: ' + xhr.responseText);
          },
          complete: function() {
            // Réactiver le bouton
            $('#confirm-delete').prop('disabled', false).text('Supprimer');
          }
        });
      });
      
      // Handle reload page button in success modal
      $('#reload-page').on('click', function() {
        location.reload();
      });
      
      // Test de connexion au démarrage
      console.log('Page marques_table.php chargée, DataTables initialisé');
      console.log('Nombre de boutons de suppression:', $('.delete-marque-btn').length);
    });
  </script>
</body>
</html>
