Geizkragen/offerAdder.php

333 lines
16 KiB
PHP

<?php
/**
* @file offerAdder.php
* @brief Angebot hinzufügen und verwalten.
*
* Dieses Skript stellt eine Benutzeroberfläche und die zugrundeliegende Logik bereit,
* um Angebote für Produkte in verschiedenen Shops hinzuzufügen, anzuzeigen und zu löschen.
* Der Zugriff ist streng auf Administratoren beschränkt.
*
* @author Geizkragen-Team
* @date 2026-04-06
*/
require_once __DIR__ . '/lib/bootstrap.php';
/**
* @brief Zugriffskontrolle für Administratoren.
*
* Überprüft, ob der aktuelle Benutzer angemeldet ist, Rollen zugewiesen hat
* und ob die Rolle 'ADMIN' in seinen Benutzerrollen enthalten ist.
* Falls nicht, wird ein HTTP 403 (Forbidden) Fehler gesendet und eine
* Fehlermeldung auf der Seite angezeigt, bevor die Ausführung beendet wird.
*/
// Only ADMIN
if (empty($_SESSION['user_id']) || empty($_SESSION['user_roles']) || !in_array('ADMIN', $_SESSION['user_roles'], true)) {
http_response_code(403);
include 'header.php';
echo '<main class="auth"><section class="auth__grid"><div class="auth__card">';
echo '<h2 class="auth__title">Zugriff verweigert</h2>';
echo '<p>Du hast keine Berechtigung, Angebote hinzuzufügen.</p>';
echo '</div></section></main>';
include 'footer.php';
exit;
}
/**
* @brief Datenbankverbindung herstellen und Initialisierung von Statusvariablen.
*
* @var mysqli $conn Die aktive Datenbankverbindung.
* @var string $message Eine Nachricht an den Benutzer (Erfolg oder Fehler).
* @var string $messageType Der Typ der Nachricht ('success' oder 'error').
*/
$conn = db_connect();
$message = '';
$messageType = '';
/**
* @brief Verarbeitung von POST-Anfragen zur Angebotsverwaltung.
*
* Überprüft, ob das Formular abgesendet wurde und eine spezifische 'action' gesetzt ist.
* Unterstützte Aktionen sind 'add_offer' (Angebot hinzufügen) und 'delete_offer' (Angebot löschen).
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
/**
* @brief Aktion: Neues Angebot hinzufügen.
*
* Liest die übermittelten Formulardaten aus, validiert diese (Produkt-ID, Shop-ID und
* gültiger Preis) und fügt sie durch ein Prepared Statement in die Tabelle `offers` ein.
*/
if ($_POST['action'] === 'add_offer') {
$productID = (int)$_POST['product_id'];
$shopID = (int)$_POST['shop_id'];
$price = (float)$_POST['price'];
$shippingCost = isset($_POST['shipping_cost']) && $_POST['shipping_cost'] !== '' ? (float)$_POST['shipping_cost'] : 0.00;
$inStock = isset($_POST['in_stock']) ? 1 : 0;
$offerURL = trim($_POST['offer_url']);
if ($productID > 0 && $shopID > 0 && $price >= 0) {
/**
* @brief Einfügen in die Datenbank.
* Bereitet das SQL-Statement vor und bindet die Parameter sicher, um SQL-Injection zu verhindern.
*/
$stmt = $conn->prepare("INSERT INTO offers (productID, shopID, price, shippingCost, inStock, offerURL) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("iiddis", $productID, $shopID, $price, $shippingCost, $inStock, $offerURL);
if ($stmt->execute()) {
$message = 'Angebot erfolgreich hinzugefügt!';
$messageType = 'success';
} else {
$message = 'Fehler beim Hinzufügen des Angebots.';
$messageType = 'error';
}
$stmt->close();
} else {
/**
* @brief Fehlerbehandlung bei ungültigen Eingaben.
*/
$message = 'Bitte alle Pflichtfelder korrekt ausfüllen.';
$messageType = 'error';
}
} elseif ($_POST['action'] === 'delete_offer') {
/**
* @brief Aktion: Existierendes Angebot löschen.
*
* Überprüft die übermittelte Angebot-ID und löscht den entsprechenden Eintrag
* sicher per Prepared Statement aus der Datenbank.
*/
$offerID = (int)$_POST['offer_id'];
if ($offerID > 0) {
$stmt = $conn->prepare("DELETE FROM offers WHERE offerID = ?");
$stmt->bind_param("i", $offerID);
if ($stmt->execute()) {
$message = 'Angebot erfolgreich gelöscht!';
$messageType = 'success';
} else {
$message = 'Fehler beim Löschen des Angebots.';
$messageType = 'error';
}
$stmt->close();
}
}
}
/**
* @brief Abrufen aller Produkte für das Dropdown-Feld.
*
* Führt eine Query aus, um alle verfügbaren Produkte (IDs und Modelle)
* alphabetisch geordnet aus der Datenbank zu laden.
*
* @var array $products Enthält die geladenen Produkte.
*/
// Get all products for dropdown
$productsResult = $conn->query("SELECT productID, model FROM products ORDER BY model ASC");
$products = [];
if ($productsResult) {
while ($row = $productsResult->fetch_assoc()) {
$products[] = $row;
}
}
/**
* @brief Abrufen aller Shops für das Dropdown-Feld.
*
* Führt eine Query aus, um alle verfügbaren Shops (IDs und Namen)
* alphabetisch geordnet aus der Datenbank zu laden.
*
* @var array $shops Enthält die geladenen Shops.
*/
// Get all shops for dropdown
$shopsResult = $conn->query("SELECT shopID, name FROM shops ORDER BY name ASC");
$shops = [];
if ($shopsResult) {
while ($row = $shopsResult->fetch_assoc()) {
$shops[] = $row;
}
}
/**
* @brief Filterlogik für die Anzeige existierender Angebote.
*
* Überprüft, ob über GET ein Filter für eine bestimmte Produkt-ID gesetzt wurde.
* Ist dies der Fall, werden nur Angebote für dieses Produkt angezeigt.
*
* @var int $filterProductID Die ID des zu filternden Produkts (0, wenn kein Filter gesetzt ist).
* @var string $offersQuery Die dynamisch generierte SQL-Abfrage für die Angebote.
*/
$filterProductID = isset($_GET['filter_product_id']) ? (int)$_GET['filter_product_id'] : 0;
$offersQuery = "
SELECT o.offerID, p.model AS productName, s.name AS shopName, o.price
FROM offers o
JOIN products p ON o.productID = p.productID
JOIN shops s ON o.shopID = s.shopID
";
if ($filterProductID > 0) {
/**
* @brief Anwenden des Filters auf die SQL-Query, falls notwendig.
*/
$offersQuery .= " WHERE o.productID = " . $filterProductID;
}
$offersQuery .= " ORDER BY o.offerID DESC";
/**
* @brief Ausführen der Angebot-Abfrage und Speichern in ein Array.
*
* @var array $existingOffers Enthält die geladenen Angebote inkl. Shop- und Produkt-Namen,
* die zur Anzeige in der Tabelle verwendet werden.
*/
// Get existing offers to manage
$offersResult = $conn->query($offersQuery);
$existingOffers = [];
if ($offersResult) {
while ($row = $offersResult->fetch_assoc()) {
$existingOffers[] = $row;
}
}
/**
* @brief Einbinden des HTML-Headers, der Navigation und Stile.
*/
include 'header.php';
?>
<main class="auth">
<section class="auth__grid" style="grid-template-columns: 1fr;">
<div class="auth__card">
<header class="auth__header">
<h2 class="auth__title">Angebot verwalten</h2>
</header>
<?php if ($message): ?>
<p class="<?php echo $messageType === 'success' ? 'auth__alert__sucess' : 'auth__alert__error'; ?>" style="margin-bottom: 1rem;">
<?php echo htmlspecialchars($message); ?>
</p>
<?php endif; ?>
<form method="POST" action="offerAdder.php" class="auth__form">
<input type="hidden" name="action" value="add_offer">
<div class="auth__select__wrap">
<label class="auth__select__label" for="product_id">Produkt auswählen *</label>
<select id="product_id" name="product_id" class="auth__select" required>
<option value="">-- Bitte wählen --</option>
<?php foreach ($products as $product): ?>
<option value="<?php echo htmlspecialchars($product['productID']); ?>" <?php echo (isset($_GET['productID']) && $_GET['productID'] == $product['productID']) ? 'selected' : ''; ?>>
<?php echo htmlspecialchars($product['model']); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="auth__select__wrap" style="margin-top: 1rem;">
<label class="auth__select__label" for="shop_id">Shop auswählen *</label>
<select id="shop_id" name="shop_id" class="auth__select" required>
<option value="">-- Bitte wählen --</option>
<?php foreach ($shops as $shop): ?>
<option value="<?php echo htmlspecialchars($shop['shopID']); ?>">
<?php echo htmlspecialchars($shop['name']); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div style="display: flex; gap: 1rem; margin-top: 1rem;">
<div style="flex: 1;">
<label for="price" style="display: block; margin-bottom: 0.5rem; font-weight: 500; color: var(--text-muted);">Preis (€) *</label>
<input type="number" id="price" name="price" class="auth__input" step="0.01" min="0" required>
</div>
<div style="flex: 1;">
<label for="shipping_cost" style="display: block; margin-bottom: 0.5rem; font-weight: 500; color: var(--text-muted);">Versandkosten (€)</label>
<input type="number" id="shipping_cost" name="shipping_cost" class="auth__input" step="0.01" min="0" value="0.00">
</div>
</div>
<div style="margin-top: 1rem; display: flex; align-items: center; gap: 0.5rem;">
<input type="checkbox" id="in_stock" name="in_stock" value="1" checked style="width: 18px; height: 18px; accent-color: var(--primary-color);">
<label for="in_stock" style="font-weight: 500; color: var(--text-muted); cursor: pointer;">Auf Lager</label>
</div>
<div style="margin-top: 1rem;">
<label for="offer_url" style="display: block; margin-bottom: 0.5rem; font-weight: 500; color: var(--text-muted);">Angebots-URL</label>
<input type="url" id="offer_url" name="offer_url" class="auth__input" placeholder="https://">
</div>
<div class="auth__actions" style="margin-top: 1.5rem;">
<button type="submit" class="auth__submit">Angebot hinzufügen</button>
</div>
</form>
</div>
<div class="auth__card" style="margin-top: 2rem;">
<header class="auth__header">
<h2 class="auth__title">Bestehende Angebote verwalten</h2>
</header>
<form method="GET" action="offerAdder.php" style="margin-bottom: 1.5rem; display: flex; gap: 1rem; align-items: flex-end;">
<div class="auth__select__wrap" style="flex: 1;">
<label class="auth__select__label" for="filter_product_id">Nach Produkt filtern</label>
<select id="filter_product_id" name="filter_product_id" class="auth__select" onchange="this.form.submit()">
<option value="">-- Alle Produkte anzeigen --</option>
<?php foreach ($products as $product): ?>
<option value="<?php echo htmlspecialchars($product['productID']); ?>" <?php echo ($filterProductID == $product['productID']) ? 'selected' : ''; ?>>
<?php echo htmlspecialchars($product['model']); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<?php if ($filterProductID > 0): ?>
<a href="offerAdder.php" style="color: var(--primary-color); text-decoration: none; font-weight: 500; font-size: 0.9rem; padding-bottom: 0.75rem;">Filter zurücksetzen</a>
<?php endif; ?>
</form>
<?php if (count($existingOffers) > 0): ?>
<div style="overflow-x: auto; margin-top: 1rem;">
<table style="width: 100%; border-collapse: collapse; min-width: 500px;">
<thead>
<tr style="border-bottom: 2px solid var(--border-color); text-align: left;">
<th style="padding: 0.75rem 0.5rem; color: var(--text-muted); font-weight: 600;">Produkt</th>
<th style="padding: 0.75rem 0.5rem; color: var(--text-muted); font-weight: 600;">Shop</th>
<th style="padding: 0.75rem 0.5rem; color: var(--text-muted); font-weight: 600;">Preis</th>
<th style="padding: 0.75rem 0.5rem; text-align: right; color: var(--text-muted); font-weight: 600;">Aktion</th>
</tr>
</thead>
<tbody>
<?php foreach ($existingOffers as $offer): ?>
<tr style="border-bottom: 1px solid var(--border-light);">
<td style="padding: 1rem 0.5rem; vertical-align: middle;"><?php echo htmlspecialchars($offer['productName']); ?></td>
<td style="padding: 1rem 0.5rem; vertical-align: middle;"><?php echo htmlspecialchars($offer['shopName']); ?></td>
<td style="padding: 1rem 0.5rem; vertical-align: middle; font-weight: 600;">€<?php echo number_format($offer['price'], 2, ',', '.'); ?></td>
<td style="padding: 1rem 0.5rem; text-align: right; vertical-align: middle;">
<form method="POST" action="offerAdder.php<?php echo $filterProductID > 0 ? '?filter_product_id=' . $filterProductID : ''; ?>" onsubmit="return confirm('Möchtest du dieses Angebot wirklich löschen?');" style="display: inline-block; margin: 0;">
<input type="hidden" name="action" value="delete_offer">
<input type="hidden" name="offer_id" value="<?php echo $offer['offerID']; ?>">
<!--
@brief Button für das Löschen eines Angebotes.
Enthält ein SVG-Icon als Mülleimer. Ein Klick löst einen Bestätigungsdialog (JavaScript) aus.
-->
<button type="submit" style="background: none; border: none; color: #ef4444; cursor: pointer; display: flex; align-items: center; justify-content: flex-end; padding: 0.5rem; border-radius: 4px;" title="Angebot löschen" onmouseover="this.style.backgroundColor='#fee2e2';" onmouseout="this.style.backgroundColor='transparent';">
<svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24">
<polyline points="3 6 5 6 21 6"></polyline>
<path d="M19 6V20a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
</svg>
</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php else: ?>
<p style="margin-top: 1rem; color: var(--text-muted); text-align: center; padding: 2rem 0;">Keine Angebote vorhanden.</p>
<?php endif; ?>
</div>
</section>
</main>
<?php
/**
* @brief Einbinden des HTML-Footers am Ende der Seite.
*/
include 'footer.php';
?>