<?php
// views/profile.php - Profile management for club members
require_once __DIR__ . '/../auth.php';

$user = current_user();
$errors = [];
$success_msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $password_confirm = $_POST['password_confirm'] ?? '';

    // Basic Validation
    if (empty($first_name) || empty($last_name) || empty($email)) {
        $errors[] = "Vorname, Nachname und E-Mail dürfen nicht leer sein.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Bitte geben Sie eine gültige E-Mail-Adresse ein.";
    }

    // Check unique email
    if (empty($errors)) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = :email AND id != :id");
        $stmt->execute([':email' => $email, ':id' => $user['id']]);
        if ($stmt->fetchColumn() > 0) {
            $errors[] = "Diese E-Mail-Adresse wird bereits von einem anderen Benutzer verwendet.";
        }
    }

    // Password Update logic
    $update_password = false;
    if (!empty($password)) {
        if ($password !== $password_confirm) {
            $errors[] = "Die neuen Passwörter stimmen nicht überein.";
        } elseif (strlen($password) < 6) {
            $errors[] = "Das neue Passwort muss mindestens 6 Zeichen lang sein.";
        } else {
            $update_password = true;
        }
    }

    // File Upload logic (Profile Photo)
    $photo_updated = false;
    $photo_path = $user['photo_path'];
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
        $file_tmp = $_FILES['photo']['tmp_name'];
        $file_name = $_FILES['photo']['name'];
        $file_size = $_FILES['photo']['size'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        $allowed_exts = ['jpg', 'jpeg', 'png', 'gif'];
        if (!in_array($file_ext, $allowed_exts)) {
            $errors[] = "Ungültiges Bildformat. Erlaubt sind JPG, PNG und GIF.";
        } elseif ($file_size > 2 * 1024 * 1024) { // 2MB max
            $errors[] = "Das Bild darf maximal 2 MB groß sein.";
        } else {
            // Delete old photo if exists
            if (!empty($user['photo_path']) && file_exists(__DIR__ . '/../' . $user['photo_path'])) {
                @unlink(__DIR__ . '/../' . $user['photo_path']);
            }

            // Move to uploads folder
            $new_name = 'user_' . $user['id'] . '_' . time() . '.' . $file_ext;
            $upload_dir = __DIR__ . '/../uploads/';
            
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }

            if (move_uploaded_file($file_tmp, $upload_dir . $new_name)) {
                $photo_path = 'uploads/' . $new_name;
                $photo_updated = true;
            } else {
                $errors[] = "Beim Hochladen des Bildes ist ein Fehler aufgetreten.";
            }
        }
    }

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            // Update basic info
            if ($update_password) {
                $password_hash = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("UPDATE users SET first_name = :first_name, last_name = :last_name, email = :email, password_hash = :password_hash, photo_path = :photo_path WHERE id = :id");
                $stmt->execute([
                    ':first_name' => $first_name,
                    ':last_name' => $last_name,
                    ':email' => $email,
                    ':password_hash' => $password_hash,
                    ':photo_path' => $photo_path,
                    ':id' => $user['id']
                ]);
            } else {
                $stmt = $pdo->prepare("UPDATE users SET first_name = :first_name, last_name = :last_name, email = :email, photo_path = :photo_path WHERE id = :id");
                $stmt->execute([
                    ':first_name' => $first_name,
                    ':last_name' => $last_name,
                    ':email' => $email,
                    ':photo_path' => $photo_path,
                    ':id' => $user['id']
                ]);
            }

            $pdo->commit();
            $success_msg = "Profil erfolgreich aktualisiert!";
            
            // Reload user session data cache
            $_SESSION['user_id'] = $user['id']; 
            
            // Refresh local variable
            $user = current_user();
        } catch (Exception $e) {
            $pdo->rollBack();
            $errors[] = "Fehler beim Speichern der Änderungen: " . $e->getMessage();
        }
    }
}
?>

<div style="max-width: 800px; margin: 0 auto;">
    <h1 style="font-size: 28px; font-weight: 800; color: var(--secondary); margin-bottom: 24px;">Profil verwalten</h1>

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

    <?php if (!empty($success_msg)): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success_msg) ?></div>
    <?php endif; ?>

    <div class="grid" style="grid-template-columns: 240px 1fr; gap: 30px;">
        <!-- Left Column: Avatar display and upload -->
        <div class="card" style="text-align: center; height: fit-content;">
            <h3 class="card-title" style="text-align: left; margin-bottom: 20px;">Profilbild</h3>
            <form method="POST" enctype="multipart/form-data" action="">
                <!-- Pass dummy fields for validation fallback -->
                <input type="hidden" name="first_name" value="<?= htmlspecialchars($user['first_name']) ?>">
                <input type="hidden" name="last_name" value="<?= htmlspecialchars($user['last_name']) ?>">
                <input type="hidden" name="email" value="<?= htmlspecialchars($user['email']) ?>">
                
                <div style="margin-bottom: 20px;">
                    <?php if (!empty($user['photo_path']) && file_exists(__DIR__ . '/../' . $user['photo_path'])): ?>
                        <img src="<?= htmlspecialchars($user['photo_path']) ?>" style="width: 150px; height: 150px; border-radius: 50%; object-fit: cover; border: 4px solid var(--primary); margin: 0 auto 15px;" alt="Avatar">
                    <?php else: ?>
                        <div style="width: 150px; height: 150px; border-radius: 50%; background-color: var(--primary); color: white; display: flex; align-items: center; justify-content: center; font-size: 48px; font-weight: bold; margin: 0 auto 15px;">
                            <?= strtoupper(substr($user['first_name'], 0, 1) . substr($user['last_name'], 0, 1)) ?>
                        </div>
                    <?php endif; ?>
                </div>

                <div style="position: relative; overflow: hidden; display: inline-block; width: 100%;">
                    <label class="btn btn-secondary btn-sm" style="display: block; cursor: pointer; text-align: center;">
                        Foto auswählen
                        <input type="file" name="photo" style="display: none;" onchange="this.form.submit()">
                    </label>
                </div>
                <p style="font-size: 11px; color: var(--text-muted); margin-top: 8px;">Erlaubt: JPG, PNG, GIF (max. 2MB)</p>
            </form>
        </div>

        <!-- Right Column: Personal information and password -->
        <div class="card">
            <h3 class="card-title">Persönliche Angaben</h3>
            <form method="POST" action="" style="margin-top: 15px;">
                <div class="grid" style="grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 0;">
                    <div class="form-group">
                        <label for="first_name">Vorname</label>
                        <input type="text" id="first_name" name="first_name" value="<?= htmlspecialchars($user['first_name']) ?>" required>
                    </div>
                    <div class="form-group">
                        <label for="last_name">Nachname</label>
                        <input type="text" id="last_name" name="last_name" value="<?= htmlspecialchars($user['last_name']) ?>" required>
                    </div>
                </div>

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

                <h3 class="card-title" style="margin-top: 30px; border-top: 1px solid var(--border-color); padding-top: 20px;">Passwort ändern</h3>
                <p style="font-size: 12px; color: var(--text-muted); margin-bottom: 15px;">Lassen Sie diese Felder leer, wenn Sie Ihr Passwort nicht ändern möchten.</p>

                <div class="grid" style="grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 0;">
                    <div class="form-group">
                        <label for="password">Neues Passwort</label>
                        <input type="password" id="password" name="password" placeholder="Mind. 6 Zeichen">
                    </div>
                    <div class="form-group">
                        <label for="password_confirm">Neues Passwort bestätigen</label>
                        <input type="password" id="password_confirm" name="password_confirm" placeholder="Passwort wiederholen">
                    </div>
                </div>

                <button type="submit" class="btn btn-primary" style="margin-top: 20px; width: 100%;">Änderungen speichern</button>
            </form>
        </div>
    </div>
</div>
