<?php
include 'db.php';
$step = 1;
$kunde_id = isset($_GET['kunde_id']) ? intval($_GET['kunde_id']) : 0;
$projekt_id = isset($_GET['projekt_id']) ? intval($_GET['projekt_id']) : 0;

// --- Kunde speichern
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['kunde_speichern'])) {
    $firma = $_POST['firmenname'];
    $stmt = $conn->prepare("INSERT INTO kunden (kundennummer, firmenname, email) VALUES (?, ?, ?)");
    $kundennummer = 'K' . str_pad(rand(1,99999), 5, '0', STR_PAD_LEFT);
    $stmt->bind_param("sss", $kundennummer, $firma, $_POST['email']);
    $stmt->execute();
    header("Location: lizenz_wizard.php?kunde_id=" . $conn->insert_id);
    exit;
}

// --- Projekt speichern
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['projekt_speichern'])) {
    $stmt = $conn->prepare("INSERT INTO projekte (kunden_id, name, beschreibung) VALUES (?, ?, ?)");
    $stmt->bind_param("iss", $kunde_id, $_POST['projektname'], $_POST['beschreibung']);
    $stmt->execute();
    header("Location: lizenz_wizard.php?kunde_id=$kunde_id&projekt_id=" . $conn->insert_id);
    exit;
}

// --- Auftrag + Lizenz speichern
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['lizenz_speichern'])) {
    $stmt = $conn->prepare("INSERT INTO auftraege (projekt_id, titel) VALUES (?, ?)");
    $stmt->bind_param("is", $projekt_id, $_POST['auftragstitel']);
    $stmt->execute();
    $auftrag_id = $conn->insert_id;

    $lizenztyp = $_POST['lizenztyp'];
    $startdatum = $_POST['startdatum'];
    $enddatum = $_POST['enddatum'];
    $wert = floatval($_POST['wert']);
    $bemerkung = $_POST['bemerkung'];

    $lizenzschluessel = strtoupper(substr(md5(uniqid($auftrag_id, true)), 0, 11));
    $lizenzschluessel = $auftrag_id . '-' . $lizenzschluessel;

    $stmt = $conn->prepare("INSERT INTO lizenzen (auftrag_id, lizenzname, startdatum, enddatum, wert, bemerkung, lizenzschluessel, typ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("isssdsss", $auftrag_id, $_POST['lizenzname'], $startdatum, $enddatum, $wert, $bemerkung, $lizenzschluessel, $lizenztyp);
    $stmt->execute();

    $success = true;
}

if ($kunde_id) {
    $step = 2;
    $kunde = $conn->query("SELECT * FROM kunden WHERE id = $kunde_id")->fetch_assoc();
    $projekte = $conn->query("SELECT * FROM projekte WHERE kunden_id = $kunde_id");
}
if ($kunde_id && $projekt_id) {
    $step = 3;
    $projekt = $conn->query("SELECT * FROM projekte WHERE id = $projekt_id")->fetch_assoc();
}
?>

<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <title>Lizenz-Wizard</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body { background: #eef1f4; font-family: "Segoe UI", sans-serif; }
    .glass {
      background: rgba(255,255,255,0.95); border-radius: 16px;
      padding: 30px; box-shadow: 0 8px 16px rgba(0,0,0,0.05);
    }
  </style>
</head>
<body>
<div class="container py-5">
  <div class="glass">
    <h2 class="mb-4">🎫 Lizenz-Wizard</h2>

    <ul class="nav nav-tabs mb-4">
      <li class="nav-item"><a class="nav-link <?= $step == 1 ? 'active' : 'disabled' ?>">1. Kunde</a></li>
      <li class="nav-item"><a class="nav-link <?= $step == 2 ? 'active' : 'disabled' ?>">2. Projekt</a></li>
      <li class="nav-item"><a class="nav-link <?= $step == 3 ? 'active' : 'disabled' ?>">3. Auftrag + Lizenz</a></li>
    </ul>

    <?php if ($step == 1): ?>
      <form method="post">
        <input type="hidden" name="kunde_speichern" value="1">
        <div class="mb-3"><label>Firmenname</label><input class="form-control" name="firmenname" required></div>
        <div class="mb-3"><label>Email</label><input class="form-control" name="email" type="email"></div>
        <button class="btn btn-success">Kunde anlegen</button>
      </form>

    <?php elseif ($step == 2): ?>
      <h5>👤 Kunde: <?= htmlspecialchars($kunde['firmenname']) ?></h5>
      <hr>
      <form method="post" class="mb-4">
        <input type="hidden" name="projekt_speichern" value="1">
        <div class="mb-2"><input name="projektname" class="form-control" placeholder="Projektname" required></div>
        <div class="mb-2"><textarea name="beschreibung" class="form-control" placeholder="Beschreibung"></textarea></div>
        <button class="btn btn-success">Projekt anlegen</button>
      </form>
      <h6>ODER auswählen:</h6>
      <?php while($p = $projekte->fetch_assoc()): ?>
        <div class="mb-2">
          <a class="btn btn-outline-primary" href="?kunde_id=<?= $kunde_id ?>&projekt_id=<?= $p['id'] ?>">
            <?= htmlspecialchars($p['name']) ?>
          </a>
        </div>
      <?php endwhile; ?>

    <?php elseif ($step == 3): ?>
      <h5>Projekt: <?= htmlspecialchars($projekt['name']) ?></h5>
      <?php if (isset($success)): ?>
        <div class="alert alert-success mt-3">✅ Lizenz wurde gespeichert!</div>
      <?php endif; ?>
      <form method="post">
        <input type="hidden" name="lizenz_speichern" value="1">
        <div class="mb-3"><label>Auftragstitel</label><input name="auftragstitel" class="form-control" required></div>
        <div class="mb-3"><label>Lizenzname</label><input name="lizenzname" class="form-control" required></div>
        <div class="mb-3">
          <label>Typ</label>
          <select name="lizenztyp" class="form-select" required>
            <option value="Standard">Standard</option>
            <option value="Individual">Individual</option>
          </select>
        </div>
        <div class="row mb-3">
          <div class="col"><label>Startdatum</label><input type="date" name="startdatum" class="form-control" required></div>
          <div class="col"><label>Enddatum</label><input type="date" name="enddatum" class="form-control" required></div>
        </div>
        <div class="mb-3"><label>Wert (€)</label><input name="wert" id="lizenz_wert" class="form-control" type="number" step="0.01" required></div>

        <div class="mb-3">
          <label>Benutzeranzahl (Standard-Modell)</label>
          <input type="number" id="nutzer" class="form-control" value="5" min="1">
        </div>
        <div class="mb-3">
          <label>Jährlich zahlen?</label>
          <select id="jahrzahlung" class="form-select">
            <option value="0">Nein (monatlich)</option>
            <option value="1">Ja (10 % Rabatt)</option>
          </select>
        </div>

        <div class="mb-3"><label>Bemerkung</label><textarea name="bemerkung" class="form-control"></textarea></div>
        <button class="btn btn-success">Lizenz speichern</button>
        <a href="lizenz_wizard.php" class="btn btn-secondary">🔁 Neue Lizenz</a>
      </form>
      <script>
        document.getElementById('nutzer').addEventListener('input', updatePreis);
        document.getElementById('jahrzahlung').addEventListener('change', updatePreis);

        function updatePreis() {
          const nutzer = parseInt(document.getElementById('nutzer').value) || 5;
          const zusatz = Math.max(nutzer - 5, 0) * 5;
          let monatlich = 49 + zusatz;
          if (document.getElementById('jahrzahlung').value == '1') {
            monatlich = Math.round(monatlich * 12 * 0.9);
          }
          document.getElementById('lizenz_wert').value = monatlich;
        }
        updatePreis();
      </script>
    <?php endif; ?>
  </div>
</div>
</body>
</html>
