<?php
require_once 'vendor/autoload.php';
use Jumbojett\OpenIDConnectClient;
session_start();
include_once("config/config.php");

// === AUTH BYPASS FOR LOCAL TESTING ===
if (getenv('AUTH_DISABLED') === 'true') {
    $_SESSION['user_authenticated'] = true;
    if (empty($_SESSION['user_name'])) {
        $_SESSION['user_name'] = 'localtest';
    }
}
// === END AUTH BYPASS ===

if (isset($_SESSION['user_authenticated']) && $_SESSION['user_authenticated'] === true) {

// #######################
//DocBee Token genrieren 
// #######################
$loginEndpoint = $docbee_baseurl . '/restApi/login';
$payload = [
    'username'         => $docbee_user, // Benutzername
    'password'         => $docbee_pass, // Passwort
    'lifeTime'         => $docbee_time,   // Gültigkeit in Minuten
    'lifeTimeRefresh'  => true  // Token-Lebenszeit bei jedem Call verlängern
];

$ch = curl_init($loginEndpoint);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Accept: application/json'],
    CURLOPT_POSTFIELDS     => json_encode($payload, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),
    CURLOPT_TIMEOUT        => 20,
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($response === false) {
    throw new RuntimeException('cURL error: ' . curl_error($ch));
}
curl_close($ch);

if ($httpCode !== 200) {
    // 401 bei falschen Credentials usw.
    throw new RuntimeException("Login fehlgeschlagen, HTTP $httpCode: $response");
}

$data = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
$docbee_token = $data['access_token'] ?? null;
if (!$docbee_token) {
    throw new RuntimeException('Kein access_token in der Antwort gefunden.');
}

?>
<!--
index.html — aufgeräumt & ausführlich kommentiert
Projekt: QA System (Test-Template-Lader, Runner & Exporter)
Firma: o-byte.com telekommunikation
Stand: 2025-09-01T17:35:27

Hinweis:
- Funktionen sind mit JSDoc kommentiert (Parameter/Return, Nebenwirkungen).
- Größere Codeabschnitte haben Abschnittsbanner.
- Keine funktionalen Änderungen, nur Kommentare & leichte Struktur.
-->

<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <title>QA System</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="stylesheet" href="style.css">
  <link rel="icon" href="favicon.ico" type="image/x-icon">
</head>
<body>

<!-- Kopfbereich mit Branding und Status -->
<header>
  <div class="brand">
    <img src="logo.png" alt="Logo" class="logo"
         onerror="this.onerror=null;this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%22160%22 height=%2236%22 viewBox=%220 0 160 36%22%3E%3Crect width=%22160%22 height=%2236%22 rx=%226%22 fill=%22%23141722%22/%3E%3Ctext x=%229%22 y=%2224%22 font-family=%22Arial,Helvetica,sans-serif%22 font-size=%2216%22 fill=%22%23e7e7ea%22%3EQA Lite%3C/text%3E%3C/svg%3E';">
    <h1>QA System</h1>
  </div>
  <div class="tags">
    <span id="tplName" class="tag">–</span>
    <span id="statusTag" class="tag">Keine Vorlage geladen</span>
  </div>
</header>

  <!-- Metadaten des Testlaufs (Name/Modul/Versionen/Tester/Status) -->
<section class="meta">
    <div class="row">
      <label>GitLab Vorlage
        <select id="gitlabTplSelect" style="min-width:320px;">
          <option value="">— GitLab-Templates laden —</option>
        </select>
      </label>
      <button class="btn" id="btnGitlabReload" title="Liste neu laden">Neu laden</button>
      <span id="gitlabTplStatus" class="tag">GitLab: nicht verbunden</span>
      <span id="docbeeTokenStatus" class="tag">DocBee: unbekannt</span>
    </div>
    
    <label>Modul <input id="module" placeholder="z. B. CallRouting"></label>
    <label>Modul-Version <input id="moduleVersion" placeholder="z. B. 1.2.3"></label>
    <label>OLM-Nummer <input id="olmNummer" placeholder="z. B. OLM-12345"></label>
    <label>PBX-Version <input id="pbxVersion" placeholder="z. B. 8.1.2"></label>
    <label>Tester <input id="tester" value="<?php echo $_SESSION['user_name']; ?>" readonly></label>
    <label>DocBee Ticket-URL <input id="docbeeUrl" placeholder="https://docbee…"></label>
  </section>

  <section>
    <table id="stepsTable">
      <thead>
        <tr>
          <th>Step</th>
          <th>Expected</th>
          <th>Status</th>
          <th>Kommentar/Evidenz</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <div class="steps-actions">
      <button class="btn" id="btnAddStep">+ Step hinzufügen</button>
      <button class="btn" id="btnAddGroup">+ Gruppe hinzufügen</button>
    </div>
  </section>

  <!-- Aktionen/Exporte & DocBee-Push -->
<section class="actions">
    <button class="btn" id="btnSaveJSON">Als JSON speichern</button>
    <label class="btn like-label" for="loadJSON">Lauf laden</label>
    <input type="file" id="loadJSON" accept=".json,.yaml,.yml" />
    <button class="btn primary" id="btnExportAll">Exportieren (DocBee, DB, PDF)</button>
    <button class="btn" id="btnExportTemplateYAML">Template als YAML</button>
  </section>

  <!-- YAML Parser (js-yaml) für Template-Import -->
  <script src="https://cdn.jsdelivr.net/npm/js-yaml@4.1.0/dist/js-yaml.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js"></script>
  <!-- App-Logik: UI-Steuerung, Parser, Exporte, DocBee-Integration -->




  <script>
    // Token in globales JS-Objekt setzen
    window.DOCBEE_TOKEN = "<?php echo $docbee_token; ?>";
  </script>
  
  <script>
    window.GITLAB = {
      host: <?php echo json_encode(getenv('GITLAB_HOST') ?: 'https://git.steinert.cc'); ?>,
      projectId: <?php echo json_encode(getenv('GITLAB_PROJECT_ID') ?: 'qa/templates'); ?>,
      ref: <?php echo json_encode(getenv('GITLAB_REF') ?: 'main'); ?>,
      path: <?php echo json_encode(getenv('GITLAB_PATH') ?: 'templates'); ?>,
      token: <?php echo json_encode(getenv('GITLAB_TOKEN') ?: ''); ?>
    };
    window.DOCBEE_BASEURL = <?php echo json_encode(getenv('DOCBEE_BASEURL') ?: 'https://obyte.docbee.com'); ?>;
  </script>

  <script src="https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/jspdf-autotable@3.8.2/dist/jspdf.plugin.autotable.min.js"></script>
  <script src="app.js?v=<?=filemtime(__DIR__.('/app.js'))?>"></script>
</body>
</html>
<?php
}
else {
    header("Location: login.php");
    exit();
}
?>