Files
WKVS/www/intern/scripts/trainer/ajax-neu_temp_order.php
2026-04-12 21:25:44 +02:00

149 lines
3.9 KiB
PHP

<?php
header('Content-Type: application/json');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
$token = isset($_GET['token']) ? $_GET['token'] : '';
/*if ($token !== 'OOlhSGI8CraW6BFmJbj6JFy4sxrYyZ0UxzzbASLhY1sWm0IgqmBXjqqwtqKSvpVFBSBgOFrXHuQLGQj1pxlxj3rlTt1r7kAAWX67dcP'){
echo json_encode(['success' => false, 'message' => '500 Error - Critical Server Error']);
exit;
}*/
if (empty($_SESSION['access_granted_trainer']) || $_SESSION['access_granted_trainer'] !== true || empty($_SESSION['passcodetrainer_id']) || intval($_SESSION['passcodetrainer_id']) < 1 ) {
http_response_code(403);
exit;
}
function generateInvoiceNumber(): int {
return random_int(10000000, 99999999);
}
$orderType = 'Startgebühr';
function createInvoice(mysqli $conn, $tableOrders, $orderType , $preis, $userId, $jsonIds, $order_status): int
{
$maxRetries = 5;
for ($i = 0; $i < $maxRetries; $i++) {
$invoiceNumber = generateInvoiceNumber();
$stmt = $conn->prepare(
"INSERT INTO `$tableOrders` (order_id, order_type, preis, user_id, item_ids, order_status)
VALUES (?, ?, ?, ?, ?, ?)"
);
$stmt->bind_param(
"isdisi",
$invoiceNumber, $orderType, $preis, $userId, $jsonIds, $order_status
);
if ($stmt->execute()) {
return $invoiceNumber; // SUCCESS
}
// Duplicate key error → retry
if ($conn->errno !== 1062) {
throw new RuntimeException(
"Database error ({$conn->errno}): {$conn->error}"
);
}
}
throw new RuntimeException('Failed to generate unique invoice number');
}
$userId = $_SESSION['passcodetrainer_id'];
if (!isset($baseDir)) $baseDir = $_SERVER['DOCUMENT_ROOT'];
$type = 'tr';
$data = include $baseDir . '/../scripts/db/db-verbindung-script.php';
if ($data['success'] === false){
echo json_encode(['success' => false, 'message' => $data['message']]);
exit;
}
require $baseDir . '/../scripts/db/db-tables.php';
$sql = "SELECT bi.id AS basket_id, bi.item_id, p.programm AS programm_name, p.preis, bi.id
FROM $tableBasketItems bi
LEFT JOIN $tableTurnerinnen t ON bi.item_id = t.id
LEFT JOIN $tableProgramme p ON p.programm = t.programm
WHERE bi.user_id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $userId);
$stmt->execute();
$result = $stmt->get_result();
$rows = $result->fetch_all(MYSQLI_ASSOC);
if (!$rows || count($rows) < 1) {
http_response_code(422);
exit;
}
$preis = 0;
foreach ($rows as $r) {
$preis += floatval($r['preis']);
$ids[] = strval($r['item_id']);
}
if ($preis < 0) {
echo json_encode(['success' => false, 'message' => 'Negative price']);
exit;
}
$jsonIds = json_encode($ids);
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_encode(['success' => false, 'message' => 'Invalid JSON']);
exit;
}
// --- Check for existing open order ---
$sql = "SELECT order_id FROM `$tableOrders` WHERE user_id = ? AND order_status = 0 LIMIT 1";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $userId);
$stmt->execute();
$stmt->bind_result($order_id);
if ($stmt->fetch()) {
// --- UPDATE existing order ---
$stmt->close();
$sql = "
UPDATE `$tableOrders`
SET preis = ?, item_ids = ?
WHERE order_id = ?
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("dsi", $preis, $jsonIds, $order_id);
$stmt->execute();
$_SESSION['order_id'] = $order_id;
$_SESSION['order_preis'] = $preis;
} else {
// --- INSERT new order ---
$stmt->close();
$order_status = 0;
$new_id = createInvoice($mysqli, $tableOrders, $orderType, $preis, $userId, $jsonIds, $order_status);
$_SESSION['order_id'] = $new_id;
$_SESSION['order_preis'] = $preis;
}
echo json_encode(['success' => true]);
exit;
?>