<?php

use Dotenv\Dotenv;

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

date_default_timezone_set('Europe/Zurich');

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';



$type = 'wkl';

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

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

$link_expires_at = $_POST['linkExpiresAt'] ?? '';

if ($link_expires_at === '' || strtotime($link_expires_at) === false) {
    echo json_encode(['success' => false, 'message' => 'Ungültiges Ablaufdatum']);
    http_response_code(400);
    exit;
}

if (strtotime($link_expires_at) > strtotime('+8 days')) {
    echo json_encode(['success' => false, 'message' => 'Datum liegt zu weit in der Zukunft']);
    http_response_code(400);
    exit;
}

if (strtotime($link_expires_at) < time()) {
    echo json_encode(['success' => false, 'message' => 'Datum liegt in der Vergangenheit']);
    http_response_code(400);
    exit;
}

$editor_id = $_SESSION['user_id_wk_leitung'];

$plain = trim($_POST['password'] ?? null);

$username = trim($_POST['username'] ?? null);

$namePerson = htmlspecialchars(trim($_POST['namePerson'] ?? null));

$freigaben = $_POST['freigaben'] ?? [];
$freigabenTrainer = $_POST['freigabenTrainer'] ?? [];
$freigabenKampfrichter = $_POST['freigabenKampfrichter'] ?? [];

if (!is_array($freigaben)) {
    $freigaben = [];
}
if (!is_array($freigabenTrainer)) {
    $freigabenTrainer = [];
}
if (!is_array($freigabenKampfrichter)) {
    $freigabenKampfrichter = [];
}

$array = [
    'types' => $freigaben,
    'freigabenTrainer' => $freigabenTrainer,
    'freigabenKampfrichter' => $freigabenKampfrichter
];

// Store as proper JSON string
$freigabe_store = json_encode($array);

$hash = null;
$cipher_store = null;

if ($plain != null) {
    // Hash for login
    $hash = password_hash($plain, PASSWORD_ARGON2ID);


    require $baseDir . '/../composer/vendor/autoload.php';

    $envFile = realpath($baseDir . '/../config/.env.pw-encryption-key');

    if ($envFile === false) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => "Environment file not found"
        ]);
        exit;
    }

    try {
        $envDir = dirname($envFile);
        
        $dotenv = Dotenv::createImmutable($envDir, '.env.pw-encryption-key');
        
        $dotenv->load();
    } catch (Throwable $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => "Dotenv error"
        ]);
    }

    // Encrypt for display
    $iv_length = openssl_cipher_iv_length('aes-256-cbc');
    $iv = random_bytes($iv_length);
    $encrypted = openssl_encrypt($plain, 'aes-256-cbc', $_ENV['PW_ENCRYPTION_KEY'], 0, $iv);
    $cipher_store = base64_encode($iv . $encrypted);
}

$created_at = date('Y-m-d H:i:s');
$updated_at = $created_at;


$stmt = $mysqli->prepare(
    "INSERT INTO {$db_tabelle_intern_benutzende}
    (username, name_person, password_hash, password_cipher, freigabe, created_at, updated_at, edited_by)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
);

$stmt->bind_param(
    "sssssssi",
    $username,
    $namePerson,
    $hash,
    $cipher_store,
    $freigabe_store,
    $created_at,
    $updated_at,
    $editor_id
);

$updated = $stmt->execute();

if (!$updated) {
    echo json_encode(['success' => false, 'message' =>  'DB Error']);
    exit;
}

$new_id = $mysqli->insert_id;

db_delete($mysqli, $db_tabelle_einmal_links, ['user_id' => $new_id]);

$typeOp = "create_profile";

$stmt = $mysqli->prepare("INSERT INTO $db_tabelle_einmal_links (user_id, `type`, `expires_at`) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $new_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();

// Now fetch the auto-generated URL
$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]);