<!DOCTYPE html>
<html lang="fr">
<html>
    <head>
        <meta charset="utf-8" />
        <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
        <link rel="stylesheet" href="style_r.css" />
        <!-- Appel Bootstrap -->
        <!-- CSS only -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" 
        integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" 
        crossorigin="anonymous">
        <!--Appel dataTables--> 
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs5/dt-1.11.5/b-2.2.2/b-colvis-2.2.2/b-html5-2.2.2/cr-1.5.5/date-1.1.2/r-2.2.9/sl-1.3.4/datatables.css"/>
 
        <!-- Appel fontawesome -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" 
        integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" 
        crossorigin="anonymous" referrerpolicy="no-referrer" />
        <!-- Appel Ajax -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        
        <title>Recherche client</title>
    </head>
    <body>
    <!---------------------------------------- Header ---------------------------------------------->
        <header>
            <!-- NavBar Bootstrap -->
            <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <div class="container-fluid">
                <a class="navbar-brand" href="#">ESCAPIA</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    <li class="nav-item">
                    <a class="nav-link active" aria-current="page" href="#">Home</a>
                    </li>
                    <li class="nav-item">
                    <a class="nav-link" href="../menu_recherche.php">Menu Principal</a>
                    </li>
                <!--ne s'affiche pas-->
                    <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                        <li><a class="dropdown-item" href="#">Action</a></li>
                        <li><a class="dropdown-item" href="#">Another action</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="#">Something else here</a></li>
                    </ul>
                </ul>
                
                </div>
            </div>
            </nav>
        </header>
<!----------------------------------------- Corps de la page ---------------------------------------------->
        <section class="container py-5" id="my_section">
            <!--Titre-->
            <div class="row">
                <div class="col-lg-8 col-sm mb-5 mx-auto">
                    <h1 class="fs-4 text-center lead "> Recherche et gestion des clients</h1>
                </div>
            </div>
            <div class="row py-3">
                <div class="col-md-6">
                    <h5 class="fw-bold mb-0"> Liste des clients</h5>
                </div>
                <div class="col-md-6">
                    <div class="d-flex justify-content-end">
                        <!--Boutton modal ajout d'un client-->
                        <button class="btn btn-danger btn-sm me-3" data-bs-toggle="modal" data-bs-target="#createModal">
                            <i class="fas fa-folder-plus"></i> Ajouter un client</button>
                        <!--Boutton export csv-->
                        <a href="../Client/process.php?action=export" id="export" 
                        class="btn btn-success btn-sm"><i class="fas fa-table"></i> Exporter</a>  
                        
                        <!--Boutton d'import csv -->
                        <!--class="form-horizontal"-->
                        <form method="post" action="" enctype="multipart/form-data">
                            <div>
                                <input type="file" name="upcsv" accept=".csv" required/>
                                <input type="submit" value="import">
                            </div>
                        </form>
                </div>
            </div>
            
            <!---------------------------------------- Tableau ---------------------------------------->
            <div class="row">
                <div class="table-responsive" id="orderTable" style="width:200%">
                    
                  <h3 class="text-center text-success">Chargement des clients...</h3>
                
                </div>
            </div>
        </section>
        <!------------------------------------Modal Ajouter un Client --------------------------------->
        <!-- Modal -->
        <div class="modal fade" id="createModal" tabindex="-1" aria-labelledby="createModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createModalLabel">Ajouter un client</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!----------------------------------- Formulaire ------------------------------------->
                <form action="" method="post" id="formOrder" >
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="Nom" name="Nom" placeholder="Nom">
                        <label for="Nom">Nom</label>
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="Nom" name="Prenom" placeholder="Prenom">
                        <label for="Prenom">Prénom</label>
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="Email" name="Email" placeholder="name@example.com">
                        <label for="Email">Adresse Mail</label>
                    </div>
                    <div class="form-floating mb-3">
                    <select class="form-select" id="Type_client" name="Type_client" aria-label="Type_client">
                        <option value="Particulier">Particulier</option>
                        <option value="Société">Société</option>
                    </select>
                    <label for="Type_client">Type du client</label>
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="Num_tel" name="Num_tel" placeholder="Num_tel">
                        <label for="Num_tel">Numéro de téléphone</label>
                    </div>
                    
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="Adresse" name="Adresse" placeholder="Adresse">
                        <label for="Adresse">Adresse</label>
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="Ville" name="Ville" placeholder="Ville">
                        <label for="Ville">Ville</label>
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="Pays" name="Pays" placeholder="Pays">
                        <label for="Pays">Pays</label>
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="Nb_reservation" name="Nb_reservation" placeholder="Nb_reservation">
                        <label for="Nb_reservation">Nombre de réservations</label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-warning" data-bs-dismiss="modal">Retour</button>
                <button type="button" class="btn btn-danger" id="create" name="create">Enregistrer <i class="fa-solid fa-floppy-disk"></i></button>
            </div>
            </div>
        </div>
        </div>
        <!------------------------------------Modal Modifier un Client --------------------------------->
        <!-- Modal -->
        <div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="updateModalLabel">Modifier un client</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!----------------------------------- Formulaire ------------------------------------->
                <form action="" method="post" id="formUpdateOrder" >
                <div class="form-floating mb-3">
                        <input type="hidden" class="form-control" id="ID_clientUpdate" name="ID_clientUpdate" placeholder="ID_clientUpdate">
                        <label for="ID_clientUpdate">Id</label>
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="NomUpdate" name="NomUpdate" placeholder="NomUpdate">
                        <label for="NomUpdate">Nom</label>
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="PrenomUpdate" name="PrenomUpdate" placeholder="PrenomUpdate">
                        <label for="PrenomUpdate">Prénom</label>
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="EmailUpdate" name="EmailUpdate" placeholder="name@example.com">
                        <label for="EmailUpdate">Adresse Mail</label>
                    </div>
                    <div class="form-floating mb-3">
                    <select class="form-select" id="Type_clientUpdate" name="Type_clientUpdate" aria-label="Type_clientUpdate">
                        <option value="particulier">Particulier</option>
                        <option value="Société">Société</option>
                    </select>
                    <label for="Type_clientUpdate">Type du client</label>
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="Num_telUpdate" name="Num_telUpdate" placeholder="Num_telUpdate">
                        <label for="Num_telUpdate">Numéro de téléphone</label>
                    </div>
                    
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="AdresseUpdate" name="AdresseUpdate" placeholder="AdresseUpdate">
                        <label for="AdresseUpdate">Adresse</label>
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="VilleUpdate" name="VilleUpdate" placeholder="VilleUpdate">
                        <label for="VilleUpdate">Ville</label>
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="PaysUpdate" name="PaysUpdate" placeholder="PaysUpdate">
                        <label for="PaysUpdate">Pays</label>
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="Nb_reservationUpdate" name="Nb_reservationUpdate" placeholder="Nb_reservationUpdate">
                        <label for="Nb_reservationUpdate">Nombre de réservations</label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-warning" data-bs-dismiss="modal">Retour</button>
                <button type="button" class="btn btn-danger" id="update" name="update">Enregistrer <i class="fa-solid fa-floppy-disk"></i></button>
            </div>
            </div>
        </div>
        </div>
        <?php
//Fichier pour gérer les requêtes Ajax côté PHP
class DataBase{
    //définition de nos variables de connexion
    //private $host= "mysql:dbname=escapia";
    private $host = 'mysql:host=localhost;dbname=escapia;charset=utf8';
    private $user = "root";
    private $pwd = "";
    //fonction nous permettant de nous connecter à la bdd
    private function getconnexion(){
        try {
            return new PDO($this->host , $this -> user , $this ->pwd);
        }
        //s'il y a une erreur, on la stock dans la variable $e
        catch(PDOException $e){
            //affiche l'erreur 
            die('Erreur:' . $e -> getMessage());
        }
    }
    //fonction nous permettant de créer un nouveau client
    public function create(string $Nom, string $Prenom, string $Email , string $Type_client, 
    string $Num_tel , string $Adresse ,string $Ville, string $Pays, string $Nb_reservation  ){
        $q = $this ->getconnexion()->prepare("INSERT INTO table_client (Nom,Prenom,Email,Type_client,Num_tel,Adresse,Ville,Pays,Nb_reservation) 
        VALUES (:Nom, :Prenom, :Email, :Type_client, :Num_tel, :Adresse, :Ville,:Pays,:Nb_reservation)");
        return $q ->execute([
            'Nom' => $Nom,
            'Prenom' => $Prenom,
            'Email' => $Email,
            'Type_client' => $Type_client,
            'Num_tel' => $Num_tel, 
            'Adresse' => $Adresse,
            'Ville' => $Ville,
            'Pays' => $Pays,
            'Nb_reservation' => $Nb_reservation
        ]);
    }
    //fonction qui récupère tous nos clients
    public function read(){
        //fetchAll() permet de récupérer d'un coup l'ensemble du résultat d'une requête
        return $this->getconnexion()->query("SELECT * FROM table_client ORDER BY ID_client")->fetchAll(PDO::FETCH_OBJ);
    }
    //fonction qui compte combien de clients sont présents dans la table
    public function countClients(): int{
        // [0] sera ce qui contiendra le count
        return (int)$this->getconnexion()->query("SELECT COUNT(ID_client) as count FROM table_client")->fetch()[0];
    }
    //fonction qui récupère un seul client
    public function getSingleClient(int $ID_client){
        $q = $this->getconnexion()->prepare("SELECT * FROM table_client WHERE ID_client = :ID_client");
        $q->execute(['ID_client' => $ID_client]);
        //return $q->fetch(PDO::FETCH_OBJ);
        return $q->fetch(PDO::FETCH_OBJ);
    }
    //fonction qui met à jour les données (envoie les données du formulaire à la bdd)
    public function update(int $ID_client, string $Nom, string $Prenom, string $Email , string $Type_client, 
    string $Num_tel , string $Adresse ,string $Ville, string $Pays, string $Nb_reservation ) {
        $q = $this->getconnexion()->prepare("UPDATE table_client SET ID_client = :ID_client,
        Nom = :Nom, Prenom = :Prenom,
        Email = :Email , Type_client = :Type_client, Num_tel = :Num_tel, Adresse = :Adresse,
        Ville = :Ville, Pays = :Pays, Nb_reservation = :Nb_reservation
        WHERE ID_client = :ID_client");
        return $q->execute([
            'ID_client' => $ID_client,
            'Nom' => $Nom,
            'Prenom' => $Prenom,
            'Email' => $Email,
            'Type_client' => $Type_client,
            'Num_tel' => $Num_tel, 
            'Adresse' => $Adresse,
            'Ville' => $Ville,
            'Pays' => $Pays,
            'Nb_reservation' => $Nb_reservation
        ]);
    }
    //fonction qui supprimer un client (renvoie true si le client a bien été supprimé, false sinon)
    public function delete(int $ID_client) : bool{
        
        $q = $this->getconnexion()->prepare("DELETE FROM table_client WHERE ID_client = :ID_client");
        //echo $q->execute(['ID_client' => $ID_client]);
        return $q->execute(['ID_client' => $ID_client]);
    }
}
$db= new DataBase();
//Créer un client
if(isset($_POST['action']) && $_POST['action']=='create'){ //on vérifie les données reçues par le form
    extract($_POST);
    $db->create( strtoupper($Nom),  ucfirst($Prenom),  $Email ,  $Type_client, $Num_tel ,  $Adresse , 
                $Ville,  $Pays,  $Nb_reservation );
    echo 'on peut créer un client';
}
//Récupérer tous les clients
if(isset($_POST['action']) && $_POST['action']=='fetch'){ //on vérifie les données reçues par le form
    //on créé une variable pour stocker l'affichage
    $output = '';
    //on vérifie que l'on a au moins un client
    if ($db->countClients() > 0){
        $clients = $db->read();
        //entête du tableau
        $output .= '
        <table class="table" id="mytable">
            <thead>
                <tr>
                <th scope="col">Id</th>
                <th scope="col">Nom</th>
                <th scope="col">Prénom</th>
                <th scope="col">Email</th>
                <th scope="col">Type client</th>
                <th scope="col">Numéro de téléphone</th>
                <th scope="col">Adresse</th>
                <th scope="col">Ville</th>
                <th scope="col">Pays</th>
                <th scope="col">Nombre de réservation</th>
                <th scope="col">Actions</th>
                </tr>
            </thead>
            <tbody>
        ';
            foreach($clients as $client){
                $output .= "
                <tr>
                            <th scope=\"row\"> {$client->ID_client} </th>
                            <td> {$client -> Nom} </td>
                            <td>{$client -> Prenom} </td>
                            <td>{$client -> Email} </td>
                            <td>{$client -> Type_client}</td>
                            <td>{$client -> Num_tel} </td>
                            <td>{$client -> Adresse} </td>
                            <td>{$client -> Ville} </td>
                            <td>{$client -> Pays} </td>
                            <td>{$client -> Nb_reservation} </td>
                            <td>
                            <!--Bouton détails-->
                            <a href=\"\" class=\"text-info me-2 infoBtn\" title=\"Voir détails\" 
                            data-id=\"$client->ID_client\">
                                <i class=\"fas fa-info-circle\"></i></a>
                            <!--Bouton modifier-->
                            <a href=\"\" class=\"text-primary me-2 editBtn\" title=\"Modifier\"
                            data-id=\"$client->ID_client\" data-bs-toggle='modal'data-bs-target='#updateModal'>
                                <i class=\"fas fa-edit\"></i></a>   
                            <!--Bouton supprimer-->    
                            <a href=\"\" class=\"text-danger me-2 deleteBtn\" title=\"Supprimer\"
                            data-id=\"$client->ID_client\">
                                <i class=\"fas fa-trash-alt\"></i></a>        
                            </td>
                </tr> ";
            }
        $output .= "</tbody>
                    <!--Footer du tableau (recherches par colonne)-->
                    <tfoot>
                        <tr>
                        <th >Id</th>
                        <th >Nom</th>
                        <th >Prénom</th>
                        <th >Email</th>
                        <th >Type client</th>
                        <th >Numéro de téléphone</th>
                        <th >Adresse</th>
                        <th >Ville</th>
                        <th >Pays</th>
                        <th >Nombre de réservation</th>
                        <th >Actions</th>
                        </tr>
                    </tfoot>
        </table>";
        echo $output;
        //print_r($output);
    } else {
        echo "<h2> Aucun client dans la base de données</h2>";
    }
}
//Récupère un seul client
if(isset($_POST['workingId'])){
    $workingId = (int)$_POST['workingId'];
    echo  json_encode($db->getSingleClient($workingId));
}
//Modifie un client
if(isset($_POST['action']) && $_POST['action']=='update'){ //on vérifie les données reçues par le form
    extract($_POST);
    print_r( $_POST);
    $db->update($ID_clientUpdate, strtoupper($NomUpdate),  ucfirst($PrenomUpdate),  $EmailUpdate ,  $Type_clientUpdate, $Num_telUpdate ,  $AdresseUpdate , 
                $VilleUpdate,  $PaysUpdate,  $Nb_reservationUpdate );
    echo 'on peut modifier un client';
}
//Récupère les infos client
if(isset($_POST['informationId'])){
    $informationId = (int)$_POST['informationId'];
    echo  json_encode($db->getSingleClient($informationId));
}
//Supprimer un client
if(isset($_POST['deleteId'])){
    $deleteId = (int)$_POST['deleteId'];
    echo $db->delete($deleteId);
}
//Exporter une liste de clients
if(isset($_GET['action']) && $_GET['action']=='export'){ //on vérifie les données reçues par le form
    //Nom du fichier Excel créé
   $excelFileName = "Liste des clients importée le : " .date('YmdHi'). '.xls'; 
   //Type d'entête du fichier
   header("Content-Type: application/vnd.ms-excel");
   header("Content-Disposition: attachement; filename=$excelFileName");
   //Nom des colonnes du fichier Excel
   $columnName = ['Id','Nom','Prenom','Email','Type_client','Num_tel', 
    'Adresse','Ville','Pays','Nb_reservation'];
    
    //Première ligne du fichier
    $data= implode("\t" ,array_values($columnName)) . "\n";
    //On vérifie qu'on a au moins un seul client avant d'exporter
    if ($db->countClients() > 0){
        $clients= $db->read();
        foreach ($clients as $client){
            //on remplit les lignes par le nombre d'éléments*l'entête
            $excelData = [$client->ID_client, $client ->Nom, $client ->Prenom, $client -> Email,
            $client ->Type_client, $client ->Num_tel, $client ->Adresse, $client ->Ville,
            $client ->Pays, $client ->Nb_reservation ];
            $data .= implode("\t", $excelData) . "\n"; 
        }
    }else{
        $data = "Aucun client trouvé ...";
    }
    echo $data;
    die();
}
?>
   
        
        <!----------------------------- Footer--------------------------------->
        <footer>
            <!-- Appel JQuery -->
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" 
            referrerpolicy="no-referrer"></script>
            
            <!-- Appel Bootstrap -->
            <!-- JavaScript Bundle with Popper -->
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" 
            integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" 
            crossorigin="anonymous"></script>
            
            <!-- Appel dataTables --> 
            <script type="text/javascript" src="https://cdn.datatables.net/v/bs5/dt-1.11.5/b-2.2.2/b-colvis-2.2.2/b-html5-2.2.2/cr-1.5.5/date-1.1.2/r-2.2.9/sl-1.3.4/datatables.js"></script>
            <!-- Appel SweetAlert2 -->
            <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
            <!-- Ici, on appel notre fichier js -->            
            <script type="text/javascript" src="process_2.js"></script>
        </footer>
    </body>
</html>
 
body {
  font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
  margin: 0;
  padding: 0;
  color: #333;
  background-color: #fff;
}
 
$(document).ready(function(){
    //Fonction JQuery permettant d'organiser le tableau (pagination,sorting)
    //$('table').DataTable()
    $('#mytable').DataTable( {dom : 'Bfrtip',
        buttons: [
            {
                extend: 'csv',
                text: 'Save current page',
                exportOptions: {
                    modifier: {
                        page: 'current'
                    }
                }
            }
        ],
        //fonction de recherche des input du footer
        initComplete: function () {
            this.api().columns().every( function () {
                var that = this;
                $( 'input', this.footer() ).on( 'keyup change clear', function () {
                    if ( that.search() !== this.value ) {
                        that
                            .search( this.value )
                            .draw();
                    }
                } );
            } );
        }
    } );
    /////////////////////////////////////// Créer un client ///////////////////////////////////////////
    $('#create').on('click' , function(e){
        //on récupère les données de notre formulaire
        let formOrder = $('#formOrder')
        //on vérifie que les valeurs du formulaire sont valides
        if (formOrder[0].checkValidity()){
            //On n'envoie pas directement les éléments au serveur
            e.preventDefault()
            $.ajax({
                url: 'process.php',
                type: 'post',//Parce que notre fichier php récupère des variables POST
                data: formOrder.serialize() + '&action=create', //action nous permet de savoir ce qu'on veut faire
                success: function(response){
                    //on cache le modal
                    $('#createModal').modal('hide');
                    //on affiche une alert de confirmation d'ajout du client
                    Swal.fire({
                        icon: 'success',
                        title: 'Le client a bien été ajouté ',
                      })
                    //on vide notre formulaire
                    formOrder[0].reset();
                    getClients();
                }
        })
    }
    })
    /////////////////////////////////////// Récupérer les clients  ///////////////////////////////////
    getClients();
    function getClients(){
        $.ajax({
            url: 'process.php',
            type: 'post',
            data : {action : 'fetch'}, //on renvoie du json
            success: function(response){
                $('#orderTable').html(response);
                $('table').DataTable();
            }
        })
    }
    ////////////////////////////////////// Récupère les données client  ///////////////////////////////////
    $('body').on('click', '.editBtn', function(e){ //on target tous les editBtn de body
        //On n'envoie pas directement les éléments au serveur
        e.preventDefault();
        $.ajax({
            url: 'process.php',
            type: 'post',
            data : {workingId: this.getAttribute('data-id')}, 
            success : function(response){
                console.log(response);
                let clientInfo = JSON.parse(response);
                $('#ID_clientUpdate').val(clientInfo.ID_client);
                $('#NomUpdate').val(clientInfo.Nom);
                $('#PrenomUpdate').val(clientInfo.Prenom);
                $('#EmailUpdate').val(clientInfo.Email);
                $('#Type_clientUpdate').val(clientInfo.Type_client);
                $('#Num_telUpdate').val(clientInfo.Num_tel);
                $('#AdresseUpdate').val(clientInfo.Adresse);
                $('#VilleUpdate').val(clientInfo.Ville);
                $('#PaysUpdate').val(clientInfo.Pays);
                $('#Nb_reservationUpdate').val(clientInfo.Nb_reservation);
            }
        })
    })    
    
    /////////////////////////////////////// Modifier un client /////////////////////////////////////////
    $('#update').on('click' , function(e){
        //on récupère les données de notre formulaire
        let formOrder = $('#formUpdateOrder')
        //on vérifie que les valeurs du formulaire sont valides
        if (formOrder[0].checkValidity()){
            //On n'envoie pas directement les éléments au serveur
            e.preventDefault()
            $.ajax({
                url: 'process.php',
                type: 'post',//Parce que notre fichier php récupère des variables POST
                data: formOrder.serialize() + '&action=update', //action nous permet de savoir ce qu'on veut faire
                success: function(response){
                    console.log(response);
                    //on cache le modal
                    $('#updateModal').modal('hide');
                    //on affiche une alert de confirmation d'ajout du client
                    Swal.fire({
                        icon: 'success',
                        title: 'Le client a bien été modifié ',
                      })
                    //on vide notre formulaire
                    formOrder[0].reset();
                    getClients();
                }
        })
    }
    })
    /////////////////////////////////// Affiche détails client /////////////////////////////////////////
        $('body').on('click', '.infoBtn', function(e){ //on target tous les editBtn de body
        //On n'envoie pas directement les éléments au serveur
        e.preventDefault();
        $.ajax({
            url: 'process.php',
            type: 'post',
            data : {informationId: this.getAttribute('data-id')}, 
            success : function(response){
                console.log(response);
                let information = JSON.parse(response);
                Swal.fire({
                    title: `<strong> Détails du client N° ${information.ID_client} </strong>`,
                    icon: 'info',
                    html:
                      `Nom du client : <b> ${information.Nom} </b> <br>
                      Prenom du client : <b> ${information.Prenom} </b> <br>
                      Email du client : <b> ${information.Email} </b> <br>
                      Type du client : <b> ${information.Type_client} </b> <br>
                      Numéro de téléphone du client : <b> ${information.Num_tel} </b> <br>
                      Adresse du client : <b> ${information.Adresse} </b> <br>
                      Ville du client : <b> ${information.Ville} </b> <br>
                      Pays du client : <b> ${information.Pays} </b> <br>
                      Nombre de réservations du client : <b> ${information.Nb_reservation} </b> <br>
                      `,
                    showCloseButton: true,
                    //showCancelButton: true,
                    focusConfirm: false,
                    //cancelButtonText:
                      //'<i class="fas fa-arrow-left"></i>'
                  })
            }
        })
    })    
    
    ////////////////////////////////////// Supprime un  client /////////////////////////////////////////
    $('body').on('click', '.deleteBtn', function(e){ //on target tous les editBtn de body
        //On n'envoie pas directement les éléments au serveur
        e.preventDefault();
        //alert qui demande à l'utilisateur avant de supprimer un client
        Swal.fire({
            title: 'Êtes-vous sûrs de vouloir supprimer le client n°' + this.getAttribute('data-id') + '?',
            text: "Attention, cette action est irreversible !",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Confirmer'
          }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                  url: 'process.php',
                  type: 'post',
                  data : {deleteId: this.getAttribute('data-id')}, 
                  success : function(response){ 
                      console.log(response);
                      if (response==1){
                        
                        Swal.fire(
                            'Supprimé !',
                            'Le client a bien été supprimé',
                            'success'
                          )
                        }
                        getClients();
        
                    }
                })
                
                }
            })
        })    
    ////////////////////////////////// Recherches footer du tableau //////////////////////////////////
    //ajoute à chaque footer un input de type texte pour les recherches
    $('#mytable tfoot th').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="'+title+'" />' );
    } );
})
28 errors 9 warnings
Line 37: 'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).
Line 37: Missing semicolon.
Line 41: Missing semicolon.
Line 53: Missing semicolon.
Line 58: Missing semicolon.
Line 60: Missing semicolon.
Line 73: Missing semicolon.
Line 86: 'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).
Line 98: Missing semicolon.
Line 99: Missing semicolon.
Line 104: 'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).
Line 104: Missing semicolon.
Line 108: Missing semicolon.
Line 121: Missing semicolon.
Line 126: Missing semicolon.
Line 128: Missing semicolon.
Line 140: 'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).
Line 142: Unexpected '`'.
Line 143: Expected '}' to match '{' from line 141 and instead saw ':'.
Line 143: Expected ')' and instead saw 'info'.
Line 144: Expected an assignment or function call and instead saw an expression.
Line 144: Missing semicolon.
Line 144: Expected '}' to match '{' from line 138 and instead saw ':'.
Line 145: Unexpected '`'.
Line 146: Expected '}' to match '{' from line 134 and instead saw 'Prenom'.
Line 146: Expected ')' and instead saw 'du'.
Line 146: Missing semicolon.
Line 146: Label 'client' on < statement.
Line 146: Expected an identifier and instead saw '<'.
Line 146: Expected an assignment or function call and instead saw an expression.
Line 146: Missing semicolon.
Line 146: Expected an assignment or function call and instead saw an expression.
Line 146: Missing semicolon.
Line 146: Expected an assignment or function call and instead saw an expression.
Line 146: Missing semicolon.
Line 146: Unclosed regular expression.
Line 146: Unrecoverable syntax error. (68% scanned).
Output 300px

This bin was created anonymously and its free preview time has expired. Get a free unrestricted account

Dismiss x
public
Bin info
anonymouspro
0viewers