<%@ Language="VBScript" %>
<%
Response.Buffer = True
Response.CharSet = "UTF-8"

' ------- À ADAPTER : même chaîne de connexion que save_results.asp -------
Dim connString
connString = "Provider=SQLOLEDB;Data Source=sql.bsite.net\MSSQL2016;" & _
             "Initial Catalog=nextgnformation_reponses_exercices;" & _
             "User ID=nextgnformation_reponses_exercices;" & _
             "Password=S5$NyFXzEjJCg6jD;"

' ------- À ADAPTER : mot de passe d'accès à cette page -------
Dim ADMIN_PASSWORD
ADMIN_PASSWORD = "Sm#gnttCaYE5f3ED"
' -----------------------------------------------------------------------

Dim authenticated
authenticated = False

If Request.Cookies("tp_admin_auth") = "ok" Then
    authenticated = True
End If

If Request.Form("password") <> "" Then
    If Request.Form("password") = ADMIN_PASSWORD Then
        authenticated = True
        Response.Cookies("tp_admin_auth") = "ok"
        Response.Cookies("tp_admin_auth").Expires = DateAdd("h", 8, Now)
    Else
        authenticated = False
    End If
End If

Function HtmlEscape(s)
    If IsNull(s) Then
        HtmlEscape = ""
        Exit Function
    End If
    s = CStr(s)
    s = Replace(s, "&", "&amp;")
    s = Replace(s, "<", "&lt;")
    s = Replace(s, ">", "&gt;")
    HtmlEscape = s
End Function
%>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Résultats des TP — NextGN Formation</title>
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=DM+Sans:ital,wght@0,300;0,400;0,500;1,300&display=swap" rel="stylesheet">
<style>
:root {
  --amber: #BA7517; --amber-light: #FAEEDA; --amber-dark: #633806;
  --coral: #993C1D; --coral-mid: #D85A30; --coral-light: #FAECE7;
  --bg: #F7F6F2; --white: #FFFFFF; --text: #1a1a18; --text-muted: #6b6a65;
  --border: rgba(0,0,0,0.1);
}
* { box-sizing: border-box; }
body {
  margin: 0; font-family: 'DM Sans', sans-serif; background: var(--bg); color: var(--text);
  padding-top: 70px;
}
.nav-header {
  position: fixed; top: 0; left: 0; right: 0; height: 70px;
  background: rgba(250,238,218,0.98); border-bottom: 2px solid var(--amber);
  display: flex; align-items: center; justify-content: space-between; padding: 0 40px; z-index: 1000;
}
.header-logo {
  font-family: 'Syne', sans-serif; font-size: 16px; font-weight: 700;
  background: linear-gradient(135deg, var(--amber), var(--coral-mid));
  -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;
}
.wrap { max-width: 1200px; margin: 0 auto; padding: 2rem; }
h1 { font-family: 'Syne', sans-serif; font-size: 24px; font-weight: 800; }
.login-box {
  max-width: 360px; margin: 80px auto; background: white; border: 1px solid var(--border);
  border-radius: 16px; padding: 2rem; text-align: center;
}
.login-box input[type="password"] {
  width: 100%; padding: 12px 16px; border: 1.5px solid var(--border); border-radius: 10px;
  font-size: 15px; margin: 1rem 0;
}
.login-box button, .btn {
  font-family: 'Syne', sans-serif; font-size: 13px; font-weight: 700; letter-spacing: 0.05em;
  text-transform: uppercase; background: var(--amber); color: white; border: none;
  border-radius: 30px; padding: 10px 24px; cursor: pointer;
}
.error-msg { color: var(--coral); font-size: 13px; margin-bottom: 0.5rem; }
table.results { width: 100%; border-collapse: collapse; background: white; border-radius: 12px; overflow: hidden; border: 1px solid var(--border); font-size: 13px; }
table.results th {
  background: var(--amber-light); color: var(--amber-dark); font-family: 'Syne', sans-serif;
  font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em;
  padding: 10px 14px; text-align: left; border-bottom: 2px solid var(--amber);
}
table.results td { padding: 10px 14px; border-bottom: 1px solid var(--border); vertical-align: top; }
table.results tr:hover { background: #FAFAFA; }
.detail-toggle { cursor: pointer; color: var(--amber-dark); font-weight: 700; text-decoration: underline; background: none; border: none; font-family: 'DM Sans', sans-serif; font-size: 13px; }
.detail-row { display: none; }
.detail-row.open { display: table-row; }
.detail-content { background: #FAFAFA; padding: 16px 24px; }
.detail-content h3 { font-family: 'Syne', sans-serif; font-size: 13px; margin: 14px 0 6px; color: var(--amber-dark); }
.detail-content p { margin: 4px 0; font-size: 13px; line-height: 1.5; }
.topbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; }
.count-badge { background: var(--amber-light); color: var(--amber-dark); padding: 6px 14px; border-radius: 20px; font-size: 12px; font-weight: 700; font-family: 'Syne', sans-serif; }
.risk-mini { width: 100%; border-collapse: collapse; margin-top: 4px; }
.risk-mini td { border: 1px solid var(--border); padding: 4px 8px; font-size: 12px; }
</style>
</head>
<body>

<nav class="nav-header">
  <span class="header-logo">NextGN Formation — Admin</span>
</nav>

<div class="wrap">
<%
If Not authenticated Then
%>
  <div class="login-box">
    <h1 style="font-size:18px;">Accès résultats TP</h1>
    <% If Request.Form("password") <> "" Then %>
      <div class="error-msg">Mot de passe incorrect.</div>
    <% End If %>
    <form method="POST">
      <input type="password" name="password" placeholder="Mot de passe" autofocus>
      <br>
      <button type="submit">Se connecter</button>
    </form>
  </div>
<%
Else
    Dim conn, rs
    Set conn = Server.CreateObject("ADODB.Connection")
    On Error Resume Next
    conn.Open connString
    If Err.Number <> 0 Then
%>
      <p style="color:var(--coral);">Erreur de connexion à la base : <%= HtmlEscape(Err.Description) %></p>
<%
    Else
        Err.Clear
        Set rs = conn.Execute("SELECT * FROM tp_resultats ORDER BY date_enregistrement DESC")
        If Err.Number <> 0 Then
%>
          <p style="color:var(--coral);">La table tp_resultats n'existe pas encore — aucun envoi reçu pour le moment.</p>
<%
        Else
%>
  <div class="topbar">
    <h1>Résultats des stagiaires</h1>
    <span class="count-badge"><%= IIf_Count(rs) %></span>
  </div>
  <table class="results">
    <tr>
      <th>Groupe / Stagiaire</th>
      <th>Date session</th>
      <th>Cas pratique</th>
      <th>Reçu le</th>
      <th>Détail</th>
    </tr>
<%
          Dim rowIndex
          rowIndex = 0
          Do While Not rs.EOF
              rowIndex = rowIndex + 1
%>
    <tr>
      <td><%= HtmlEscape(rs("nom")) %></td>
      <td><%= HtmlEscape(rs("date_session")) %></td>
      <td><%= HtmlEscape(rs("cas_choisi")) %></td>
      <td><%= HtmlEscape(rs("date_enregistrement")) %></td>
      <td><button class="detail-toggle" onclick="toggleDetail(<%= rowIndex %>)">Voir le détail</button></td>
    </tr>
    <tr class="detail-row" id="detail-<%= rowIndex %>">
      <td colspan="5">
        <div class="detail-content">
          <h3>Réponses TP1 &amp; TP2</h3>
          <%= RenderReponses(rs("reponses_json")) %>
          <h3>TP3 — Analyse de risques</h3>
          <p><strong>Intitulé :</strong> <%= HtmlEscape(rs("tp3_intitule")) %></p>
          <p><strong>Description :</strong> <%= HtmlEscape(rs("tp3_description")) %></p>
          <p><strong>Lieu :</strong> <%= HtmlEscape(rs("tp3_lieu")) %></p>
          <p><strong>Début prévu :</strong> <%= HtmlEscape(rs("tp3_debut")) %></p>
          <%= RenderTableau(rs("tp3_tableau_json")) %>
          <p><strong>Réalisée par :</strong> <%= HtmlEscape(rs("tp3_realise_par")) %> —
             <strong>Vérifiée par :</strong> <%= HtmlEscape(rs("tp3_verifie_par")) %> —
             <strong>MAJ par :</strong> <%= HtmlEscape(rs("tp3_maj_par")) %></p>
        </div>
      </td>
    </tr>
<%
              rs.MoveNext
          Loop
%>
  </table>
<%
        End If
        conn.Close
    End If
End If
%>
</div>

<script>
function toggleDetail(i) {
  var row = document.getElementById('detail-' + i);
  row.classList.toggle('open');
}
</script>
</body>
</html>
<%
Function IIf_Count(rs)
    Dim n
    n = 0
    Do While Not rs.EOF
        n = n + 1
        rs.MoveNext
    Loop
    rs.MoveFirst
    IIf_Count = n & " envoi(s)"
End Function

' --- Parsing JSON minimal via ScriptControl pour l'affichage admin ---
Function RenderReponses(jsonStr)
    Dim out
    out = ""
    If Trim(jsonStr) = "" Then
        RenderReponses = "<p><em>Aucune réponse.</em></p>"
        Exit Function
    End If
    Dim sc
    Set sc = Server.CreateObject("MSScriptControl.ScriptControl")
    sc.Language = "JScript"
    sc.AddCode "function parseArr(s){ return eval('(' + s + ')'); }"
    On Error Resume Next
    Dim arr
    Set arr = sc.Run("parseArr", jsonStr)
    If Err.Number <> 0 Then
        RenderReponses = "<p><em>Erreur de lecture des réponses.</em></p>"
        Exit Function
    End If
    On Error Goto 0
    Dim i
    For i = 0 To arr.length - 1
        Dim q, r
        q = arr.Item(i).question
        r = arr.Item(i).reponse
        If Trim(r) = "" Then r = "(sans réponse)"
        out = out & "<p><strong>" & ServerHtmlEscape(q) & " :</strong> " & ServerHtmlEscape(r) & "</p>"
    Next
    RenderReponses = out
End Function

Function RenderTableau(jsonStr)
    Dim out
    out = ""
    If Trim(jsonStr) = "" Then
        RenderTableau = ""
        Exit Function
    End If
    Dim sc
    Set sc = Server.CreateObject("MSScriptControl.ScriptControl")
    sc.Language = "JScript"
    sc.AddCode "function parseArr(s){ return eval('(' + s + ')'); }"
    On Error Resume Next
    Dim arr
    Set arr = sc.Run("parseArr", jsonStr)
    If Err.Number <> 0 Then
        RenderTableau = "<p><em>Erreur de lecture du tableau.</em></p>"
        Exit Function
    End If
    On Error Goto 0
    out = "<table class='risk-mini'><tr><th>Étape</th><th>Risque</th><th>Mesure</th></tr>"
    Dim i
    For i = 0 To arr.length - 1
        out = out & "<tr><td>" & ServerHtmlEscape(arr.Item(i).etape) & "</td><td>" & _
              ServerHtmlEscape(arr.Item(i).risque) & "</td><td>" & _
              ServerHtmlEscape(arr.Item(i).mesure) & "</td></tr>"
    Next
    out = out & "</table>"
    RenderTableau = out
End Function

Function ServerHtmlEscape(s)
    If IsNull(s) Then
        ServerHtmlEscape = ""
        Exit Function
    End If
    s = CStr(s)
    s = Replace(s, "&", "&amp;")
    s = Replace(s, "<", "&lt;")
    s = Replace(s, ">", "&gt;")
    ServerHtmlEscape = s
End Function
%>
