<?php
session_start();
include 'includes/db.php';
include 'includes/header.php';
include 'includes/nav.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id = (int)$_SESSION['user_id'];
$meldung = '';

// --- Profilbild hochladen/aktualisieren ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_avatar'])) {
    // Upload-Ziel
    $uploadDir = __DIR__ . '/uploads/profile/';
    if (!is_dir($uploadDir)) {
        @mkdir($uploadDir, 0775, true);
    }

    if (!empty($_FILES['avatar']['name']) && is_uploaded_file($_FILES['avatar']['tmp_name'])) {
        // Validierungen
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime  = finfo_file($finfo, $_FILES['avatar']['tmp_name']);
        finfo_close($finfo);

        $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
        if (!isset($allowed[$mime])) {
            $meldung = '<div class="alert alert-danger">Ungültiges Dateiformat. Erlaubt: JPG, PNG, WEBP.</div>';
        } elseif ($_FILES['avatar']['size'] > 3 * 1024 * 1024) { // 3 MB
            $meldung = '<div class="alert alert-danger">Datei ist zu groß (max. 3 MB).</div>';
        } else {
            // Dateiname stabil an User-ID binden (ersetzt bestehendes)
            $ext       = $allowed[$mime];
            $fileName  = 'avatar_'.$user_id.'.'.$ext;
            $targetAbs = $uploadDir . $fileName;
            $targetRel = 'uploads/profile/' . $fileName;

            // ggf. alte Avatare mit anderer Endung löschen
            foreach (glob($uploadDir . 'avatar_'.$user_id.'.*') as $old) {
                @unlink($old);
            }

            if (move_uploaded_file($_FILES['avatar']['tmp_name'], $targetAbs)) {
                // Rechte etwas strenger setzen
                @chmod($targetAbs, 0644);

                // In DB speichern (Spalte `profilbild` wird erwartet)
                $stmtUp = $conn->prepare("UPDATE users SET profilbild = ? WHERE id = ?");
                $stmtUp->bind_param("si", $targetRel, $user_id);
                if ($stmtUp->execute()) {
                    $meldung = '<div class="alert alert-success">Profilbild aktualisiert.</div>';
                } else {
                    $meldung = '<div class="alert alert-warning">Bild gespeichert, aber DB-Update fehlgeschlagen. Prüfe, ob die Spalte <code>profilbild</code> in <code>users</code> existiert.</div>';
                }
                $stmtUp->close();
            } else {
                $meldung = '<div class="alert alert-danger">Upload fehlgeschlagen.</div>';
            }
        }
    } else {
        $meldung = '<div class="alert alert-warning">Bitte eine Datei auswählen.</div>';
    }
}

// --- Userdaten laden ---
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user   = $result->fetch_assoc();
$stmt->close();

// Avatar-URL ermitteln
$avatarUrl = '';
if (!empty($user['profilbild'])) {
    $avatarUrl = htmlspecialchars($user['profilbild'], ENT_QUOTES, 'UTF-8');
}

// Fallback-Avatar (SVG Data-URL)
$defaultAvatar = 'data:image/svg+xml;utf8,' . rawurlencode('
<svg xmlns="http://www.w3.org/2000/svg" width="240" height="240" viewBox="0 0 100 100">
  <defs>
    <linearGradient id="g" x1="0" x2="1" y1="0" y2="1">
      <stop offset="0" stop-color="#e9ecef"/>
      <stop offset="1" stop-color="#dee2e6"/>
    </linearGradient>
  </defs>
  <rect width="100" height="100" fill="url(#g)"/>
  <circle cx="50" cy="38" r="16" fill="#adb5bd"/>
  <path d="M15,92c6-18,26-24,35-24s29,6,35,24" fill="#adb5bd"/>
</svg>');
?>
<style>
  .profile-card{
    border:1px solid #e9ecef; border-radius:1rem; background:#fff;
    box-shadow:0 4px 16px rgba(0,0,0,.04);
  }
  .avatar-wrap{
    width:132px; height:132px; border-radius:50%;
    overflow:hidden; border:4px solid #fff; box-shadow:0 2px 12px rgba(0,0,0,.08);
    background:#f8f9fa;
  }
  .avatar-wrap img{
    width:100%; height:100%; object-fit:cover;
  }
  .kv{ background:#f8f9fa; border:1px solid #eef0f2; border-radius:.75rem; padding:.75rem 1rem;}
  .kv .k{color:#6c757d; font-size:.9rem;}
  .kv .v{font-weight:600;}
</style>

<div class="container mt-5">
  <div class="d-flex align-items-center justify-content-between mb-4">
    <h1 class="mb-0">👤 Mein Benutzerkonto</h1>
    <div class="d-flex gap-2">
      <a href="account_edit.php" class="btn btn-primary">✏️ Bearbeiten</a>
      <a href="passwort_aendern.php" class="btn btn-outline-secondary">🔒 Passwort ändern</a>
    </div>
  </div>

  <?= $meldung ?>

  <?php if ($user): ?>
    <div class="row g-4">
      <!-- Profilkarte -->
      <div class="col-12 col-lg-4">
        <div class="profile-card p-4 text-center">
          <div class="d-flex justify-content-center mb-3">
            <div class="avatar-wrap">
              <img
                src="<?= $avatarUrl ?: $defaultAvatar ?>"
                alt="Profilbild"
                onerror="this.src='<?= $defaultAvatar ?>'">
            </div>
          </div>
          <div class="fw-semibold fs-5">
            <?= htmlspecialchars(($user['vorname'] ?? '').' '.($user['nachname'] ?? '')) ?>
          </div>
          <div class="text-muted mb-3"><?= htmlspecialchars($user['username'] ?? '') ?></div>

          <form method="post" enctype="multipart/form-data" class="mt-2">
            <input type="hidden" name="upload_avatar" value="1">
            <div class="mb-2 text-start">
              <label class="form-label">Profilbild (JPG/PNG/WEBP, max. 3 MB)</label>
              <input type="file" name="avatar" accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp" class="form-control" required>
            </div>
            <button class="btn btn-dark w-100">📤 Hochladen / Aktualisieren</button>
          </form>

          <?php if (!empty($user['profilbild'])): ?>
            <form method="post" class="mt-2" onsubmit="return confirm('Profilbild entfernen?');">
              <input type="hidden" name="upload_avatar" value="1">
              <!-- Trick: leeres File erzwingen nicht möglich, daher löschen wir per Flag via GET?
                   Hier einfache Variante: Dateiname in DB leeren -->
              <button formaction="remove_avatar.php" class="btn btn-outline-danger w-100" type="submit">🗑️ Bild entfernen</button>
            </form>
          <?php endif; ?>
        </div>
      </div>

      <!-- Stammdaten -->
      <div class="col-12 col-lg-8">
        <div class="profile-card p-4">
          <div class="row g-3">
            <div class="col-12 col-md-6">
              <div class="kv">
                <div class="k">Benutzername</div>
                <div class="v"><?= htmlspecialchars($user['username']) ?></div>
              </div>
            </div>
            <div class="col-12 col-md-6">
              <div class="kv">
                <div class="k">E-Mail</div>
                <div class="v"><?= htmlspecialchars($user['email']) ?></div>
              </div>
            </div>

            <div class="col-12 col-md-6">
              <div class="kv">
                <div class="k">Vorname</div>
                <div class="v"><?= htmlspecialchars($user['vorname']) ?></div>
              </div>
            </div>
            <div class="col-12 col-md-6">
              <div class="kv">
                <div class="k">Nachname</div>
                <div class="v"><?= htmlspecialchars($user['nachname']) ?></div>
              </div>
            </div>

            <div class="col-12 col-md-6">
              <div class="kv">
                <div class="k">Einheit</div>
                <div class="v"><?= htmlspecialchars($user['einheit']) ?></div>
              </div>
            </div>
            <div class="col-12 col-md-6">
              <div class="kv">
                <div class="k">Gemeinde-ID</div>
                <div class="v"><?= htmlspecialchars($user['gemeinde_id']) ?></div>
              </div>
            </div>

            <div class="col-12 col-md-6">
              <div class="kv">
                <div class="k">Rolle</div>
                <div class="v"><?= htmlspecialchars($user['rolle']) ?></div>
              </div>
            </div>
          </div>

          <div class="alert alert-info mt-4 mb-0">
            Tipp: Weitere persönliche Angaben kannst du über <strong>„✏️ Bearbeiten“</strong> pflegen.
          </div>
        </div>
      </div>
    </div>
  <?php else: ?>
    <div class="alert alert-danger mt-4">Benutzer nicht gefunden.</div>
  <?php endif; ?>
</div>

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