<?php
session_start();
require_once 'config.php';

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

$userId = $_SESSION['user']['id'];
$message = '';

// ✅ Mise à jour de la bio et/ou de la photo
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $bio = trim($_POST['bio'] ?? '');
    $profilePictureUrl = $_SESSION['user']['profile_picture'] ?? null;

    global $s3Client, $bucketName;

    // 📸 Upload d'une nouvelle image
    if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] === UPLOAD_ERR_OK) {
        $fileName = 'profile_' . $userId . '_' . time() . '_' . basename($_FILES['profile_picture']['name']);
        $tmpPath = $_FILES['profile_picture']['tmp_name'];

        try {
            $s3Client->putObject([
                'Bucket' => $bucketName,
                'Key' => $fileName,
                'SourceFile' => $tmpPath,
                'ACL' => 'public-read'
            ]);
            $profilePictureUrl = "http://localhost:9000/$bucketName/$fileName";
        } catch (Exception $e) {
            $message = "❌ Erreur upload MinIO : " . $e->getMessage();
        }
    }

    // 🧹 Suppression de la photo
    if (isset($_POST['delete_picture'])) {
        $profilePictureUrl = null;
    }

    try {
        $stmt = $pdo->prepare("UPDATE utilisateurs SET bio = ?, profile_picture = ? WHERE id = ?");
        $stmt->execute([$bio, $profilePictureUrl, $userId]);

        $_SESSION['user']['bio'] = $bio;
        $_SESSION['user']['profile_picture'] = $profilePictureUrl;

        $message = "✅ Profil mis à jour avec succès !";
    } catch (PDOException $e) {
        $message = "❌ Erreur base de données : " . $e->getMessage();
    }
}

// ✅ Récupération des infos utilisateur
$stmt = $pdo->prepare("SELECT username, role, bio, profile_picture FROM utilisateurs WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();

// ✅ Détermine la redirection correcte
if ($user['role'] === 'admin') {
    $redirectPage = "dashboard.php"; // Admin → tableau de bord admin
} else {
    $redirectPage = "index.php"; // Utilisateur → accueil public
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Profil de <?= htmlspecialchars($user['username']) ?></title>
<style>
body {
    font-family: 'Poppins', sans-serif;
    background: linear-gradient(120deg, #fff4f7, #ffe6ea);
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.container {
    background: white;
    padding: 30px;
    border-radius: 15px;
    box-shadow: 0 6px 18px rgba(255, 100, 150, 0.2);
    text-align: center;
    width: 400px;
}

h2 {
    color: #ff69b4;
    margin-bottom: 15px;
}

.profile-picture {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid #ff69b4;
    margin-bottom: 10px;
}

form {
    display: flex;
    flex-direction: column;
    gap: 10px;
    margin-top: 15px;
}

textarea {
    padding: 10px;
    border-radius: 8px;
    border: 1px solid #ddd;
    resize: vertical;
    font-family: 'Poppins', sans-serif;
}

button {
    background: linear-gradient(45deg, #ff69b4, #ffa07a);
    border: none;
    color: white;
    padding: 10px;
    border-radius: 20px;
    cursor: pointer;
    font-weight: 600;
    transition: 0.3s;
}

button:hover {
    opacity: 0.9;
}

.actions {
    display: flex;
    justify-content: center;
    gap: 10px;
}

.message {
    margin: 10px 0;
    color: #ff69b4;
    font-weight: bold;
}

a {
    color: #ff69b4;
    text-decoration: none;
}

a:hover {
    text-decoration: underline;
}
</style>
</head>
<body>
<div class="container">
    <h2>Profil de <?= htmlspecialchars($user['username']) ?></h2>

    <?php if (!empty($user['profile_picture'])): ?>
        <img src="<?= htmlspecialchars($user['profile_picture']) ?>" class="profile-picture" alt="Photo de profil">
    <?php else: ?>
        <div style="font-size:60px;">👤</div>
    <?php endif; ?>

    <p><strong>Rôle :</strong> <?= htmlspecialchars($user['role']) ?></p>

    <form method="POST" enctype="multipart/form-data">
        <label for="bio">Votre bio :</label>
        <textarea name="bio" id="bio" rows="4"><?= htmlspecialchars($user['bio'] ?? '') ?></textarea>

        <label for="profile_picture">Changer la photo :</label>
        <input type="file" name="profile_picture" id="profile_picture" accept="image/png, image/jpeg">

        <div class="actions">
            <button type="submit" name="update_profile">Mettre à jour</button>
            <button type="submit" name="delete_picture" style="background:#ddd;color:#333;">Supprimer la photo</button>
        </div>
    </form>

    <?php if ($message): ?>
        <div class="message"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <p style="margin-top:20px;">
        <a href="<?= $redirectPage ?>">⬅ Retour au tableau de bord</a>
    </p>
</div>
</body>
</html>
