<?php
// src/auth/register.php
// Wird durch public/auth/register.php aufgerufen

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $lang = $_GET['lang'] ?? 'de';
    header('Location: /login/?lang=' . urlencode($lang) . '&view=register#auth');
    exit;
}

// Benötigt: $pdo, flash(), Session → via fileload
require_once __DIR__ . '/../../config/fileload.php';

$lang     = $_POST['lang'] ?? 'de';
$name     = trim((string)($_POST['name'] ?? ''));
$email    = trim((string)($_POST['email'] ?? ''));
$password = (string)($_POST['password'] ?? '');
$redirect = $_POST['redirect'] ?? '/';

/* ---------------------------------------------------------
   VALIDIERUNG
--------------------------------------------------------- */

if ($name === '' || $email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    flash_set('error', 'Bitte einen gültigen Namen und eine gültige E-Mail-Adresse eingeben.', 'register');
    header('Location: /login/?lang=' . urlencode($lang) . '&view=register#auth');
    exit;
}

if (strlen($password) < 8) {
    flash_set('error', 'Das Passwort muss mindestens 8 Zeichen lang sein.', 'register');
    header('Location: /login/?lang=' . urlencode($lang) . '&view=register#auth');
    exit;
}


/* ---------------------------------------------------------
   PRÜFEN, OB E-MAIL SCHON EXISTIERT
--------------------------------------------------------- */

try {
    $stmt = $pdo->prepare('SELECT id FROM users WHERE email = :email LIMIT 1');
    $stmt->execute([':email' => $email]);
    $existing = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    flash_set('error', 'Es ist ein technischer Fehler aufgetreten. Bitte später erneut versuchen.', 'register');
    header('Location: /login/?lang=' . urlencode($lang) . '&view=register#auth');
    exit;
}

if ($existing) {
    flash_set('error', 'Diese E-Mail-Adresse ist bereits registriert.', 'register');
    header('Location: /login/?lang=' . urlencode($lang) . '&view=register#auth');
    exit;
}


/* ---------------------------------------------------------
   NAME AUFTEILEN (Vorname / Nachname)
--------------------------------------------------------- */

$firstName = $name;
$lastName  = null;

$parts = preg_split('/\s+/', $name);
if (count($parts) >= 2) {
    $firstName = array_shift($parts);
    $lastName  = implode(' ', $parts);
}

/* ---------------------------------------------------------
   USER ANLEGEN
--------------------------------------------------------- */

$username     = $email;
$passwordHash = password_hash($password, PASSWORD_DEFAULT);

try {
    $stmt = $pdo->prepare('
        INSERT INTO users
            (username, email, password_hash, first_name, last_name, plan)
        VALUES
            (:username, :email, :password_hash, :first_name, :last_name, :plan)
    ');
    $stmt->execute([
        ':username'      => $username,
        ':email'         => $email,
        ':password_hash' => $passwordHash,
        ':first_name'    => $firstName,
        ':last_name'     => $lastName,
        ':plan'          => 'free',
    ]);

    $userId = (int)$pdo->lastInsertId();
} catch (Throwable $e) {
    flash_set('error', 'Die Registrierung ist fehlgeschlagen. Bitte versuche es später erneut.', 'register');
    header('Location: /login/?lang=' . urlencode($lang) . '&view=register#auth');
    exit;
}


/* ---------------------------------------------------------
   DIREKT EINLOGGEN
--------------------------------------------------------- */

$initials = '';
if ($firstName !== '') {
    $initials .= mb_substr($firstName, 0, 1);
}
if ($lastName !== null && $lastName !== '') {
    $initials .= mb_substr($lastName, 0, 1);
}
if ($initials === '') {
    $initials = mb_substr($username, 0, 2);
}
$initials = mb_strtoupper($initials);

$_SESSION['user'] = [
    'id'         => $userId,
    'email'      => $email,
    'username'   => $username,
    'first_name' => $firstName,
    'last_name'  => $lastName,
    'plan'       => 'free',
    'initials'   => $initials,
];


/* ---------------------------------------------------------
   ERFOLGSMELDUNG + REDIRECT
--------------------------------------------------------- */

flash_set('success', 'Konto erfolgreich erstellt. Willkommen bei USBCheck!', 'login');

// Redirect absichern: nur interne Pfade erlauben
$target = is_string($redirect) ? trim($redirect) : '/';
if ($target === '' || !str_starts_with($target, '/')) {
    $target = '/';
}

$separator = (strpos($target, '?') === false) ? '?' : '&';
$target .= $separator . 'lang=' . urlencode($lang);

header('Location: ' . $target);
exit;

