<?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();

$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['scor']) || empty($_POST['scor']) || $_POST['scor'] === '') {
    echo json_encode(['success' => false, 'message' => 'Keine Referenz angegeben']);
    http_response_code(422);
    exit; 
}

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

$scorFullStr = strval($_POST['scor'] ?? '');

$scor = intval(substr($scorFullStr, 2));

$stmt = $mysqli->prepare(
    "SELECT 1 FROM $db_tabelle_verbuchte_startgebueren WHERE order_id = ? LIMIT 1"
);

$stmt->bind_param('i', $scor);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows !== 1) {
    echo json_encode(['success' => false, 'message' => 'Invalide Referenz']);
    http_response_code(403);
    exit; 
}

$stmt->close();

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

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

    $sql = "UPDATE $db_tabelle_verbuchte_startgebueren SET order_status = 2 WHERE order_id = ?";

    $nstmt = $mysqli->prepare($sql);

    $nstmt->bind_param('i', $scor);

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

$mysqli->close();

echo json_encode(['success' => true, 'message' => 'Rechnung wurde aktualisiert']);
http_response_code(200);
exit; 