<?php
include VIEWPATH.'includes/new_header.php';
?>
<body class="hold-transition sidebar-mini">
  <div class="wrapper">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>


    <?php
    include VIEWPATH.'includes/new_top_menu.php';
    include VIEWPATH.'includes/new_menu_principal.php';
    ?>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
      <!-- Content Header (Page header) -->

      <?php 
      include 'includes/menu_retour_vente.php';
      ?>

      <!-- Main content -->
      <section class="content">
        <div class="container-fluid">
          <div class="row">
            <div class="col-12">

              <!-- /.card -->

              <div class="card card-primary">
                <div class="card-header">
                  <h3 class="card-title">Retour Vente</h3>
                </div>
                <!-- /.card-header -->
                <div class="card-body">
                  <table id="example1" class="table table-bordered table-striped" style="width:100%">
                    <thead>
                      <tr>
                        <th>#</th>
                        <th>Client</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Montant à payer</th>
                        <th>Details</th>
                        <!--<th></th>-->
                      </tr>   
                    </thead>
                    <tbody>
                      <?php

                      $resultat=$this->Model->getRequete('SELECT `ID_VENTE`,`NUMERO_VENTE`,client_client.NOM, client_client.PRENOM, `DATE_ENREGISTREMENT`, vente_statut.DESCRIPTION,`DATE_COMMANDE`,`MONTANT_TOTAL` FROM `vente_vente` JOIN client_client ON client_client.ID_CLIENT = vente_vente.ID_CLIENT JOIN vente_statut ON vente_statut.ID_VENTE_STATUT = vente_vente.ID_VENTE_STATUT WHERE vente_vente.ID_VENTE_STATUT IN (2,3) ');

                      foreach ($resultat as $key) 
                      {
                        $commune = $this->Model->getRequete("SELECT `ID_VENTE_DETAILS`, syst_taille_bouteille.DESCRIPTION, `QUANTITE_LIVRE`, `PRIX_UNITAIRE`,vente_details.ID_STATUS,prod_lot.LOT_PRODUCTION FROM `vente_details` JOIN syst_taille_bouteille ON syst_taille_bouteille.ID_TAILLE_BOUTEILLE = vente_details.ID_TAILLE_BOUTEILLE JOIN prod_lot ON prod_lot.ID_LOT=vente_details.ID_LOT WHERE vente_details.QUANTITE_RETOURNE IS NULL AND vente_details.ID_STATUS=2 AND `ID_VENTE` = " . $key['ID_VENTE'] . "");
                        $retourst=$this->Model->getList('stock_motif_retour',array());


                        $datas = '<form method="POST" action="'.base_url('vente/Retour_Vente/retour_vente').'" id="myModal'.$key['ID_VENTE'].'">';
                        $datas .= '<input type="hidden" name="ID_VENTE" value="'.$key['ID_VENTE'].'">';
                        $datas .= '<table class="table">';
                        $datas .= '<tr>
                        <td><b>Taille</b></td>
                        <td class="text-center"><b>Prix Unitaire</b></td>
                        <td class="text-center"><b>Lot</b></td>
                        <td class="text-center"><b>Quantite</b></td>   
                         <td class="text-center"><b>Motif</b></td>
                        <td class="text-center"><b>Commentaire</b></td>                    
                        <td class="text-center"><b>Select</b></td>
                        </tr>';
                        $totalPayable = 0;
                        
                        foreach ($commune as $commun) {
                          // $totalPayable += $commun["QUANTITE_LIVRE"] * $commun["PRIX_UNITAIRE"];
                          $datas .= '<tr>
                          <td>' . $commun["DESCRIPTION"] . '</td>
                          <td class="text-right">' . number_format($commun["PRIX_UNITAIRE"], 0, ' ', ' ') . '</td>
                          <td>' . $commun["LOT_PRODUCTION"] . '</td>
                          <td>
                          <input type="number" class="form-control" 
                          id="QUANTITE_LIVRE_' . $commun['ID_VENTE_DETAILS'] . '" 
                          name="QUANTITE_LIVRE[' . $commun["ID_VENTE_DETAILS"] . ']" 
                          max="' . $commun["QUANTITE_LIVRE"] . '" 
                          min="0">
                          </td>

                          <td>
                          <select class="custom-select" name="ID_MOTIF_RETOUR[' . $commun["ID_VENTE_DETAILS"] . ']" id="ID_MOTIF_RETOUR">
                          <option value="">-- Select --</option>';

                          foreach ($retourst as $retourmotif) {
                            $datas .= "<option value='" . htmlspecialchars($retourmotif['ID_MOTIF_RETOUR']) . "'>" . 
                            htmlspecialchars($retourmotif['DESCRIPTION']) . "</option>";
                          }

                          $datas .= '
                          </td>

                          <td>
                          <textarea class="form-control" name="COMMENTAIRE[' . $commun["ID_VENTE_DETAILS"] . ']" id="COMMENTAIRE" rows="3"></textarea>

                          </td>



                          <td class="text-center">
                          <input type="checkbox" id="SELECT_' . $commun['ID_VENTE_DETAILS'] . '" 
                          name="SELECT[]" value="' . $commun['ID_VENTE_DETAILS'] . '">
                          </td>
                          </tr>';
                        }
                        
                        $datas .= '</table>';
                      
                        $datas .= '<button type="submit" class="btn btn-primary">Retour vente</button>'; 
                        $datas .= '</form>';

                        $commune_livre = $this->Model->getRequete("SELECT `ID_VENTE_DETAILS`, vente_details.ID_TAILLE_BOUTEILLE, syst_taille_bouteille.DESCRIPTION,QUANTITE_LIVRE,QUANTITE_RETOURNE, `QUANTITE_COMMANDE`, `PRIX_UNITAIRE`, vente_details.ID_STATUS FROM `vente_details` JOIN syst_taille_bouteille ON syst_taille_bouteille.ID_TAILLE_BOUTEILLE = vente_details.ID_TAILLE_BOUTEILLE WHERE vente_details.ID_STATUS=2 AND `ID_VENTE` = ".$key['ID_VENTE']."");

                        $totalpay = 0;
                        if(!empty($commune_livre)){
                         foreach ($commune_livre as $commun) {
                           $totalpay+= $commun["QUANTITE_LIVRE"]*$commun["PRIX_UNITAIRE"];
                          //  if(!empty($commun["QUANTITE_RETOURNE"])){
                          //   $totalpayable += $commun["QUANTITE_RETOURNE"]*$commun["PRIX_UNITAIRE"];
                          // } 

                         }
                       }
                       $montant=$totalpay;
                       echo "<tr>
                       <td>".$key['NUMERO_VENTE']."</td>
                       <td>".$key['NOM']." ".$key['PRENOM']."</td>
                       <td>".$key['DESCRIPTION']."</td>
                       <td>".$key['DATE_COMMANDE']."</td>
                       <td class='text-right'>". number_format($montant,0,' ',' ')."</td>
                       <td>";
                       echo'<button type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#myModal'.$key['ID_VENTE'].'">
                       Details
                       </button>

                       <!-- Modal -->
                       <div class="modal fade" id="myModal'.$key['ID_VENTE'].'" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                       <div class="modal-dialog modal-lg" role="document">
                       <div class="modal-content">
                       <div class="modal-header">
                       <h4 class="modal-title" id="myModalLabel">Details</h4>
                       <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                       </div>
                       <div class="modal-body">
                       '.$datas.'
                       </div>
                       <div class="modal-footer">
                       <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>
                       </div>
                       </div>
                       </div>
                       </div></td>';

                     }
                     ?>

                   </tbody>

                 </table>
               </div>
               <!-- /.card-body -->
             </div>
             <!-- /.card -->
           </div>
           <!-- /.col -->
         </div>
         <!-- /.row -->
       </div>
       <!-- /.container-fluid -->
     </section>
     <!-- /.content -->
   </div>
   <!-- /.content-wrapper -->

   <?php
   include VIEWPATH.'includes/new_copy_footer.php';  
   ?>


   <!-- Control Sidebar -->
   <aside class="control-sidebar control-sidebar-dark">
    <!-- Control sidebar content goes here -->
  </aside>
  <!-- /.control-sidebar -->
</div>

<!-- ./wrapper -->
<?php
include VIEWPATH.'includes/new_script.php';
?>

<!-- Page specific script -->
<script>
  $(function () {
    $("#example1").DataTable({
      "responsive": true, "lengthChange": false, "autoWidth": false,
      "buttons": ["excel", "pdf", "print", "colvis"]
    }).buttons().container().appendTo('#example1_wrapper  .col-md-6:eq(0)');

  });
</script>

<script type="text/javascript">
  function changelist() {
    document.getElementById("myForm").submit();
  }

  $('#reservation').daterangepicker({

    locale: {
      format: 'DD/MM/YYYY'
    }
  })
  $('.select').select2();

</script>
</body>
</html>
<script>
  function modifierarti(idVenteDetails) {
    var quantiteLivre = $('#QUANTITE_LIVRE_' + idVenteDetails).val();

    $.post('<?php echo base_url('vente/Retour_Vente/retourv')?>', {
      ID_VENTE_DETAILS: idVenteDetails,
      QUANTITE_RETOURNE: quantiteLivre
    }, function(response) {
      if (response == '1') {

       Swal.fire({
        icon: 'success',
        title: 'Succès!',
        text: 'Retour de vente effectuée avec succès.',
      }).then(() => {
        location.reload(true); 
      });
    } else {
     Swal.fire({
      icon: 'error',
      title: 'Échec de la retout vente',
      text: 'Quantite depasse celle du commande.',

    });
     console.log('Réponse inattendue:', result);
   }
 });
  }
</script>      

<script>
// Validation du formulaire avant soumission
$(document).on('submit', 'form[id^="myModal"]', function(e) {
    // Vérifier si au moins un article est sélectionné
    const selectedItems = $(this).find('input[name="SELECT[]"]:checked');
    if (selectedItems.length === 0) {
      Swal.fire({
        icon: 'error',
        title: 'Erreur',
        text: 'Veuillez sélectionner au moins un article à retourner'
      });
      e.preventDefault();
      return false;
    }

    // Vérifier les quantités pour les articles sélectionnés
    let isValid = true;
    selectedItems.each(function() {
      const id = $(this).val().replace('SELECT_', '');
      const quantityInput = $(this).closest('tr').find(`input[name="QUANTITE_LIVRE[${id}]"]`);
      const quantity = quantityInput.val();

      if (!quantity || quantity <= 0) {
        isValid = false;
        quantityInput.addClass('is-invalid');
      } else {
        quantityInput.removeClass('is-invalid');
      }
    });

    // Vérifier le motif de retour
    const motif = $(this).find('#ID_MOTIF_RETOUR').val();
    if (!motif) {
      isValid = false;
      $(this).find('#ID_MOTIF_RETOUR').addClass('is-invalid');
    } else {
      $(this).find('#ID_MOTIF_RETOUR').removeClass('is-invalid');
    }

    if (!isValid) {
      Swal.fire({
        icon: 'error',
        title: 'Erreur',
        text: 'Veuillez remplir tous les champs obligatoires pour les articles sélectionnés'
      });
      e.preventDefault();
      return false;
    }

    return true;
  });
</script>
