<?php
require_once __DIR__ . '/../lib/auth.php';
require_once __DIR__ . '/../lib/layout.php';
require_login();

$username  = current_username();
$user      = current_user();

$saved       = isset($_GET['saved']);
$pwchanged   = isset($_GET['pwchanged']);
$avatar_saved = isset($_GET['avatar_saved']);
$error       = isset($_GET['error']) ? urldecode($_GET['error']) : '';

layout_start('OMSORG – Einstellungen', 'settings');
?>
      <h1 class="main-title">Einstellungen</h1>
      <p class="main-sub">Deine persönlichen Daten und Passwort.</p>

      <?php if ($saved): ?>
        <div class="success" style="margin-top:20px">Profil erfolgreich gespeichert.</div>
      <?php elseif ($pwchanged): ?>
        <div class="success" style="margin-top:20px">Passwort erfolgreich geändert.</div>
      <?php elseif ($avatar_saved): ?>
        <div class="success" style="margin-top:20px">Profilbild erfolgreich gespeichert.</div>
      <?php elseif ($error): ?>
        <div class="error" style="margin-top:20px"><?= e($error) ?></div>
      <?php endif; ?>

      <!-- Profilbild -->
      <div class="settings-section">
        <h2 style="font-family:'KindelSerif',Georgia,serif;font-size:1.5rem;margin:0 0 18px">Profilbild</h2>
        <div style="display:flex;align-items:center;gap:24px;flex-wrap:wrap;margin-bottom:20px">
          <?php if (!empty($user['avatar'])): ?>
            <img id="avatar-preview" src="../assets/avatars/<?= e($user['avatar']) ?>"
                 alt="Profilbild" class="settings-avatar-preview">
          <?php else: ?>
            <div id="avatar-preview-placeholder" class="settings-avatar-placeholder">
              <?= e(mb_substr($user['name'], 0, 1)) ?>
            </div>
            <img id="avatar-preview" src="" alt="Vorschau" class="settings-avatar-preview"
                 style="display:none">
          <?php endif; ?>
          <div>
            <form action="../actions/upload-avatar.php" method="post" enctype="multipart/form-data"
                  style="display:flex;flex-direction:column;gap:10px;align-items:flex-start">
              <?= csrf_field() ?>
              <label class="btn" style="cursor:pointer;margin:0">
                Bild auswählen
                <input type="file" name="avatar" accept="image/*" id="avatar-input"
                       style="display:none" onchange="previewAvatar(this)">
              </label>
              <button type="submit" class="btn" id="avatar-upload-btn" style="display:none">
                Hochladen
              </button>
            </form>
            <?php if (!empty($user['avatar'])): ?>
              <form action="../actions/upload-avatar.php" method="post" style="margin-top:8px">
                <?= csrf_field() ?>
                <input type="hidden" name="remove_avatar" value="1">
                <button type="submit" class="btn btn-ghost" style="font-size:.85rem;padding:6px 14px">
                  Bild entfernen
                </button>
              </form>
            <?php endif; ?>
          </div>
        </div>
        <p style="color:var(--muted);font-size:.82rem;margin:0">JPG, PNG, GIF oder WebP · max. 3 MB</p>
      </div>

      <!-- Profildaten -->
      <div class="settings-section">
        <h2 style="font-family:'KindelSerif',Georgia,serif;font-size:1.5rem;margin:0 0 18px">Profildaten</h2>
        <form action="../actions/save-profile.php" method="post" style="max-width:480px">
          <?= csrf_field() ?>
          <input type="hidden" name="action" value="profile">
          <label>
            Name
            <input type="text" value="<?= e($user['name']) ?>" disabled>
          </label>
          <label>
            Benutzername
            <input type="text" value="<?= e($username) ?>" disabled>
          </label>
          <label>
            E-Mail
            <input type="email" name="email" autocomplete="email"
                   value="<?= e($user['email'] ?? '') ?>">
          </label>
          <label>
            Telefon
            <input type="tel" name="telefon" autocomplete="tel"
                   value="<?= e($user['telefon'] ?? '') ?>">
          </label>
          <button type="submit" class="btn">Speichern</button>
        </form>
      </div>

      <!-- Passwort ändern -->
      <div class="settings-section">
        <h2 style="font-family:'KindelSerif',Georgia,serif;font-size:1.5rem;margin:0 0 18px">Passwort ändern</h2>
        <form action="../actions/save-profile.php" method="post" style="max-width:480px">
          <?= csrf_field() ?>
          <input type="hidden" name="action" value="password">
          <label>
            Aktuelles Passwort
            <input type="password" name="old_password" autocomplete="current-password" required>
          </label>
          <label>
            Neues Passwort
            <input type="password" name="new_password" autocomplete="new-password" required minlength="8">
          </label>
          <label>
            Neues Passwort wiederholen
            <input type="password" name="new_password_repeat" autocomplete="new-password" required minlength="8">
          </label>
          <button type="submit" class="btn">Passwort ändern</button>
        </form>
      </div>
<script>
function previewAvatar(input) {
  if (!input.files || !input.files[0]) return;
  const reader = new FileReader();
  reader.onload = e => {
    const img = document.getElementById('avatar-preview');
    const ph  = document.getElementById('avatar-preview-placeholder');
    img.src = e.target.result;
    img.style.display = '';
    if (ph) ph.style.display = 'none';
    document.getElementById('avatar-upload-btn').style.display = '';
  };
  reader.readAsDataURL(input.files[0]);
}
</script>
<?php layout_end(); ?>
