<?php
// account.php – Mein Benutzerkonto (Modern UI)
ob_start();
session_start();

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/nav.php';

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

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

// --- Helper für Alerts ---
function get_alert(string $type, string $message): string {
    $icon = ($type === 'success') ? '✅' : (($type === 'danger') ? '❌' : '⚠️');
    $color = ($type === 'success') ? 'success' : (($type === 'danger') ? 'danger' : 'warning');
    return "<div class='alert alert-{$color} alert-dismissible fade show shadow-sm' role='alert'>{$icon} {$message}<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
}

// --- 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 = get_alert('danger', 'Ungültiges Dateiformat. Erlaubt: JPG, PNG, WEBP.');
        } elseif ($_FILES['avatar']['size'] > 3 * 1024 * 1024) { // 3 MB
            $meldung = get_alert('danger', 'Datei ist zu groß (max. 3 MB).');
        } 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)) {
                @chmod($targetAbs, 0644);

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

// --- Profilbild entfernen (DB-Eintrag leeren) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remove_avatar'])) {
    // 1. DB-Eintrag leeren
    $stmtUp = $conn->prepare("UPDATE users SET profilbild = NULL WHERE id = ?");
    $stmtUp->bind_param("i", $user_id);
    $success_db = $stmtUp->execute();
    $stmtUp->close();

    if ($success_db) {
        // 2. Physische Dateien löschen
        $uploadDir = __DIR__ . '/uploads/profile/';
        foreach (glob($uploadDir . 'avatar_'.$user_id.'.*') as $old) {
            @unlink($old);
        }
        $meldung = get_alert('success', 'Profilbild erfolgreich entfernt.');
    } else {
        $meldung = get_alert('danger', 'Fehler beim Entfernen des Bildes aus der Datenbank.');
    }
}

// --- Userdaten laden (nach Aktionen) ---
$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 = !empty($user['profilbild']) ? htmlspecialchars($user['profilbild']) : '';

// 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;
  }
  /* Verbessertes KV-Layout */
  .kv{ background:#f8f9fa; border:1px solid #eef0f2; border-radius:.75rem; padding:.75rem 1rem; height: 100%; }
  .kv .k{color:#6c757d; font-size:.85rem; text-transform:uppercase; font-weight: 500;}
  .kv .v{font-weight:700; color:#1e293b; font-size: 1.1rem; line-height: 1.3;}
</style>

<div class="container mt-5">
  <div class="d-flex flex-wrap align-items-center justify-content-between mb-4 gap-3">
    <h1 class="mb-0 fw-bold fs-3">
        <i class="bi bi-person-circle text-primary me-2"></i>
        Mein Benutzerkonto
    </h1>
    <div class="d-flex gap-2">

      <a href="passwort_aendern.php" class="btn btn-outline-secondary shadow-sm">
        <i class="bi bi-lock me-1"></i> Passwort ändern
      </a>
    </div>
  </div>

  <?= $meldung ?>

  <?php if ($user): ?>
    <div class="row g-4">
      <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-bold fs-5 text-dark">
            <?= 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-4 border-top pt-3">
            <input type="hidden" name="upload_avatar" value="1">
            <div class="mb-2 text-start">
              <label class="form-label small fw-bold">Neues 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 shadow-sm mt-2">
                <i class="bi bi-cloud-arrow-up-fill me-1"></i> Hochladen
            </button>
          </form>

          <?php if (!empty($user['profilbild'])): ?>
            <form method="post" class="mt-2" onsubmit="return confirm('Profilbild wirklich entfernen?');">
              <input type="hidden" name="remove_avatar" value="1">
              <button class="btn btn-outline-danger w-100" type="submit">
                  <i class="bi bi-trash me-1"></i> Bild entfernen
              </button>
            </form>
          <?php endif; ?>
        </div>
      </div>

      <div class="col-12 col-lg-8">
        <div class="profile-card p-4">
          <h4 class="fw-bold text-primary mb-3 pb-2 border-bottom">Persönliche Angaben & Rolle</h4>
          <div class="row g-3">

            <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">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">Benutzername (Login)</div>
                <div class="v"><?= htmlspecialchars($user['username']) ?></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 / Berechtigung</div>
                <div class="v"><?= htmlspecialchars($user['rolle']) ?></div>
              </div>
            </div>
             <div class="col-12 col-md-6">
              <div class="kv">
                <div class="k">Status</div>
                <div class="v"><span class="badge bg-success-subtle text-success border border-success-subtle">Aktiv</span></div>
              </div>
            </div>
          </div>

          <div class="alert alert-info mt-4 mb-0">
            <i class="bi bi-info-circle me-1"></i> Hinweis: Zur Änderung des Benutzernamens oder der Einheit muss der Administrator kontaktiert werden.
          </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'; ob_end_flush(); ?>
