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

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

$db = db();
$user_id = $_SESSION['user_id'];
$error = '';
$success = '';

// Fetch current user data + join for stats
$stmt = $db->prepare("
    SELECT u.*, l.level_name, g.grade_name 
    FROM users u 
    LEFT JOIN levels l ON u.level_id = l.id 
    LEFT JOIN grades g ON u.level_id = g.level_id 
    WHERE u.id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update_profile') {
        $email = trim($_POST['email'] ?? '');
        $current_password = $_POST['current_password'] ?? '';
        $new_password = $_POST['new_password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';

        if (empty($email)) {
            $error = 'L\'email ne peut pas être vide.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Email invalide.';
        } elseif (!password_verify($current_password, $user['password'])) {
            $error = 'Mot de passe actuel incorrect.';
        } else {
            $sql = "UPDATE users SET email = ?";
            $params = [$email];

            if (!empty($new_password)) {
                if ($new_password !== $confirm_password) {
                    $error = 'Les nouveaux mots de passe ne correspondent pas.';
                } else {
                    $sql .= ", password = ?";
                    $params[] = password_hash($new_password, PASSWORD_DEFAULT);
                }
            }
            $sql .= " WHERE id = ?";
            $params[] = $user_id;

            $stmt = $db->prepare($sql);
            $stmt->execute($params);
            $success = 'Profil mis à jour avec succès.';
            
            $stmt = $db->prepare("SELECT u.*, l.level_name, g.grade_name FROM users u LEFT JOIN levels l ON u.level_id = l.id LEFT JOIN grades g ON u.level_id = g.level_id WHERE u.id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();
        }
    } elseif ($action === 'update_display_name') {
        $display_name = trim($_POST['display_name'] ?? '');
        if (!empty($display_name)) {
            $stmt = $db->prepare("UPDATE users SET display_name = ? WHERE id = ?");
            $stmt->execute([$display_name, $user_id]);
            $_SESSION["display_name"] = $display_name; $success = "Nom affiché mis à jour avec succès.";;
            
            $stmt = $db->prepare("SELECT u.*, l.level_name, g.grade_name FROM users u LEFT JOIN levels l ON u.level_id = l.id LEFT JOIN grades g ON u.level_id = g.level_id WHERE u.id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();
        } else {
            $error = 'Le nom affiché ne peut pas être vide.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mon Profil - Nexus</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #000; margin: 0; padding: 20px; font-family: Arial, sans-serif; color: #fff; background-image: radial-gradient(circle at 50% 50%, #1a2a4a 0%, #000 70%); min-height: 100vh; }
        .profile-container { background: rgba(10, 15, 30, 0.95); border: 1px solid #4c566a; padding: 30px; width: 100%; max-width: 600px; margin: 0 auto; box-shadow: 0 0 20px rgba(0,0,0,0.8); }
        h2 { text-transform: uppercase; color: #88c0d0; border-bottom: 1px solid #4c566a; padding-bottom: 10px; display: flex; align-items: center; gap: 10px; }
        .tabs { display: flex; gap: 10px; margin-bottom: 20px; border-bottom: 1px solid #4c566a; padding-bottom: 10px; }
        .tab-btn { background: none; border: none; color: #8c92a3; cursor: pointer; padding: 10px 15px; text-transform: uppercase; font-weight: bold; }
        .tab-btn.active { color: #88c0d0; border-bottom: 2px solid #88c0d0; }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        .form-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 5px; color: #8c92a3; font-size: 14px; }
        input { width: 100%; padding: 10px; background: #000; border: 1px solid #4c566a; color: #fff; box-sizing: border-box; }
        .inline-form { display: flex; gap: 10px; align-items: end; }
        .inline-form input { flex-grow: 1; }
        .inline-form button { width: auto; padding: 10px 20px; }
        button { width: 100%; padding: 12px; background: #5e81ac; border: none; color: #fff; font-weight: bold; cursor: pointer; text-transform: uppercase; transition: background 0.2s; }
        button:hover { background: #81a1c1; }
        .stat-card { padding: 15px; background: rgba(0,0,0,0.3); border: 1px solid #2d3545; margin-bottom: 10px; }
        .alert { padding: 10px; margin-bottom: 20px; font-size: 14px; }
        .alert-error { background: rgba(191, 97, 106, 0.2); border: 1px solid #bf616a; color: #bf616a; }
        .alert-success { background: rgba(163, 190, 140, 0.2); border: 1px solid #a3be8c; color: #a3be8c; }
        .nav-links { display: flex; justify-content: space-between; margin-top: 25px; border-top: 1px solid #2d3545; padding-top: 15px; font-size: 13px; }
        .nav-links a { color: #88c0d0; text-decoration: none; }
    </style>
</head>
<body>
    <div class="profile-container">
        <div class="tabs">
            <button class="tab-btn active" onclick="openTab('overview')">Vue d\'ensemble</button>
            <button class="tab-btn" onclick="openTab('account')">Gestion du compte</button>
        </div>

        <?php if ($error): ?><div class="alert alert-error"><?php echo $error; ?></div><?php endif; ?>
        <?php if ($success): ?><div class="alert alert-success"><?php echo $success; ?></div><?php endif; ?>

        <div id="overview" class="tab-content active">
            <h2><i class="fa-solid fa-chart-line"></i> Vue d\'ensemble</h2>
            <div class="stat-card"><strong>Pseudo de compte:</strong> @<?php echo htmlspecialchars($user['username']); ?></div>
            
            <form method="POST" class="form-group">
                <input type="hidden" name="action" value="update_display_name">
                <label>Nom affiché (Jeu)</label>
                <div class="inline-form">
                    <input type="text" name="display_name" value="<?php echo htmlspecialchars($user['display_name']); ?>">
                    <button type="submit">Sauvegarder</button>
                </div>
            </form>

            <div class="stat-card"><strong>Niveau:</strong> <?php echo htmlspecialchars($user['level_name'] ?? 'N/A'); ?></div>
            <div class="stat-card"><strong>Grade:</strong> <?php echo htmlspecialchars($user['grade_name'] ?? 'N/A'); ?></div>
        </div>

        <div id="account" class="tab-content">
            <h2><i class="fa-solid fa-user-gear"></i> Gestion du Compte</h2>
            <form method="POST">
                <input type="hidden" name="action" value="update_profile">
                <div class="form-group">
                    <label>Adresse Email</label>
                    <input type="email" name="email" required value="<?php echo htmlspecialchars($user['email']); ?>">
                </div>
                <div class="form-group">
                    <label>Nouveau mot de passe</label>
                    <input type="password" name="new_password" placeholder="Laisser vide pour ne pas changer">
                </div>
                <div class="form-group">
                    <label>Confirmer le nouveau mot de passe</label>
                    <input type="password" name="confirm_password">
                </div>
                <div class="form-group">
                    <label>Mot de passe actuel (requis pour valider)</label>
                    <input type="password" name="current_password" required>
                </div>
                <button type="submit">Enregistrer les modifications</button>
            </form>
        </div>

        <div class="nav-links">
            <a href="index.php"><i class="fa-solid fa-arrow-left"></i> Retour au Nexus</a>
            <a href="auth.php?logout=1" style="color: #bf616a;"><i class="fa-solid fa-right-from-bracket"></i> Déconnexion</a>
        </div>
    </div>
    <script>
        function openTab(id) {
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
            document.getElementById(id).classList.add('active');
            event.currentTarget.classList.add('active');
        }
    </script>
</body>
</html>
