<?php
session_start();
/* doc-project | pointages/modif_pointage.php | Gère l’accès sécurisé par appareil et l’affichage du formulaire de modification d’un pointage existant avec assets locaux versionnés sans Modernizr/Respond ni Bootstrap JS. | Expose: aucun | Dépend de: config.php, includes/device_auth.php, includes/asset_version.php, traitement_modif_pointage.php, index.php, connexion.php, pointage.php, js/vendor/jquery-1.11.2.min.js, js/plugins.js, js/main.js | Impacte: session PHP, cookie d’appareil, affichage UI, redirection d’accès, toasts internes | Tables: pos_device_authorizations(token_hash, authorized_at, last_used_at), z_ptg_aqp_pointages(PointageID, UserID, DateHeureEntree, DateHeureSortie), z_ptg_aqp_utilisateurs(UserID, Nom, Prenom) */

require_once "config.php";
require_once __DIR__ . "/includes/device_auth.php";
require_once __DIR__ . "/includes/asset_version.php";
require_device_authorized($pdo);

date_default_timezone_set('Europe/Paris');

$pointage = null;
$employe = null;
$userId = null;

function formatDatetimeLocal($value) {
    $raw = is_string($value) ? trim($value) : '';
    if ($raw === '') return '';
    try {
        $dt = new DateTime($raw);
        $dt->setTimezone(new DateTimeZone('Europe/Paris'));
        return $dt->format('Y-m-d\TH:i');
    } catch (Exception $e) {
        return '';
    }
}

if (isset($_GET['pointageId'])) {
    $pointageId = (int)$_GET['pointageId'];

    // Récupération des informations de pointage
    $stmt = $pdo->prepare("SELECT * FROM z_ptg_aqp_pointages WHERE PointageID = :pointageId");
    $stmt->execute([':pointageId' => $pointageId]);
    $pointage = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($pointage && isset($pointage['UserID'])) {
        $userId = (int)$pointage['UserID'];
        $stmt = $pdo->prepare("SELECT Nom, Prenom FROM z_ptg_aqp_utilisateurs WHERE UserID = :userID LIMIT 1");
        $stmt->execute([':userID' => $userId]);
        $employe = $stmt->fetch(PDO::FETCH_ASSOC);
    }
}

$entreeValue = $pointage ? formatDatetimeLocal($pointage['DateHeureEntree'] ?? '') : '';
$sortieValue = $pointage ? formatDatetimeLocal($pointage['DateHeureSortie'] ?? '') : '';

$employeeFullName = '';
if (is_array($employe)) {
    $nom = isset($employe['Nom']) ? (string)$employe['Nom'] : '';
    $prenom = isset($employe['Prenom']) ? (string)$employe['Prenom'] : '';
    $employeeFullName = trim($nom . ' ' . $prenom);
}
?>
<!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>Modification pointage</title>

<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="<?php echo htmlspecialchars(asset_version_url('css/bootstrap.min.css'), ENT_QUOTES, 'UTF-8'); ?>">
<link rel="stylesheet" href="<?php echo htmlspecialchars(asset_version_url('css/bootstrap-theme.min.css'), ENT_QUOTES, 'UTF-8'); ?>">
<link rel="stylesheet" href="<?php echo htmlspecialchars(asset_version_url('css/fontAwesome.css'), ENT_QUOTES, 'UTF-8'); ?>">
<link rel="stylesheet" href="<?php echo htmlspecialchars(asset_version_url('css/hero-slider.css'), ENT_QUOTES, 'UTF-8'); ?>">
<link rel="stylesheet" href="<?php echo htmlspecialchars(asset_version_url('css/tooplate-style.css'), ENT_QUOTES, 'UTF-8'); ?>">
<link rel="stylesheet" href="<?php echo htmlspecialchars(asset_version_url('css/style.css'), ENT_QUOTES, 'UTF-8'); ?>">
<link rel="stylesheet" href="<?php echo htmlspecialchars(asset_version_url('css/modif-pointage.css'), ENT_QUOTES, 'UTF-8'); ?>">

</head>

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

<main class="ptg-page" role="main">
  <div class="ptg-card">
    <header class="ptg-header">
      <h1>Modification d’un pointage</h1>
      <?php if ($employeeFullName !== ''): ?>
        <p class="ptg-subtitle"><?php echo htmlspecialchars($employeeFullName, ENT_QUOTES, 'UTF-8'); ?></p>
      <?php endif; ?>
    </header>

    <?php if (!$pointage): ?>
      <div class="ptg-alert" role="status">
        Pointage introuvable (ou identifiant manquant).
      </div>
      <div class="ptg-actions">
        <a class="ptg-btn secondary" href="index.php">Retour accueil</a>
      </div>
    <?php else: ?>
      <form class="ptg-form" action="traitement_modif_pointage.php" method="post" autocomplete="off">
        <input type="hidden" name="pointageId" value="<?php echo (int)$pointage['PointageID']; ?>">

        <div class="ptg-field">
          <label for="DateHeureEntree">Date / heure d’entrée</label>
          <input
            id="DateHeureEntree"
            type="datetime-local"
            name="DateHeureEntree"
            value="<?php echo htmlspecialchars($entreeValue, ENT_QUOTES, 'UTF-8'); ?>"
            required
          >
          <p class="ptg-help">Format local (Europe/Paris).</p>
        </div>

        <div class="ptg-field">
          <label for="DateHeureSortie">Date / heure de sortie</label>
          <input
            id="DateHeureSortie"
            type="datetime-local"
            name="DateHeureSortie"
            value="<?php echo htmlspecialchars($sortieValue, ENT_QUOTES, 'UTF-8'); ?>"
          >
          <p class="ptg-help">Laissez vide si le pointage doit rester “en cours”.</p>
        </div>

        <div class="ptg-actions">
          <?php if (is_int($userId) || is_numeric($userId)): ?>
            <a class="ptg-btn secondary" href="pointage.php?employe=<?php echo (int)$userId; ?>&view=1">Annuler</a>
          <?php else: ?>
            <a class="ptg-btn secondary" href="index.php">Annuler</a>
          <?php endif; ?>
          <button type="submit" class="ptg-btn primary">Valider</button>
        </div>
      </form>
    <?php endif; ?>
  </div>
</main>

<script src="<?php echo htmlspecialchars(asset_version_url('js/vendor/jquery-1.11.2.min.js'), ENT_QUOTES, 'UTF-8'); ?>"></script>
<script src="<?php echo htmlspecialchars(asset_version_url('js/plugins.js'), ENT_QUOTES, 'UTF-8'); ?>"></script>
<script src="<?php echo htmlspecialchars(asset_version_url('js/main.js'), ENT_QUOTES, 'UTF-8'); ?>"></script>

</body>
</html>