<?php
header('Content-Type: application/json');

ini_set("display_errors", 1);

if (!isset($baseDir)) {
	$baseDir = $_SERVER['DOCUMENT_ROOT'];
}

require_once $baseDir . '/../scripts/session_functions.php';

ini_wkvs_session();

check_user_permission('wk_leitung');

verify_csrf();

$allowedActions = ['payEntrys' => 2, 'deleteEntrys' => 3];

$requestedAction = trim($_POST['action'] ?? '');

if (!array_key_exists($requestedAction, $allowedActions)) {
    echo json_encode(['success' => false, 'message' => 'Invalid Action']);
    http_response_code(400);
    exit;
}

$actionValue = $allowedActions[$requestedAction];

$user = $_SESSION['user_id_wk_leitung'] ?? 0;

$type = 'wkl';

$data = include $baseDir . '/../scripts/db/db-verbindung-script.php';

if ($data['success'] === false){
	echo json_encode(['success' => false, 'message' => $data['message']]);
    http_response_code(500);
    exit; 
}

require $baseDir . '/../scripts/db/db-tables.php';
require $baseDir . '/../scripts/db/db-functions.php';

if (!isset($_POST['ids']) || !is_array($_POST['ids']) || count($_POST['ids']) < 1) {
    echo json_encode(['success' => false, 'message' => 'Keine Id angegeben']);
    http_response_code(422);
    exit; 
}

$ids = $_POST['ids'];

// Validate: all IDs must be integers
$ids = array_filter($ids, fn($id) => ctype_digit(strval($id)));

if (count($ids) === 0) {
    echo json_encode(['success' => false, 'message' => 'Kein gültiger Input']);
    http_response_code(422);
    exit;
}

// Build placeholders for prepared statement
$placeholders = implode(',', array_fill(0, count($ids), '?'));

$affectedRows = db_select($mysqli, $db_tabelle_verbuchte_startgebueren, "order_status, order_id, `item_ids`, `used_verein_konten`", "order_id IN ($placeholders)", $ids);

$mysqli->begin_transaction();

require $baseDir . '/../scripts/rechnungen/rechnungs-functions.php';

try {
    $stmt = $mysqli->prepare("INSERT INTO $db_tabelle_verbuchte_startgebueren_log (`old_order_status`, `new_order_status`, `order_id`, `edited_by`) VALUES (?, ?, ?, ?)");
    foreach ($affectedRows as $row) {
        $stmt->bind_param("ssss", $row['order_status'], $actionValue, $row['order_id'], $user);
        $stmt->execute();
        update_teilnehmende($row['item_ids'], $row['order_status'], $actionValue);
        update_konten_vereine($row['used_verein_konten'], $row['order_status'], $actionValue);
    }

    // Prepare the SQL statement
    $sql = "UPDATE $db_tabelle_verbuchte_startgebueren SET order_status = ? WHERE order_id IN ($placeholders)";
    $stmt = $mysqli->prepare($sql);

    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Fehler beim Vorbereiten der Abfrage']);
        http_response_code(500);
        exit;
    }

    $params = array_merge([$actionValue], $ids);

    $types = 's' . str_repeat('i', count($ids));
    $stmt->bind_param($types, ...$params);

    if (!$stmt->execute()) {
        echo json_encode(['success' => false, 'message' => 'Fehler beim Löschen']);
        http_response_code(500);
        exit;
    }

    $stmt->close();

    $mysqli->commit();
} catch (Exception $e) {
    $mysqli->rollback();
    exit;
}
$mysqli->close();

echo json_encode(['success' => true, 'message' => 'Bestellungen erfolgreich gelöscht']);
http_response_code(200);
exit;
