<?php

use Dotenv\Dotenv;

ini_set('display_errors', 1);

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

$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;
}

$allowed_update_types = ['all', 'no_password', 'new_user'];

$update_type = $_POST['updateType'] ?? '';

if (!in_array($update_type, $allowed_update_types)) {
    echo json_encode(['success' => false, 'message' => 'Unbekannte Aktion']);
    http_response_code(400);
    exit;
}

$editor_id = (int) $_SESSION['user_id_wk_leitung'];

if ($update_type === 'new_user') {
    $stmt = $mysqli->prepare(
        "INSERT INTO {$db_tabelle_intern_benutzende}
        (created_at, updated_at, edited_by, login_active)
        VALUES (?, ?, ?, ?)"
    );

    $loginActive = 1;

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

    $stmt->bind_param(
        "ssis",
        $created_at,
        $updated_at,
        $editor_id,
        $loginActive
    );

    $updated = $stmt->execute();

    $new_id = $mysqli->insert_id;
    echo json_encode(['success' => true, 'message' =>  'Neuer Benutzer wurde erfolgreich erstellt', 'id' => $new_id]);
    http_response_code(200);
    exit;
}

$id = (int) ($_POST['personId'] ?? 0);

if ($id < 1 && $update_type !== 'new_user')  {
    echo json_encode(['success' => false, 'message' => 'Die angegebene ID ist nicht valide']);
    http_response_code(400);
    exit;
}

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

if ($plain_password === '' && $update_type !== 'no_password') {
    echo json_encode(['success' => false, 'message' => 'Kein Passwort angegeben']);
    http_response_code(422);
    exit;
}

if ($update_type !== 'no_password' && strlen($plain_password) < 6) {
    echo json_encode(['success' => false, 'message' => 'Das Passwort muss mindestens 6 Zeichen enthalten']);
    http_response_code(400);
    exit;
}

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

if ($username === '') {
    echo json_encode(['success' => false, 'message' => 'Keinen Benutzernamen angegeben']);
    http_response_code(422);
    exit;
}

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

$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);

if ($update_type !== 'no_password') {
    $hash = password_hash($plain_password, 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"
        ]);
    }

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

if ($update_type === 'no_password') {
    $updated = db_update($mysqli, $db_tabelle_intern_benutzende, [
        'username' => $username,
        'name_person' => $namePerson,
        'freigabe' => $freigabe_store,
        'updated_at' => date('Y-m-d H:i:s'),
        'edited_by' => $editor_id
    ], ['id' => $id]);
} else {
    $updated = db_update($mysqli, $db_tabelle_intern_benutzende, [
        'password_hash' => $hash, 
        'password_cipher' => $cipher_store,
        'username' => $username,
        'name_person' => $namePerson,
        'freigabe' => $freigabe_store,
        'updated_at' => date('Y-m-d H:i:s'),
        'edited_by' => $editor_id
    ], ['id' => $id]);
}

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

echo json_encode(['success' => true, 'message' =>  $username.' wurde erfolgreich aktualisiert.']);
http_response_code(200);
exit;