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


        <?php if (in_array('createRecouvrement', $user_permission)): ?>
          <button class="btn btn-primary" data-toggle="modal" data-target="#createModal">RECOUVREMENT</button>
          <br /> <br />
        <?php endif; ?>
        <div class="box">
          <div class="box-header">
            <h3 class="box-title">Gérer les recouvrements</h3>
          </div>

          <div class="box-body">
            <table id="manageTable" class="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Montant</th>
                  <th>Date</th>
                  <th>Caissier</th>
                  <th>Type de Montant à recouvrer</th>
                  <th>Destination du Montant à recouvrer</th>
                  <?php if (in_array('updateRecouvrement', $user_permission) || in_array('deleteRecouvrement', $user_permission)): ?>
                    <th>Action</th>
                  <?php endif; ?>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td></td>
                  <td class="test"></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                </tr>
              </tbody>

            </table>
            <!-- totaliter mvola = somme tranche 1 izay type mvola tranche 1 + somme tranche 2
                    totaliter mvola dia - recouvrement izay sortie ùmvola plus recouvremnt entrer mvola
          -->
          </div>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-lg-3 col-6" bis_skin_checked="1">
        <!-- small box -->
        <div class="small-box " style="background-color: #A9A9A9;" bis_skin_checked="1">
          <div class="inner" bis_skin_checked="1">
            <h3 id="total"><?php echo number_format($total, 0, '', ' '); ?></h3>
            <p>Total</p>
          </div>
          <div class="icon" bis_skin_checked="1">
            <i class="ion ion-cash"></i>
          </div>
        </div>
      </div>
      <div class="col-lg-3 col-6" bis_skin_checked="1">
        <!-- small box -->
        <div class="small-box " style="background-color: #A9A9A9;" bis_skin_checked="1">
          <div class="inner" bis_skin_checked="1">
            <h3 id="total_mvola"><?php echo number_format($total_mvola, 0, '.', ' '); ?></h3>
            <p>Total en MVOLA</p>
          </div>
          <div class="icon" bis_skin_checked="1">
            <i class="ion ion-android-phone-portrait"></i>
          </div>
        </div>
      </div>
      <!--  -->
      <div class="col-lg-3 col-6" bis_skin_checked="1">
        <!-- small box -->
        <div class="small-box " style="background-color: #A9A9A9;" bis_skin_checked="1">
          <div class="inner" bis_skin_checked="1">
            <h3 id="total_caisse"><?php echo number_format($total_espece, 0, '.', ' '); ?></h3>
            <p>Total en Caisse</p>
          </div>
          <div class="icon" bis_skin_checked="1">
            <i class="ion ion-cash"></i>
          </div>
        </div>
      </div>
      <div class="col-lg-3 col-6" bis_skin_checked="1">
        <!-- small box -->
        <div class="small-box " style="background-color: #A9A9A9;" bis_skin_checked="1">
          <div class="inner" bis_skin_checked="1">
            <h3 id="total_banque"><?php echo number_format($total_virement_bancaire, 0, '.', ' '); ?></h3>
            <p>Total en Banque</p>
          </div>
          <div class="icon" bis_skin_checked="1">
            <i class="ion ion-bank"></i>
          </div>
        </div>
      </div>
    </div>
  </section>
  <!-- Modal pour la Création -->
  <?php if (in_array('createRecouvrement', $user_permission)): ?>
    <!-- remove brand modal -->
    <div class="modal fade" tabindex="-1" role="dialog" id="createModal">
      <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 un recouvrement</h4>
          </div>

          <form role="form" action="<?php echo base_url('recouvrement/create') ?>" method="post" id="create_form">
            <div class="modal-body">

              <!-- Montant du recouvrement -->
              <div class="form-group">
                <label for="sendmode" class="control-label">Type de Montant à recouvrer</label>
                <select name="send_mode" id="sendmode" class="form-control">
                  <option value="MVOLA">MVOLA</option>
                  
                  <option value="Virement Bancaire">Virement Bancaire</option>
                </select>
              </div>

              <div class="form-group">
                <label for="getmode" class="control-label">Destination du Montant à recouvrer</label>
                <select name="get_mode" id="getmode" class="form-control">
                  <option value="MVOLA">MVOLA</option>
                  <option value="En espèce">En espèce</option>
                  <option value="Virement Bancaire">Virement Bancaire</option>
                </select>
              </div>

              <!-- Montant du recouvrement -->
              <div class="form-group">
                <label for="recouvrement_montant" class="control-label">Montant du recouvrement</label>
                <input type="text" class="form-control" id="recouvrement_montant" name="recouvrement_montant" autocomplete="off">
              </div>

              <!-- Date du recouvrement -->
              <div class="form-group">
                <label for="recouvrement_date" class="control-label">Date du recouvrement</label>
                <input type="date" class="form-control" id="recouvrement_date" name="recouvrement_date" autocomplete="off">
              </div>

            </div>

            <!-- Boutons avec espacement -->
            <div class="modal-footer text-right" style="margin-top: 15px;">
              <button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>
              <button type="submit" class="btn btn-primary">Enregistrer</button>
            </div>
          </form>

        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

  <?php endif; ?>

  <!-- Modal for updatting a recouvrement -->
  <?php if (in_array('updateRecouvrement', $user_permission)): ?>
    <!-- update brand modal -->
    <div class="modal fade" tabindex="-1" role="dialog" id="updateModal">
      <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">Modifier un recouvrement</h4>
          </div>

          <form role="form" action="<?php echo base_url('recouvrement/update') ?>" method="post" id="update_form">
            <div class="modal-body"> <!-- Correction ici -->
              <div class="row form-group">
                <div class="col-lg-6">
                  <label for="recouvrement_montant" class="control-label">Montant du recouvrement</label>
                </div>

                <div class="col-lg-6">
                  <input type="text" class="form-control" id="recouvrement_montant_edit" name="recouvrement_montant_edit" autocomplete="off">
                </div>
              </div>
              <div class="row form-group">
                <div class="col-lg-6">
                  <label for="gross_amount" class="control-label">Date du recouvrement</label>
                </div>
                <div class="col-lg-6">
                  <input type="date" class="form-control" id="recouvrement_date_edit" name="recouvrement_date_edit" autocomplete="off">
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="form-group">
                <button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>
                <button type="submit" class="btn btn-primary">Enregistrer</button>
              </div>
            </div>
          </form>

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


  <?php if (in_array('deleteRecouvrement', $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 le recrouvement</h4>
          </div>
          <form role="form" action="<?php echo base_url('recouvrement/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; ?>
</div>
</section>
</div>



<script>
  $(document).ready(function() {
    $("#motos").select2();
    $("#motos_edit").select2();
    $('.mecanic').select2();
    $("#recouvrement").addClass('active');

    // Check if the URL contains the _ parameter
    if (window.location.search.startsWith("?_=")) {
      window.location.href = window.location.origin + window.location.pathname;
    }
    // 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"
        }
    }
});


    manageTable = $('#manageTable').DataTable({
      'ajax': '<?= base_url('recouvrement/fetchRecouvrementData') ?>',
      'order': [],
      'columnDefs': [{
          targets: 1,
          className: 'text-right rowmontant'
        },
        {
          targets: 4,
          className: 'rowtype'
        },
        {
          targets: 5,
          className: 'rowdestination'
        }
      ]
    });
    
  })

  $("#create_form").unbind('submit').on('submit', function() {
      var form = $(this);

      // remove the text-danger
      $(".text-danger").remove();

      $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        data: form.serialize(), // /converting the form data into array and sending it to server
        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>');


            // hide the modal
            $("#createModal").modal('hide');

            // reset the form
            $("#create_form")[0].reset();
            $("#create_form .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);

        // remove the text-danger
        $(".text-danger").remove();

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

              // hide the modal
              $("#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;
      });
    }
  }

  // update function
  function editFunc(id) {
    $.ajax({
      url: '<?= base_url('recouvrement/fetchRecouvrementSingle') ?>/' + id,
      type: 'post',
      dataType: 'json',
      success: function(response) {
        $("#recouvrement_montant_edit").val(response.recouvrement_montant).change();
        $("#recouvrement_date_edit").val(response.recouvrement_date).change();
        // submit the edit from 
        $("#update_form").unbind('submit').bind('submit', function() {
          var form = $(this);

          // remove the text-danger
          $(".text-danger").remove();

          $.ajax({
            url: form.attr('action').replace(/\/?$/, '/') + id,
            type: form.attr('method'),
            data: form.serialize(), // /converting the form data into array and sending it to server
            dataType: 'json',
            success: function(response) {
              manageTable.ajax.reload(null, false);
              $("#updateModal").modal('hide');
              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>');


                // reset the form 
                $("#updateForm .form-group").removeClass('has-error').removeClass('has-success');

              } else {
                $("#updateModal").modal('hide');
                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 {
                  $("#updateModal").modal('hide');
                  $("#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>
<script>
    const endpoint = '<?= base_url('recouvrement/fetchTotalData') ?>';
  async function fetchTotalData() {
    try {
      let res = await fetch(endpoint, { headers:{'Content-Type':'application/json'} });
      if (!res.ok) throw new Error(res.status);
      let data = await res.json();
      $('#total').text(formatNum(data.total));
      $('#total_mvola').text(formatNum(data.total_mvola));
      $('#total_caisse').text(formatNum(data.total_espece));
      $('#total_banque').text(formatNum(data.total_virement_bancaire));
    } catch(e) {
      console.error('fetchTotalData error', e);
    }
  }
  function formatNum(n){
    n = parseFloat(n)||0; return n.toLocaleString('fr-FR').replace(/\s/g,' ');
  }
  fetchTotalData();
  setInterval(fetchTotalData, 1000);
</script>
