<?php
session_start();
require 'config.php';
require 'db.php';

// Prüfen ob das Formular abgeschickt wurde
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if ($dbhandle->connect_error) {
        die("Verbindung fehlgeschlagen: " . $dbhandle->connect_error);
    }

    $clientid = $_SESSION['user']['id'];              // Discord-ID
    $clientname = $_SESSION['user']['nickname'];      // Server-Nickname
    $service = $dbhandle->real_escape_string($_POST['Services']);
    $menge = intval($_POST['preis']); // Anzahl für Reparaturkits
    $modell = $dbhandle->real_escape_string($_POST['modell']);
    $kennzeichen = $dbhandle->real_escape_string($_POST['kennzeichen']);

    if ($service === "repkits") {
    $result = $dbhandle->query("SELECT repkits FROM settings");
    if ($result && $row = $result->fetch_assoc()) {
        $aktuellerBestand = intval($row['repkits']);
        $neuerBestand = $aktuellerBestand + $menge;

        if ($neuerBestand < 0) {
            $meldung = "❌ Fehler: Nicht genug Reparaturkits im Lager!";
        } else {
            // Lagerbestand aktualisieren
            $update = $dbhandle->prepare("UPDATE settings SET repkits = ?");
            $update->bind_param("i", $neuerBestand);
            if ($update->execute()) {
                $meldung = "✅ Lagerbestand aktualisiert! Neuer Bestand: $neuerBestand Kits.";

                // Log-Eintrag
                $aktion = ($menge > 0) ? "ADD" : "REMOVE";
                $log = $dbhandle->prepare("INSERT INTO service_log (user_id, service, menge, aktion) VALUES (?, ?, ?, ?)");
                $log->bind_param("isis", $clientid, $service, $menge, $aktion);
                $log->execute();
                $log->close();
            } else {
                $meldung = "❌ Fehler beim Lager-Update: " . htmlspecialchars($update->error);
            }
            $update->close();
        }
    } else {
        $meldung = "❌ Fehler: Lager nicht gefunden.";
    }
}
else {
    // Auftrag speichern
    $stmt = $dbhandle->prepare("INSERT INTO contracts (user_id, service, preis, modell, kennzeichen) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("isiss", $clientid, $service, $menge, $modell, $kennzeichen);

    if ($stmt->execute()) {
        $meldung = "✅ Eintrag erfolgreich gespeichert!";

        // Log-Eintrag
        $aktion = "ADD";
        $log = $dbhandle->prepare("INSERT INTO service_log (user_id, service, menge, modell, kennzeichen, aktion) VALUES (?, ?, ?, ?, ?, ?)");
        $log->bind_param("isisss", $clientid, $service, $menge, $modell, $kennzeichen, $aktion);
        $log->execute();
        $log->close();
    } else {
        $meldung = "❌ Fehler: " . htmlspecialchars($stmt->error);
    }
    $stmt->close();
}
}
?>




<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Eintragung</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <?php include "header.php"?>
<div id="formdiv">
  <div class="form-group">
    <?php if (isset($meldung)): ?>
      <p style="color: lime; font-weight: bold; text-align: center;"><?php echo $meldung; ?></p>
    <?php endif; ?>
  </div class="form-group">
  <form name="entryform" id="entryform" method="post" action="">
    <h1>Eintragung</h1>

  <div class="form-group">
    <label for="service">Wähle eine Dienstleistung:</label>
    <select name="Services" id="service">
      <option value="Reparatur">Reparatur</option>
      <option value="Carplay">Carplay</option>
      <option value="Tuning">Tuning</option>
      <option value="repkits">Reparatur-Kits</option>
    </select>
  </div>

  <div class="form-group">
    <label for="name">Preis:</label>
    <input type="number" name="preis" id="preis" placeholder="0">
  </div>

  <div class="form-group">
    <label for="modell">Automodell:</label>
    <input type="text" name="modell" id="name" placeholder="infernus">
  </div>
  <div class="form-group">
    <label for="kennzeichen">Kennzeichen:</label>
    <input type="text" name="kennzeichen" id="kennzeichen" placeholder="RXJ 661">
  </div>
    <input type="submit" name="button" id="button" value="Absenden">
  </form>
  
</div>


<script>
document.getElementById('service').addEventListener('change', function () {
    const preisLabel = document.querySelector("label[for='name']");
    const modellGroup = document.querySelector("input[name='modell']").parentNode;
    const kennzeichenGroup = document.querySelector("input[name='kennzeichen']").parentNode;

    if (this.value === 'repkits') {
        preisLabel.textContent = "Menge (+/-):";
        modellGroup.style.display = "none";
        kennzeichenGroup.style.display = "none";
        document.getElementById('preis').placeholder = "+5 oder -3";
    } else {
        preisLabel.textContent = "Preis:";
        modellGroup.style.display = "block";
        kennzeichenGroup.style.display = "block";
        document.getElementById('preis').placeholder = "0";
    }
});
</script>

</body>
</html>