<?php
// public/account.php
declare(strict_types=1);

require __DIR__ . '/../src/auth.php';

auth_require_login();

$lang = auth_get_lang();
$user = auth_current_user();
$errors = [];
$flashSuccess = '';
$flashError = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!auth_verify_csrf($_POST['_csrf'] ?? null)) {
        $flashError = 'Sicherheitsfehler. Bitte Formular erneut absenden.';
    } else {
        $fullName      = $_POST['full_name'] ?? ($user['full_name'] ?? '');
        $preferredLang = $_POST['preferred_lang'] ?? ($user['preferred_lang'] ?? $lang);

        $result = auth_update_profile((int)$user['id'], $fullName, $preferredLang);

        if ($result['success'] ?? false) {
            $flashSuccess = 'Profil wurde aktualisiert.';
            $user = auth_current_user(); // neu laden
        } else {
            $errors = $result['errors'] ?? [];
        }
    }
}

$csrfToken = auth_csrf_token();
$initials  = auth_user_initials($user);
$avatarUrl = auth_user_avatar_url($user);
?>
<!DOCTYPE html>
<html lang="<?php echo htmlspecialchars($lang, ENT_QUOTES, 'UTF-8'); ?>">
<head>
    <meta charset="UTF-8">
    <title>Mein Konto – usbcheck.it</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Fonts: Montserrat + Inter -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500&family=Montserrat:wght@600;700&display=swap" rel="stylesheet">

    <!-- Main stylesheet -->
    <link rel="stylesheet" href="/assets/css/main.css?v=1">
</head>
<body>
<?php include __DIR__ . '/partials/header.php'; ?>

<main class="account-page">
    <div class="container">
        <div class="account-grid">
            <!-- Profil -->
            <section class="account-card">
                <h1 class="account-title">Mein Profil</h1>
                <p class="account-subtitle">
                    Passe deinen Namen und deine bevorzugte Sprache an. Der Avatar wird aktuell aus deinen Initialen generiert.
                </p>

                <?php if ($flashSuccess): ?>
                    <div class="auth-flash-success">
                        <?php echo htmlspecialchars($flashSuccess, ENT_QUOTES, 'UTF-8'); ?>
                    </div>
                <?php endif; ?>

                <?php if ($flashError): ?>
                    <div class="auth-flash-error">
                        <?php echo htmlspecialchars($flashError, ENT_QUOTES, 'UTF-8'); ?>
                    </div>
                <?php endif; ?>

                <form method="post" novalidate>
                    <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8'); ?>">

                    <div class="form-row">
                        <label class="form-label" for="email">E-Mail-Adresse</label>
                        <input
                            class="form-input"
                            type="email"
                            id="email"
                            name="email"
                            value="<?php echo htmlspecialchars($user['email'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                            readonly
                        >
                        <div class="form-help">
                            E-Mail-Änderungen bitte später über einen separaten Flow.
                        </div>
                    </div>

                    <div class="form-row">
                        <label class="form-label" for="username">Benutzername</label>
                        <input
                            class="form-input"
                            type="text"
                            id="username"
                            name="username"
                            value="<?php echo htmlspecialchars($user['username'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                            readonly
                        >
                        <div class="form-help">
                            Benutzername ist aktuell nicht änderbar.
                        </div>
                    </div>

                    <div class="form-row">
                        <label class="form-label" for="full_name">Vollständiger Name</label>
                        <input
                            class="form-input"
                            type="text"
                            id="full_name"
                            name="full_name"
                            required
                            value="<?php echo htmlspecialchars($_POST['full_name'] ?? ($user['full_name'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>"
                        >
                        <?php if (!empty($errors['full_name'])): ?>
                            <div class="form-error"><?php echo htmlspecialchars($errors['full_name'], ENT_QUOTES, 'UTF-8'); ?></div>
                        <?php endif; ?>
                    </div>

                    <div class="form-row">
                        <label class="form-label" for="preferred_lang">Bevorzugte Sprache</label>
                        <select class="form-select" id="preferred_lang" name="preferred_lang">
                            <?php
                            $selLang = $_POST['preferred_lang'] ?? ($user['preferred_lang'] ?? $lang);
                            $opts = [
                                'de' => 'Deutsch',
                                'en' => 'English',
                                'it' => 'Italiano',
                                'fr' => 'Français',
                            ];
                            foreach ($opts as $code => $label) {
                                $selected = ($code === $selLang) ? 'selected' : '';
                                echo '<option value="' . htmlspecialchars($code, ENT_QUOTES, 'UTF-8') . '" ' . $selected . '>'
                                    . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . '</option>';
                            }
                            ?>
                        </select>
                    </div>

                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary">
                            Änderungen speichern
                        </button>
                        <a href="/logout.php" class="auth-link">
                            Logout
                        </a>
                    </div>
                </form>
            </section>

            <!-- Avatar / Meta -->
            <section class="account-card">
                <h2 class="account-title">Avatar &amp; Konto</h2>
                <p class="account-subtitle">
                    Dein Avatar wird aktuell aus deinen Initialen erzeugt. Später kannst du hier ein eigenes Bild hochladen.
                </p>

                <div class="account-avatar-preview">
                    <?php if ($avatarUrl): ?>
                        <div class="user-avatar" style="background-image:url('<?php echo htmlspecialchars($avatarUrl, ENT_QUOTES, 'UTF-8'); ?>'); background-size:cover; background-position:center; color:transparent;">
                            &nbsp;
                        </div>
                    <?php else: ?>
                        <div class="user-avatar">
                            <?php echo htmlspecialchars($initials, ENT_QUOTES, 'UTF-8'); ?>
                        </div>
                    <?php endif; ?>
                    <div class="account-avatar-note">
                        <strong>Avatar-Vorschau</strong><br>
                        Standardmäßig Initialen aus deinem Namen.<br>
                        Upload-Funktion folgt in einem späteren Schritt.
                    </div>
                </div>

                <div class="account-meta" style="margin-top:1.5rem;">
                    <p><strong>Account-ID:</strong> <?php echo (int)$user['id']; ?></p>
                    <p><strong>Registriert am:</strong>
                        <?php
                        if (!empty($user['created_at'])) {
                            echo htmlspecialchars($user['created_at'], ENT_QUOTES, 'UTF-8');
                        } else {
                            echo '–';
                        }
                        ?>
                    </p>
                </div>
            </section>
        </div>
    </div>
</main>

<?php include __DIR__ . '/partials/footer.php'; ?>

<script src="/assets/js/lang.js?v=1"></script>
</body>
</html>
