<?php
declare(strict_types=1);

require __DIR__ . '/auth.php';
requireLogin();
$user = currentUser(); // holt aktuell eingeloggten User

$errors  = [];
$success = [];

// Feste Farbpalette (25 gut unterscheidbare Farben)
$colorOptions = [
    '#ef4444', '#f97316', '#facc15', '#22c55e', '#16a34a',
    '#14b8a6', '#06b6d4', '#0ea5e9', '#3b82f6', '#2563eb',
    '#4f46e5', '#6366f1', '#8b5cf6', '#a855f7', '#d946ef',
    '#ec4899', '#f472b6', '#fb7185', '#6b7280', '#4b5563',
    '#111827', '#f59e0b', '#10b981', '#0f766e', '#b91c1c'
];
$colorNames = [
    'Rot', 'Orange', 'Gelb', 'Gruen', 'Gruen dunkel',
    'Mint', 'Cyan', 'Hellblau', 'Blau', 'Blau dunkel',
    'Indigo', 'Violett', 'Lila', 'Lila dunkel', 'Magenta',
    'Pink', 'Rose', 'Koralle', 'Grau', 'Grau dunkel',
    'Schwarz', 'Bernstein', 'Gruen teal', 'Petrol', 'Rot dunkel'
];

// aktuelle Farbe aus DB oder Default, immer klein
$currentColor = strtolower($user['text_color'] ?? '#3b82f6');

// Hilfsfunktion für einfache Validierung der Farbe
function isValidHexColor(string $color): bool
{
    return (bool)preg_match('/^#[0-9a-fA-F]{6}$/', $color);
}

// E-MAIL + FARBE aktualisieren
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'update_profile') {
    $email = trim($_POST['email'] ?? '');
    $color = strtolower(trim($_POST['text_color'] ?? ''));

    if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Bitte eine gültige E-Mail-Adresse eingeben.';
    }

    if ($color === '' || !isValidHexColor($color)) {
        $errors[] = 'Bitte einen gültigen Farbwert im Format #RRGGBB auswählen.';
    }

    if (!$errors) {
        global $pdo;
        // prüfen ob E-Mail schon vergeben ist
        $stmt = $pdo->prepare('SELECT id FROM users WHERE email = :email AND id <> :id');
        $stmt->execute([
            ':email' => $email,
            ':id'    => $user['id'],
        ]);
        if ($stmt->fetch()) {
            $errors[] = 'Diese E-Mail-Adresse wird bereits verwendet.';
        } else {
            $stmt = $pdo->prepare('UPDATE users SET email = :email, text_color = :color WHERE id = :id');
            $stmt->execute([
                ':email' => $email,
                ':color' => $color,
                ':id'    => $user['id'],
            ]);

            $success[] = 'Profil wurde gespeichert.';

            // Lokales User-Array aktualisieren
            $user['email']      = $email;
            $user['text_color'] = $color;
            $currentColor       = $color;
        }
    }
}

// PASSWORT ändern
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'change_password') {
    $current = $_POST['current_password'] ?? '';
    $new1    = $_POST['new_password'] ?? '';
    $new2    = $_POST['new_password_repeat'] ?? '';

    if ($current === '' || $new1 === '' || $new2 === '') {
        $errors[] = 'Bitte alle Passwort-Felder ausfüllen.';
    } elseif ($new1 !== $new2) {
        $errors[] = 'Die neuen Passwörter stimmen nicht überein.';
    } elseif (strlen($new1) < 10) {
        $errors[] = 'Das neue Passwort muss mindestens 10 Zeichen haben.';
    } else {
        if (!password_verify($current, $user['password'])) {
            $errors[] = 'Aktuelles Passwort ist falsch.';
        } else {
            $hash = password_hash($new1, PASSWORD_ARGON2ID);

            global $pdo;
            $stmt = $pdo->prepare('UPDATE users SET password = :pw WHERE id = :id');
            $stmt->execute([
                ':pw' => $hash,
                ':id' => $user['id'],
            ]);

            $success[] = 'Passwort wurde geändert.';

            @mail(
                $user['email'],
                'EKL: Passwort geändert',
                "Hallo {$user['first_name']},\n\ndein Passwort wurde soeben geändert.\n\nWenn du das nicht selbst warst, melde dich bitte sofort beim Administrator.",
                "From: EKL@Mile-dev.com\r\n"
            );
        }
    }
}

?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <!-- wichtig für Mobile, genau wie in articles.php -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mein Profil</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body class="profile-page">
<div id="app">
    <h1>MEIN PROFIL</h1>

    <?php if ($errors): ?>
        <div class="alert alert-error">
            <ul>
                <?php foreach ($errors as $e): ?>
                    <li><?= htmlspecialchars($e) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ($success): ?>
        <div class="alert alert-success">
            <ul>
                <?php foreach ($success as $s): ?>
                    <li><?= htmlspecialchars($s) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <!-- 1. FARBE + 2. E-MAIL -->
    <section>
        <h2>Farbe & E-Mail</h2>

        <form method="post" class="profile-form">
            <input type="hidden" name="action" value="update_profile">

            <!-- Farbe zuerst -->
            <div class="profile-row">
                <span class="profile-label">Textfarbe für deine Einträge</span>

                <input type="hidden" name="text_color" id="text_color"
                       value="<?= htmlspecialchars($currentColor) ?>">

                <div class="color-palette">
                    <?php foreach ($colorOptions as $index => $color): ?>
                        <?php $c = strtolower($color); ?>
                        <?php $name = $colorNames[$index] ?? $c; ?>
                        <button type="button"
                                class="color-swatch<?= ($c === $currentColor ? ' is-selected' : '') ?>"
                                data-color="<?= htmlspecialchars($c) ?>"
                                data-name="<?= htmlspecialchars($name) ?>"
                                style="background: <?= htmlspecialchars($c) ?>;"
                                title="<?= htmlspecialchars($name) ?>">
                        </button>
                    <?php endforeach; ?>
                </div><div class="color-info">
                    Ausgewählte Farbe:
                    <span id="colorHex"><?= htmlspecialchars($currentColor) ?></span> | <span id="colorName"></span>
                </div>

                <div class="profile-color-preview">
                    Vorschau:
                    <span id="colorPreview" style="color: <?= htmlspecialchars($currentColor) ?>;">
                        <?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?>
                    </span>
                </div>
            </div>

            <!-- E-Mail darunter -->
            <div class="profile-row">
                <label class="profile-label" for="email">E-Mail-Adresse</label>
                <input id="email"
                       type="email"
                       name="email"
                       class="profile-input"
                       value="<?= htmlspecialchars($user['email']) ?>"
                       required>
            </div>

            <div class="profile-submit">
                <button type="submit">Speichern</button>
            </div>
        </form>
    </section>

    <!-- 3. PASSWORT ÄNDERN -->
    <section>
        <h2>Passwort ändern</h2>

        <form method="post" class="profile-form">
            <input type="hidden" name="action" value="change_password">

            <div class="profile-row">
                <label class="profile-label" for="pw_current">Aktuelles Passwort</label>
                <input id="pw_current"
                       type="password"
                       name="current_password"
                       class="profile-input"
                       required>
            </div>

            <div class="profile-row">
                <label class="profile-label" for="pw_new">Neues Passwort</label>
                <input id="pw_new"
                       type="password"
                       name="new_password"
                       class="profile-input"
                       required>
            </div>

            <div class="profile-row">
                <label class="profile-label" for="pw_new2">Neues Passwort wiederholen</label>
                <input id="pw_new2"
                       type="password"
                       name="new_password_repeat"
                       class="profile-input"
                       required>
            </div>

            <div class="profile-submit">
                <button type="submit">Passwort ändern</button>
            </div>
        </form>
    </section>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const swatches   = document.querySelectorAll('.color-swatch');
    const hidden     = document.getElementById('text_color');
    const nameLabel  = document.getElementById('colorName');
    const hexLabel   = document.getElementById('colorHex');
    const preview    = document.getElementById('colorPreview');

    const initial = hidden ? hidden.value.toLowerCase() : null;

    if (initial) {
        swatches.forEach(b => {
            const c = (b.dataset.color || '').toLowerCase();
            if (c === initial) {
                b.classList.add('is-selected');
            } else {
                b.classList.remove('is-selected');
            }
        });
        const selected = document.querySelector('.color-swatch[data-color="' + initial + '"]');
        if (hexLabel) {
            hexLabel.textContent = initial;
        }
        if (nameLabel) {
            nameLabel.textContent = selected ? (selected.dataset.name || initial) : initial;
        }
        if (preview) {
            preview.style.color = initial;
        }
    }

    swatches.forEach(btn => {
        btn.addEventListener('click', () => {
            const color = (btn.dataset.color || '').toLowerCase();
            if (!color) return;

            hidden.value = color;

            if (hexLabel) {
                hexLabel.textContent = color;
            }
            if (nameLabel) {
                nameLabel.textContent = btn.dataset.name || color;
            }
            if (preview) {
                preview.style.color = color;
            }

            swatches.forEach(b => b.classList.remove('is-selected'));
            btn.classList.add('is-selected');
        });
    });
});
</script>

<?php include 'footer.php'; ?>

</body>
</html>


