<?php

/* doc-project | pointages/pointage.php | Affiche, sécurise et pilote l’interface de pointage des salariés avec consultation des heures et actions arrivée/départ via PIN. | Expose: aucun | Dépend de: config.php, connexion.php, enregistrement_arrivee.php, enregistrement_depart.php, verifier_pin.php, sortir_employe.php, modif_pointage.php | Impacte: session PHP, redirections, affichage UI, AJAX, pointages en base | Tables: pos_ip_authorizations(ip_address, authorized_until), z_ptg_aqp_utilisateurs(UserID, Nom, Prenom), z_ptg_aqp_pointages(PointageID, UserID, DateHeureEntree, DateHeureSortie) */


// Démarrage ou reprise de la session
session_start();

// Supprimer uniquement $_SESSION['pin_verifie']
if (isset($_SESSION['pin_verifie'])) {
    unset($_SESSION['pin_verifie']);
  }



// Connexion à la base de données
require_once "config.php"; // Assurez-vous que ce fichier existe et contient les bonnes informations de connexion

// Vérification de l'autorisation d'accès
$ip_address = $_SERVER['REMOTE_ADDR'];
$isAuthorized = false;

// Utilisez l'objet PDO déjà créé dans config.php
global $pdo;

if (isset($_SESSION['authorized']) && $_SESSION['authorized'] === true) {
    // L'utilisateur est déjà autorisé via la session
    $isAuthorized = true;
} else {
    // Vérification de l'autorisation de l'IP dans la base de données
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM pos_ip_authorizations WHERE ip_address = :ip_address AND authorized_until > NOW()");
        $stmt->execute([':ip_address' => $ip_address]);
        $count = $stmt->fetchColumn();
        
        if ($count > 0) {
            // L'adresse IP est autorisée
            $_SESSION['authorized'] = true;
            $isAuthorized = true;
        }
    } catch (PDOException $e) {
        // En cas d'erreur de base de données, affichez l'erreur
        echo "Erreur de base de données : " . $e->getMessage();
        exit;
    }
}

// Si l'utilisateur n'est pas autorisé, redirigez-le vers connexion.php
if (!$isAuthorized) {
    header('Location: connexion.php?access=refused');
    exit;
}

date_default_timezone_set('Europe/Paris');

// Récupération de l'ID de l'employé
$employeId = isset($_GET['employe']) ? intval($_GET['employe']) : null;
$viewOnly = (isset($_GET['view']) && $_GET['view'] === '1');

// Récupération des informations de l'employé depuis la BDD
$stmt = $pdo->prepare("SELECT Nom, Prenom FROM z_ptg_aqp_utilisateurs WHERE UserID = :userID");
$stmt->execute([':userID' => $employeId]);
$employe = $stmt->fetch(PDO::FETCH_ASSOC);

// Récupération du dernier pointage de l'employé
$stmt = $pdo->prepare("SELECT * FROM z_ptg_aqp_pointages WHERE UserID = :userID ORDER BY DateHeureEntree DESC, PointageID DESC LIMIT 1");
$stmt->execute([':userID' => $employeId]);
$lastPointage = $stmt->fetch(PDO::FETCH_ASSOC);

$isWorking = $lastPointage && $lastPointage['DateHeureSortie'] === null;

?>
<!DOCTYPE html>

<html>

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8" />

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">





<title>Pointages salariés</title>

<!--



Template 2089 Meteor



http://www.tooplate.com/view/2089-meteor



-->

<meta name="description" content="">

<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="apple-touch-icon" href="apple-touch-icon.png">



<link rel="stylesheet" href="css/bootstrap.min.css">

<link rel="stylesheet" href="css/bootstrap-theme.min.css">

<link rel="stylesheet" href="css/fontAwesome.css">

<link rel="stylesheet" href="css/fontAwesome.css">
<link rel="stylesheet" href="css/hero-slider.css">
<link rel="stylesheet" href="css/tooplate-style.css">
<?php
$cssPath = __DIR__ . '/css/style.css';
$cssVersion = file_exists($cssPath) ? filemtime($cssPath) : time();
?>
<link rel="stylesheet" href="css/style.css?v=<?php echo (int)$cssVersion; ?>">



<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800" rel="stylesheet">



<script src="js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>

</head>



<body class="page-pointage theme-dark">




<div id="about" class="page-section">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="section-heading">
<h1>Pointages <?php echo $employe['Nom'] . " " . $employe['Prenom']; ?></h1>
<div class="line-dec"></div>
<center>
<font color="white">
<br>
<button type="button" id="backHomeButton" class="btn" onclick="window.location.href='index.php';">Retour accueil</button>
<br>
<?php if (!$viewOnly): ?>
    <?php if (!$isWorking): ?>
        <form id="contact">
        <button data-employe="<?php echo $employeId; ?>" id="arrivalButton" class="btn">Arrivée</button>
        </form>
    <?php else: ?>
        <form id="contact2">
        <button data-employe="<?php echo $employeId; ?>" id="departureButton" class="btn">Départ</button>
        </form>
    <?php endif; ?>
<?php endif; ?>
        <!-- Autre contenu... -->
        </font>
        </center>
        </div>
        </div>
        </div>
        </div>
        
        
        <br><br> 
        
        
        
        
        
        <div class="line-dec"></div>
        
        <br><br>
        <center>
        <?php
        // Récupération de l'ID de l'employé
        $employeId = isset($_GET['employe']) ? intval($_GET['employe']) : null;
        
        // Initialisation des variables pour le tableau
        $total_hours = 0;
        $table_rows = "";
        
        $current_month = date('m');
        $current_year = date('Y');
        date_default_timezone_set('Europe/Paris');
        
        
        // Récupération des pointages de l'employé depuis la BDD
        $stmt = $pdo->prepare("SELECT PointageID, UNIX_TIMESTAMP(DateHeureEntree) AS EntreeTimestamp, UNIX_TIMESTAMP(DateHeureSortie) AS SortieTimestamp FROM z_ptg_aqp_pointages WHERE UserID = :userID AND MONTH(DateHeureEntree) = :currentMonth AND YEAR(DateHeureEntree) = :currentYear");
        $stmt->execute([':userID' => $employeId, ':currentMonth' => $current_month, ':currentYear' => $current_year]);
        $pointages = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($pointages as $pointage) {
            // Création de l'objet DateTime pour l'heure d'arrivée
            $arrival_time = DateTime::createFromFormat('U', $pointage['EntreeTimestamp']);
            $arrival_time->setTimezone(new DateTimeZone('Europe/Paris'));
            $date_display = $arrival_time->format('Y-m-d');
            $arrival_time_display = $arrival_time->format('H:i');
            
            // Gérer le cas où le pointage de sortie n'est pas encore défini
            if (empty($pointage['SortieTimestamp'])) {
                $departure_time_display = "En cours";
                $work_hours_display = "En cours";
            } else {
                // Création de l'objet DateTime pour l'heure de départ
                $departure_time = DateTime::createFromFormat('U', $pointage['SortieTimestamp']);
                $departure_time->setTimezone(new DateTimeZone('Europe/Paris'));
                $departure_time_display = $departure_time->format('H:i');
                
                // Calcul des heures travaillées
                $work_seconds = $pointage['SortieTimestamp'] - $pointage['EntreeTimestamp'];
                $work_hours = $work_seconds / 3600;
                $work_hours_display = number_format($work_hours, 2);
                $total_hours += $work_hours;
            }
            
            // Ajout de la ligne dans le tableau
            $table_rows .= "<tr data-pointage-id='".$pointage['PointageID']."' data-entree-timestamp='".$pointage['EntreeTimestamp']."' data-sortie-timestamp='".$pointage['SortieTimestamp']."' onclick='afficherModal(this)'><td>{$date_display}</td><td>{$arrival_time_display}</td><td>{$departure_time_display}</td><td>$work_hours_display</td></tr>";
        }
        
        
        
        
        // Affichage du tableau des pointages
        echo "<table>";
        echo "<tr><th>Date</th><th>Heure d'arrivée</th><th>Heure de départ</th><th>Nombre d'heures</th></tr>";
        echo $table_rows;
        echo "</table>";
        
        ?>
        
        
        <font color="white">
        <?php
        // Affichage du total d'heures travaillées
        echo "Total d'heures travaillées : " . number_format($total_hours, 2);
        ?>
        </font>
        
        
        
        
        
        <br><br><br>
        <font color="white">
        <h4>Affichage sur dates sélectionnées</h4>
        </font>
        
        <br>
        <div class="d1">
        
        <div class="map">
        
        <form id="contact" method="post" action="">
        
        <font color="white"> Date de début : </font><font color="black"><input type="date" name="start_date" required></font><br><br>
        
        <font color="white">Date de fin : </font><font color="black"><input type="date" name="end_date" required></font><br><br>
        
        <font color="black"><input class="btn" id="form-submit" type="submit" value="Afficher la sélection"></font>
        
        </form>
        
        </div></div><br><br><br><br><br><br>
        
        <font color="white">
        
        
        
        <?php
        // Vérification de la soumission du formulaire
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_GET['employe'])) {
            $employeId = intval($_GET['employe']);
            $start_date = $_POST['start_date'];
            $end_date = $_POST['end_date'];
            
            // Conversion des dates en format Y-m-d
            $start_date_formatted = date('Y-m-d', strtotime($start_date));
            $end_date_formatted = date('Y-m-d', strtotime($end_date . ' +1 day'));
            
            $total_hours = 0;
            $table_rows = "";
            date_default_timezone_set('Europe/Paris');
            
            // Requête pour obtenir les pointages entre les dates spécifiées
            $stmt = $pdo->prepare("SELECT PointageID, UNIX_TIMESTAMP(DateHeureEntree) AS EntreeTimestamp, UNIX_TIMESTAMP(DateHeureSortie) AS SortieTimestamp FROM z_ptg_aqp_pointages WHERE UserID = :userID AND DateHeureEntree BETWEEN :startDate AND :endDate");
            
            $stmt->execute([':userID' => $employeId, ':startDate' => $start_date_formatted, ':endDate' => $end_date_formatted]);
            $pointages = $stmt->fetchAll(PDO::FETCH_ASSOC);
            if (!$stmt->execute()) {
                print_r($stmt->errorInfo());
            }
            
            foreach ($pointages as $pointage) {
                // Création de l'objet DateTime pour l'heure d'arrivée
                $arrival_time = DateTime::createFromFormat('U', $pointage['EntreeTimestamp']);
                $arrival_time->setTimezone(new DateTimeZone('Europe/Paris'));
                $date_display = $arrival_time->format('Y-m-d');
                $arrival_time_display = $arrival_time->format('H:i');
                
                // Gérer le cas où le pointage de sortie n'est pas encore défini
                if (empty($pointage['SortieTimestamp'])) {
                    $departure_time_display = "En cours";
                    $work_hours_display = "En cours";
                } else {
                    // Création de l'objet DateTime pour l'heure de départ
                    $departure_time = DateTime::createFromFormat('U', $pointage['SortieTimestamp']);
                    $departure_time->setTimezone(new DateTimeZone('Europe/Paris'));
                    $departure_time_display = $departure_time->format('H:i');
                    
                    // Calcul des heures travaillées
                    $work_seconds = $pointage['SortieTimestamp'] - $pointage['EntreeTimestamp'];
                    $work_hours = $work_seconds / 3600;
                    $work_hours_display = number_format($work_hours, 2);
                    $total_hours += $work_hours;
                }
                
                // Ajout de la ligne dans le tableau
                $table_rows .= "<tr data-pointage-id='".$pointage['PointageID']."' data-entree-timestamp='".$pointage['EntreeTimestamp']."' data-sortie-timestamp='".$pointage['SortieTimestamp']."' onclick='afficherModal(this)'><td>{$date_display}</td><td>{$arrival_time_display}</td><td>{$departure_time_display}</td><td>$work_hours_display</td></tr>";
            }
            
            
            
            // Affichage du tableau
            echo "<table><tr><th>Date</th><th>Heure d'arrivée</th><th>Heure de départ</th><th>Nombre d'heures</th></tr>$table_rows</table>";
            echo "Total d'heures travaillées : " . number_format($total_hours, 2);
            
            
        }
        ?>
        
        
        <br><br><br>
        
        <p><a href="#" onclick="promptExitPin()">Sortir Employé</a></p>
        
        </div>
        
        
        </div></div>
        
        </div>
        
        </div>
        
        
        
        </center>
        
        
        <!-- Modal PIN (design refait) -->
        <div id="modalBackground" onclick="closePinModal()" aria-hidden="true"></div>
        <div id="pinModal" role="dialog" aria-modal="true" aria-labelledby="pinModalTitle">
          <form id="pinForm" onsubmit="verifierPin(); return false;">
            <h2 id="pinModalTitle" class="pin-modal-title">Code PIN</h2>
            <p class="pin-modal-subtitle">Saisissez votre code à 4 chiffres</p>

            <div class="pin-input-wrapper" onclick="focusPinInput()">
              <label for="pinInput" class="sr-only">Code PIN (4 chiffres)</label>
              <div class="pin-boxes" aria-hidden="true">
                <div class="pin-box" data-idx="0"></div>
                <div class="pin-box" data-idx="1"></div>
                <div class="pin-box" data-idx="2"></div>
                <div class="pin-box" data-idx="3"></div>
              </div>
              <input
                type="tel"
                id="pinInput"
                class="pin-hidden-input"
                inputmode="numeric"
                pattern="[0-9]*"
                maxlength="4"
                autocomplete="off"
                autocapitalize="off"
                autocorrect="off"
                spellcheck="false"
                title="Seulement des chiffres."
                value=""
              >
            </div>

            <div class="pin-modal-actions">
              <button type="button" class="pin-modal-btn cancel" onclick="closePinModal()">Annuler</button>
              <button type="submit" class="pin-modal-btn confirm">Valider</button>
            </div>
          </form>
        </div>
        
        
        
        <script>
        
        
        
        
        
        
        
        </script>
        
        
        
        
        
        
        <script src="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        
        <script src="js/vendor/bootstrap.min.js"></script>
        
        <script src="js/plugins.js"></script>
        
        <script src="js/main.js"></script>
        
        


        <script type="text/javascript">

        var employeeFirstName = <?php echo json_encode(($employe && isset($employe['Prenom'])) ? (string)$employe['Prenom'] : '', JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
        function buildPunchToast(action) { var p = employeeFirstName ? (" " + employeeFirstName) : ""; return (action === "depart") ? ("Départ" + p + " enregistré") : ("Arrivée" + p + " enregistrée"); }

        $("#arrivalButton").click(function(e) {
            e.preventDefault();
            let employe = $(this).data('employe');
            $.ajax({
                type: "POST",
                url: "enregistrement_arrivee.php",
                data: {employe: employe},
                success: function(response) {
                    var msg = buildPunchToast("arrivee");
                    window.location.href = "index.php?toast=" + encodeURIComponent(msg) + "&toastType=success";
                },
                error: function() {
                    if (typeof window.showToast === "function") {
                      window.showToast("Erreur lors de l'enregistrement du pointage.", "error");
                    } else {
                      alert("Erreur lors de l'enregistrement du pointage.");
                    }
                }
            });
        });
        
        
        $("#departureButton").click(function(e) {
            e.preventDefault();
            let employe = $(this).data('employe');
            $.ajax({
                type: "POST",
                url: "enregistrement_depart.php",
                data: {employe: employe},
                success: function(response) {
                    var msg = buildPunchToast("depart");
                    window.location.href = "index.php?toast=" + encodeURIComponent(msg) + "&toastType=success";
                },
                error: function() {
                    if (typeof window.showToast === "function") {
                      window.showToast("Erreur lors de l'enregistrement du pointage.", "error");
                    } else {
                      alert("Erreur lors de l'enregistrement du pointage.");
                    }
                }
            });
        });
        
        
        var actionContext = ""; // Variable globale pour stocker le contexte de l'action

function sanitizePinValue(val) {
  return String(val || '').replace(/\D/g, '').slice(0, 4);
}

function updatePinBoxes(pin) {
  var boxes = document.querySelectorAll('#pinModal .pin-box');
  for (var i = 0; i < boxes.length; i++) {
    boxes[i].textContent = (i < pin.length) ? '★' : '';
  }
}

function focusPinInput() {
  var input = document.getElementById('pinInput');
  if (!input) return;
  try { input.focus(); } catch (e) {}
}

function resetPinModal() {
  var input = document.getElementById('pinInput');
  if (input) input.value = '';
  updatePinBoxes('');
}

function openPinModal() {
  var modal = document.getElementById('pinModal');
  var bg = document.getElementById('modalBackground');
  if (!modal || !bg) return;
  modal.style.display = 'block';
  bg.style.display = 'block';
  resetPinModal();
  window.setTimeout(function() { focusPinInput(); }, 10);
}

function closePinModal() {
  var modal = document.getElementById('pinModal');
  var bg = document.getElementById('modalBackground');
  if (modal) modal.style.display = 'none';
  if (bg) bg.style.display = 'none';
  resetPinModal();
}

// Bind input once (digits only + sync UI boxes)
(function bindPinOnce() {
  var input = document.getElementById('pinInput');
  if (!input || input.getAttribute('data-bound') === '1') return;
  input.setAttribute('data-bound', '1');
  input.addEventListener('input', function() {
    var clean = sanitizePinValue(input.value);
    if (input.value !== clean) input.value = clean;
    updatePinBoxes(clean);
  });
  input.addEventListener('keydown', function(e) {
    var key = e.key || '';
    if (key === 'Escape') {
      closePinModal();
    }
  });
})();

function afficherModal(element) {
    var pointageId = element.getAttribute('data-pointage-id');
    window.pointageIdPourModification = pointageId;
    actionContext = "modificationPointage"; // Définir le contexte pour la modification de pointage
    openPinModal();
}

function verifierPin() {
    var input = document.getElementById('pinInput');
    var pin = sanitizePinValue(input ? input.value : '');
    if (input && input.value !== pin) input.value = pin;
    updatePinBoxes(pin);

    if (pin.length !== 4) {
        if (typeof window.showToast === "function") {
          window.showToast("Entrez un code PIN à 4 chiffres.", "error");
        } else {
          alert("Entrez un code PIN à 4 chiffres.");
        }
        try { focusPinInput(); } catch (e) {}
        return;
    }
    if (pin) {
        // Envoi du code PIN à un script PHP pour vérification
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                if (this.responseText == "OK") {
                    // Exécuter l'action en fonction du contexte
                    if (actionContext === "modificationPointage") {
                        window.location.href = "modif_pointage.php?pointageId=" + window.pointageIdPourModification;
                    } else if (actionContext === "sortieEmploye") {
                        sortirEmploye(window.pointageIdPourSortie);
                    }
                } else {
                    if (typeof window.showToast === "function") {
                      window.showToast("Code PIN incorrect.", "error");
                    } else {
                      alert("Code PIN incorrect.");
                    }
                    resetPinModal();
                    try { focusPinInput(); } catch (e) {}
                }
            }
        };
        xhr.open("POST", "verifier_pin.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send("pin=" + pin);
    }
}

function promptExitPin() {
    window.pointageIdPourSortie = <?php echo $employeId; ?>;
    actionContext = "sortieEmploye"; // Définir le contexte pour la sortie de l'employé
    openPinModal();
}

function sortirEmploye(employeId) {
    $.ajax({
        type: "POST",
        url: "sortir_employe.php", // Script PHP pour sortir l'employé
        data: {employe: employeId},
        success: function(response) {
            var msg = "Statut de l'employé mis à jour.";
            window.location.href = "index.php?toast=" + encodeURIComponent(msg) + "&toastType=success";
        },
        error: function() {
            if (typeof window.showToast === "function") {
              window.showToast("Erreur lors de la mise à jour du statut employé.", "error");
            } else {
              alert("Erreur lors de la mise à jour du statut employé.");
            }
        }
    });
}

            
            
            </script>
            
            
            
            </body>
            
            </html>