<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <h1>
      Gestion des
      <small>Réparations</small>
    </h1>
    <ol class="breadcrumb">
      <li><a href="#"><i class="fa fa-dashboard"></i> Accueil</a></li>
      <li class="active">Mécanicien</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 endif; ?>

        <?php if (in_array('createMecanicien', $user_permission)): ?>
          <button class="btn btn-primary" data-toggle="modal" data-target="#addModal">Ajouter une réparation</button>
          <br /> <br />
        <?php endif; ?>

        <!-- ✅ SECTION FILTRES AVEC MÉCANICIENS -->
        <div class="box">
          <div class="box-header with-border">
            <h3 class="box-title"><i class="fa fa-filter"></i> Filtres</h3>
          </div>
          <div class="box-body">
            <div class="row">
              <div class="col-md-3">
                <label for="filterStartDate">Date de début</label>
                <input type="date" id="filterStartDate" class="form-control">
              </div>
              <div class="col-md-3">
                <label for="filterEndDate">Date de fin</label>
                <input type="date" id="filterEndDate" class="form-control">
              </div>
              <!-- ✅ FILTRE PAR MÉCANICIEN -->
              <div class="col-md-3">
                <label for="filterMecanic">Mécanicien</label>
                <select id="filterMecanic" class="form-control">
                  <option value="">Tous les mécaniciens</option>
                  <?php if (isset($users) && is_array($users)): ?>
                    <?php foreach ($users as $user): ?>
                      <option value="<?= $user['id'] ?>">
                        <?= $user['firstname'] . ' ' . $user['lastname'] ?>
                      </option>
                    <?php endforeach; ?>
                  <?php endif; ?>
                </select>
              </div>
              <div class="col-md-3">
                <label>&nbsp;</label><br>
                <button id="btnFilter" class="btn btn-primary">
                  <i class="fa fa-filter"></i> Filtrer
                </button>
                <button id="btnReset" class="btn btn-warning">
                  <i class="fa fa-refresh"></i> Réinitialiser
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- ✅ STATISTIQUES PAR MÉCANICIEN -->
        <div class="row" id="statsContainer">
          <div class="col-md-3 col-sm-6 col-xs-12">
            <div class="info-box bg-aqua">
              <span class="info-box-icon"><i class="fa fa-wrench"></i></span>
              <div class="info-box-content">
                <span class="info-box-text">Total Réparations</span>
                <span class="info-box-number" id="statTotal">0</span>
              </div>
            </div>
          </div>
          <div class="col-md-3 col-sm-6 col-xs-12">
            <div class="info-box bg-yellow">
              <span class="info-box-icon"><i class="fa fa-clock-o"></i></span>
              <div class="info-box-content">
                <span class="info-box-text">En Cours</span>
                <span class="info-box-number" id="statEnCours">0</span>
              </div>
            </div>
          </div>
          <div class="col-md-3 col-sm-6 col-xs-12">
            <div class="info-box bg-green">
              <span class="info-box-icon"><i class="fa fa-check"></i></span>
              <div class="info-box-content">
                <span class="info-box-text">Réparées</span>
                <span class="info-box-number" id="statRepare">0</span>
              </div>
            </div>
          </div>
          <div class="col-md-3 col-sm-6 col-xs-12">
            <div class="info-box bg-red">
              <span class="info-box-icon"><i class="fa fa-times"></i></span>
              <div class="info-box-content">
                <span class="info-box-text">Non Réparées</span>
                <span class="info-box-number" id="statNonRepare">0</span>
              </div>
            </div>
          </div>
        </div>

        <!-- ✅ TABLEAU -->
        <div class="box">
          <div class="box-header">
            <h3 class="box-title">Gérer les Réparations</h3>
          </div>

          <div class="box-body">
            <table id="manageTable" class="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>Image</th>
                  <th>Motos</th>
                  <th>Mécanicien</th>
                  <th>Magasin</th>
                  <th>Statut</th>
                  <th>Observation</th>
                  <th>Date de début</th>
                  <th>Date de fin</th>
                  <?php if (in_array('updateMecanicien', $user_permission) || in_array('deleteMecanicien', $user_permission)): ?>
                    <th>Action</th>
                  <?php endif; ?>
                </tr>
              </thead>
            </table>
          </div>
        </div>
      </div>
    </div>
  </section>
</div>

<!-- Vos modaux existants (addModal, removeModal, editModal) restent inchangés -->
<?php if (in_array('createMecanicien', $user_permission)): ?>
  <!-- create brand modal -->
  <div class="modal fade" tabindex="-1" role="dialog" id="addModal">
    <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">Ajouter une moto pour réparation</h4>
        </div>

        <form role="form" action="<?php echo base_url('mecanicien/create') ?>" method="post" id="createForm">

          <div class="modal-body">

            <div class="form-group">
              <label for="motos">Nom du motos</label>
              <select name="motos" class="form-control select2" id="moto_select" style="width: 100%;" required>
                <option value=""></option>
                <?php foreach ($moto as $k => $v): ?>
                  <?php if ($v['product_sold'] == false): ?>
                    <option value="<?php echo $v['id'] ?>">
                      <?= $v['sku'] . ' | ' . $v['name'] . ' | ' . $v['numero_de_moteur'] . ' | ' . $v['puissance'] ?>
                    </option>
                  <?php endif; ?>
                <?php endforeach ?>
              </select>
            </div>
            <div class="form-group">
              <label for="mecano">Nom du mecanicien</label>
              <select class="form-control select2" id="moto_select2" name="mecano" style="width: 100%;">
                <?php foreach ($users as $k => $v): ?>
                  <option value="<?php echo $v['id'] ?>"><?php echo $v['firstname'] . " " . $v['lastname'] ?></option>
                <?php endforeach ?>
              </select>
            </div>
            <div class="form-group">
              <label for="statut">Status</label>
              <select class="form-control" id="statut" name="statut" required>
                <option value="1">En cours de réparation</option>
                <option value="2">Réparer</option>
                <option value="3">Non réparer</option>
              </select>
            </div>

            <div class="form-group">
              <label for="observation">Observation</label>
              <textarea class="form-control" name="observation" id="observation" cols="30" rows="3"
                placeholder="votre observation"></textarea>
            </div>

            <div class="form-group">
              <label for="date_debut">Date de debut</label>
              <input type="date" name="date_debut" id="date_debut" class="form-control" required>
            </div>

            <div class="form-group">
              <label for="date_fin">Date de fin</label>
              <input type="date" name="date_fin" id="date_fin" class="form-control" required>
            </div>
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>
            <button type="submit" class="btn btn-primary">Enregistrer</button>
          </div>

        </form>


      </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
  </div><!-- /.modal -->
<?php endif; ?>

<?php if (in_array('deleteMecanicien', $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 la réparation</h4>
        </div>

        <form role="form" action="<?php echo base_url('mecanicien/delete') ?>" 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; ?>

<?php if (in_array('updateMecanicien', $user_permission)): ?>
  <!-- edit brand modal -->
  <div class="modal fade" tabindex="-1" role="dialog" id="editModal">
    <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">Mise à jour du réparation</h4>
        </div>

        <form role="form" action="<?php echo base_url('mecanicien/update') ?>" method="post" id="updateForm">

          <div class="modal-body">

            <div class="form-group">
              <label for="motos">Nom du motos</label>
              <select class="form-control" id="motos_edit" name="motos" style="width: 100%;" required>
                <?php foreach ($moto as $k => $v): ?>
                  <?php if ($v['product_sold'] == false): ?>
                    <option value="<?php echo $v['id'] ?>">
                      <?= $v['sku'] . ' | ' . $v['name'] . ' | ' . $v['numero_de_moteur'] . ' | ' . $v['puissance'] ?>
                    </option>
                  <?php endif; ?>
                <?php endforeach ?>
              </select>
            </div>
            <div class="form-group">
              <label for="mecano">Nom du mecanicien</label>
              <select class="mecanic" id="mecano" name="mecano" style="width: 100%;">
                <?php foreach ($users as $k => $v): ?>
                  <option value="<?php echo $v['id'] ?>"><?php echo $v['firstname'] . " " . $v['lastname'] ?></option>
                <?php endforeach ?>
              </select>
            </div>
            <div class="form-group">
              <label for="statut">Status</label>
              <select class="form-control" id="statut_edit" name="statut" required>
                <option value="1">En cours de réparation</option>
                <option value="2">Réparer</option>
                <option value="3">Non réparer</option>
              </select>
            </div>

            <div class="form-group">
              <label for="observation">Observation</label>
              <textarea class="form-control" name="observation" id="observation_edit" cols="30" rows="3"
                placeholder="votre observation"></textarea>
            </div>

            <div class="form-group">
              <label for="date_debut">Date de debut</label>
              <input type="date" name="date_debut" id="date_debut_edit" class="form-control" required>
            </div>

            <div class="form-group">
              <label for="date_fin">Date de fin</label>
              <input type="date" name="date_fin" id="date_fin_edit" class="form-control" required>
            </div>
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>
            <button type="submit" class="btn btn-primary">Enregistrer</button>
          </div>

        </form>


      </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
  </div><!-- /.modal -->
<?php endif; ?>

<script>
  $(document).ready(function () {
    $('#addModal').on('shown.bs.modal', function () {
      if (!$('#moto_select').hasClass("select2-hidden-accessible")) {
        $('#moto_select').select2({
          dropdownParent: $('#addModal'),
          width: '100%'
        });
      }

      if (!$('#moto_select2').hasClass("select2-hidden-accessible")) {
        $('#moto_select2').select2({
          dropdownParent: $('#addModal'),
          width: '100%'
        });
      }
    });
    
    $("#motos_edit").select2();
    $('.mecanic').select2();
    $("#mecanicNav").addClass('active');

    // ✅ INITIALISER LES DATES À AUJOURD'HUI
    var today = new Date().toISOString().split('T')[0];
    $('#filterStartDate').val(today);
    $('#filterEndDate').val(today);

    // Configuration DataTable en français
    $.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"
        }
      }
    });

    // ✅ FONCTION POUR CALCULER LES STATISTIQUES
    function updateStatistics(data) {
      let total = data.length;
      let enCours = 0;
      let repare = 0;
      let nonRepare = 0;

      data.forEach(function(row) {
        // Le statut est dans la colonne index 4
        let statusHTML = row[4];
        if (statusHTML.includes('label-warning')) {
          enCours++;
        } else if (statusHTML.includes('label-success')) {
          repare++;
        } else if (statusHTML.includes('label-danger')) {
          nonRepare++;
        }
      });

      $('#statTotal').text(total);
      $('#statEnCours').text(enCours);
      $('#statRepare').text(repare);
      $('#statNonRepare').text(nonRepare);
    }

    // ✅ INITIALISATION DATATABLE AVEC FILTRES
    manageTable = $('#manageTable').DataTable({
      ajax: {
        url: '<?= base_url('mecanicien/fetchMecanicien') ?>',
        type: 'GET',
        data: function(d) {
          d.startDate = $('#filterStartDate').val();
          d.endDate = $('#filterEndDate').val();
          d.mecanic_id = $('#filterMecanic').val();
          
          console.log('📤 Filtres envoyés:', {
            startDate: d.startDate,
            endDate: d.endDate,
            mecanic_id: d.mecanic_id
          });
        },
        dataSrc: function(json) {
          console.log('📥 Données reçues:', json.data.length, 'réparations');
          updateStatistics(json.data);
          return json.data;
        },
        error: function(xhr, error, code) {
          console.error('❌ Erreur DataTables:', error);
        }
      },
      order: []
    });

    // ✅ BOUTON FILTRER
    $('#btnFilter').on('click', function() {
      console.log('🔍 Bouton Filtrer cliqué');
      console.log('Dates:', $('#filterStartDate').val(), 'à', $('#filterEndDate').val());
      console.log('Mécanicien ID:', $('#filterMecanic').val());
      
      manageTable.ajax.reload();
    });

    // ✅ BOUTON RÉINITIALISER
    $('#btnReset').on('click', function() {
      console.log('🔄 Réinitialisation des filtres');
      
      var today = new Date().toISOString().split('T')[0];
      $('#filterStartDate').val(today);
      $('#filterEndDate').val(today);
      $('#filterMecanic').val('');
      
      manageTable.ajax.reload();
    });

    // submit the create form 
    $("#createForm").unbind('submit').on('submit', function () {
      var form = $(this);
      $(".text-danger").remove();

      $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        data: form.serialize(),
        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>');

            $("#addModal").modal('hide');
            $("#createForm")[0].reset();
            $("#createForm .form-group").removeClass('has-error').removeClass('has-success');
          } else {
            if (response.messages instanceof Object) {
              $.each(response.messages, function (index, value) {
                var id = $("#" + index);
                id.closest('.form-group')
                  .removeClass('has-error')
                  .removeClass('has-success')
                  .addClass(value.length > 0 ? 'has-error' : 'has-success');
                id.after(value);
              });
            } 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;
    });

  });

  // edit function
  function editFunc(id) {
    $.ajax({
      url: '<?= base_url('mecanicien/fetchmecanicienSingle') ?>/' + id,
      type: 'post',
      dataType: 'json',
      success: function (response) {
        console.log(response);
        let date1 = new Date(response.reparation_debut);
        let date2 = new Date(response.reparation_fin);
        let formattedDate1 = date1.toLocaleDateString("fr-CA").split("T")[0];
        let formattedDate2 = date2.toLocaleDateString("fr-CA").split("T")[0];
        $("#motos_edit").val(response.produit_id).change();
        $("#mecano").val(response.user_id).trigger('change');
        $("#statut_edit").val(response.reparation_statut);
        $("#observation_edit").val(response.reparation_observation);
        $("#date_debut_edit").val(formattedDate1);
        $("#date_fin_edit").val(formattedDate2);

        $("#updateForm").unbind('submit').bind('submit', function () {
          var form = $(this);
          $(".text-danger").remove();

          $.ajax({
            url: form.attr('action').replace(/\/?$/, '/') + id,
            type: form.attr('method'),
            data: form.serialize(),
            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>');

                $("#editModal").modal('hide');
                $("#updateForm .form-group").removeClass('has-error').removeClass('has-success');
              } else {
                if (response.messages instanceof Object) {
                  $.each(response.messages, function (index, value) {
                    var id = $("#" + index);
                    id.closest('.form-group')
                      .removeClass('has-error')
                      .removeClass('has-success')
                      .addClass(value.length > 0 ? 'has-error' : 'has-success');
                    id.after(value);
                  });
                } 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;
        });
      }
    });
  }

  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: { reparation_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;
      });
    }
  }
</script>