<?php
//la session active après s'être connecter sur la page de connexion
session_start();
if ($_SESSION["connecter"] != "yes") {
header("location:login.php");
exit();
}
if (date("H") < 18)
$bienvenue = "Bonjour et bienvenue "  .
$_SESSION["prenom_nom"];
else
$bienvenue = "Bonsoir et bienvenue "  .
$_SESSION["prenom_nom"];


include 'confconnect.php';

if (isset($_POST['suppression'])) {
    $supp = $_POST['supp'];
    $supprime = $conn->prepare("DELETE FROM DashBoard.peripherique WHERE peripherique.ip = :ip");
    $supprime->bindParam(':ip', $supp);
    $supprime->execute();
}

if (isset($_POST['validation'])) {
    $nom = $_POST['nom'];
    $adressip = $_POST['adressip'];
    $location = $_POST['location'];
    $type = $_POST['type'];

    // Vérifier que les données sont valides (ajoutez d'autres validations si nécessaire)

    $insert = $conn->prepare("INSERT INTO DashBoard.peripherique (`nom`, `ip`, `location`, `Type`) VALUES (:nom, :ip, :location, :type)");
    $insert->bindParam(':nom', $nom);
    $insert->bindParam(':ip', $adressip);
    $insert->bindParam(':location', $location);
    $insert->bindParam(':type', $type);
    
    if ($insert->execute()) {
        // Insertion réussie
        header('Location: confirmation.php'); // Redirige vers une page de confirmation
        exit(); // Assurez-vous d'arrêter l'exécution du script ici
    } else {
        // Erreur lors de l'insertion
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="img/logo_udaf.png" type="image/png">
    <title>Supervision</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700">
    <script>
    function pingAsync(ip, tdElement) {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", "ping.php?ip=" + ip, true);

        xhr.onload = function () {
            if (xhr.status === 200) {
                const response = xhr.responseText;
                const latencyCell = tdElement.nextElementSibling;

                if (response === "success") {
                    tdElement.style.backgroundColor = "green";
                    tdElement.innerText = "Success";
                } else {
                    tdElement.style.backgroundColor = "red";
                    tdElement.innerText = "Failure";
                }
            }
        };

        xhr.onerror = function () {
            console.error("AJAX request error.");
        };

        xhr.send();
    }

    function performPings() {
        const cellElements = document.querySelectorAll(".ping-result-cell");
        cellElements.forEach((cell) => {
            const ip = cell.dataset.ip;
            pingAsync(ip, cell);
        });
    }

    document.addEventListener("DOMContentLoaded", performPings);
    </script>

</head>
<body>
<nav class="navbar navbar-dark navbar-expand-md navigation-clean-search">
                <div class="container"><img src="img/logo_udaf.png" width="70px" height="50px" style="border-radius: 15px;"><a class="navbar-brand" href="#">Udaf Du Var 83</a><button class="navbar-toggler" data-toggle="collapse" data-target="#navcol-1"><span class="sr-only">Toggle navigation</span><span class="navbar-toggler-icon"></span></button>
                    <div class="collapse navbar-collapse"
                        id="navcol-1">

                        <form class="form-inline mr-auto" target="_self">
                            <div class="form-group"><label for="search-field"><i class="fa fa-user-circle"><?php echo $bienvenue ?></i></label></div>
                        </form><span class="navbar-text"> <a href="inscription.php" class="login">Créer un Compte</a></span><a class="btn btn-light action-button" role="button" href="deconnexion.php">Se déconnecter</a></div>
                </div>
            </nav>
    </div>
</div>





<br> <br>




<div class="container contact-form">

            <form method="post" id="insert" autocomplete="FALSE">
                <h2>Les appareils</h2>
               <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#SA">Supprimer un appareil</button>

    <div class="modal fade" id="SA">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Supprimer un appareil</h4>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <!-- Contenu de la fenêtre modale -->
                    <div class="container">
                                    <form method="post" id="sup" autocomplete="FALSE">
                                        <input type="text" class="form-control" placeholder="IP" name="supp">
                                        <input type="submit" name="suppression" class="btn btn-danger" value="Supprimer">
                                    </form>
                            </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>

                </div>
            </div>
        </div>
    </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                    <div class="form-group">
                    <div class="container contact-form">

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
    Ajouter un appareil
</button>

<div class="modal fade" id="myModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Ajouter un appareil</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <!-- Contenu de la fenêtre modale -->
                <div class="container contact-form">

<form method="post" id="insert" autocomplete="FALSE">
<div class="row">
    <div class="col-md-6">
        <div class="form-group">
            <input type="text" class="form-control" placeholder="Name" name="nom">
        </div>
        <div class="form-group">
        <a>Lieu</a>
        <select name="location" class="form-control" placeholder="Location">
            <option></option>
                <?php
                $array = $conn->query("SELECT * FROM DashBoard.location");
                foreach ($array as $key) {
                echo '<option value="' . $key['code'] . '">' . $key['lieu'] . '</option>';
                }
                ?>
        </select>
        </div>
        <div class="form-group">
        <input type="submit" name="validation" class="btn btn-primary" value="Sauvegarder">
        </div>
        
    </div>
    <div class="col-md-6">
    <div class="form-group">
        <input type="text" class="form-control" placeholder="IP" name="adressip">
        </div>
    <div class="form-group">
    <a>Type</a>
        <select name="type" class="form-control" placeholder="Type">

            <option></option>
                <?php
                $array = $conn->query("SELECT * FROM DashBoard.Type");
                foreach ($array as $key) {
                echo '<option value="' . $key['code'] . '">' . $key['type'] . '</option>';
                }
                ?>
        </select>
        </div>
    </div>
</div>
</form>
</div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
            </div>
        </div>
    </div>
</div>
</div>
                        </div>
                    </div>
                </div>
            </form>
    </div>





    <br>


 <div class="container">
    <h1 id="titre">Liste des Pings</h1>
    <div class="contenu">
        <form method="post" class="forme">
            <input type="submit" name="enter" class="btn btn-info" value="Serveurs">
            <input type="submit" name="enter_" class="btn btn-info" value="Imprimantes">
            <input type="submit" name="enter_tous" class="btn btn-info" value="Tous">
        </form>
        <?php
if (!isset($_POST['enter']) && !isset($_POST['enter_']) && !isset($_POST['enter_tous'])) {
    // Si aucun des boutons n'a été soumis, exécuter la requête "enter_tous" par défaut
    $sql = $conn->query("SELECT * FROM DashBoard.peripherique, DashBoard.location, DashBoard.Type WHERE DashBoard.peripherique.location = DashBoard.location.code AND DashBoard.peripherique.Type = DashBoard.Type.code");
}

if (isset($_POST['enter'])) {
    $sql = $conn->query("SELECT * FROM DashBoard.peripherique, DashBoard.location, DashBoard.Type WHERE DashBoard.peripherique.location = DashBoard.location.code AND DashBoard.peripherique.Type = DashBoard.Type.code AND DashBoard.Type.code = 1");
}
if (isset($_POST['enter_'])) {
    $sql = $conn->query("SELECT * FROM DashBoard.peripherique, DashBoard.location, DashBoard.Type WHERE DashBoard.peripherique.location = DashBoard.location.code AND DashBoard.peripherique.Type = DashBoard.Type.code AND DashBoard.Type.code = 2");
}
if (isset($_POST['enter_tous'])) {
    $sql = $conn->query("SELECT * FROM DashBoard.peripherique, DashBoard.location, DashBoard.Type WHERE DashBoard.peripherique.location = DashBoard.location.code AND DashBoard.peripherique.Type = DashBoard.Type.code");
}
?>

    </div>
</div>

<br>

    <div class="container ">
        <div class="row">
            <div class="col-md-offset-1 col-md-10">
                <div class="panel">
                    <div class="panel-heading">
                        <div class="row">
                            <div class="col col-sm-3 col-xs-12">
                                <h4 class="title">Data <span>List</span></h4>
                            </div>
                        </div>
                    </div>
                    <div class="panel-body table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>IP</th>
                                    <th>Location</th>
                                    <th>Type</th>
                                    <th>Ping</th>
                                    <th>Lancer Bureau à distance</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php
                            function generateRDPFile($ip) {
                            ini_set('display_errors', 1);
                            ini_set('display_startup_errors', 1);
                            error_reporting(E_ALL);

                            // Contenu du fichier RDP
                            $content = "full address:s:$ip";

                            // Chemin absolu du dossier de destination
                            $destinationFolder = __DIR__ . "/rdp_files/";

                            // Nom du fichier (utilisez l'adresse IP comme nom)
                            $filename = $destinationFolder . $ip . ".rdp";

                            // Écrire le contenu dans le fichier
                            file_put_contents($filename, $content);

                            return $filename; // Retournez le nom du fichier généré
                            }


                            while ($row = $sql->fetch()) {
                                echo "<tr><td>" . $row['nom'] . "</td>";
                                echo "<td>" . $row['ip'] . "</td>";
                                echo "<td>" . $row['lieu'] . "</td>";
                                echo "<td>" . $row['type'] . "</td>";
                                echo '<td class="ping-result-cell" data-ip="' . $row['ip'] . '">Pinging...</td>';
                                $rdpFilename = generateRDPFile($row['ip']);
                                echo '<td><a href="/new_supervision/rdp_files/' . $row['ip'] . '.rdp" download>Télécharger RDP</a></td>';

                            }
                            ?>
                        </tbody>
                        </table>
                    </div>
                    <div class="panel-footer">
                </div>
            </div>
        </div>
    </div>
</div>





    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.1/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script>
</body>
</html>
