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

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

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

ini_wkvs_session();

check_user_permission('wk_leitung');

verify_csrf();

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

date_default_timezone_set('Europe/Zurich');

$type = 'wkl';

$dbconnection = require $baseDir . '/../scripts/db/db-verbindung-script.php';

if ($dbconnection['success'] !== true){
    echo 'Critical DB Error.';
    exit;
}

$id = intval($_POST['user_id'] ?? 0);
$typeOp = trim($_POST['type'] ?? '');

$allowedTypesOp = ['login', 'pwreset'];

if (!in_array($typeOp, $allowedTypesOp)) {
    echo json_encode(['success' => false, 'message' => 'Operation nicht gestattet']);
    exit;
}

if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => 'No valid ID']);
    exit;
}

// Delete old OTL links for this user (recommended)
db_delete($mysqli, $db_tabelle_einmal_links, ['user_id' => $id]);

$timestamp_one_day = strtotime('+1 days');

$link_expires_at = date("Y-m-d H:i:s", $timestamp_one_day);

$stmt = $mysqli->prepare("INSERT INTO $db_tabelle_einmal_links (user_id, `type`, `expires_at`) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $id, $typeOp, $link_expires_at);


if (!$stmt->execute()) {
    echo json_encode(['success' => false, 'message' => 'Failed to create OTL record']);
    exit;
}

$row_id = $stmt->insert_id;

$stmt->close();

$url = db_get_var($mysqli, "SELECT url FROM $db_tabelle_einmal_links WHERE id = ? LIMIT 1", [$row_id]);

if (!$url) {
    echo json_encode(['success' => false, 'message' => 'Could not fetch generated URL']);
    exit;
}

echo json_encode(['success' => true, 'url' => $url, 'expiresAt' => $link_expires_at]);
