#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from flask import Flask, render_template_string, request, redirect, url_for, session, jsonify
import sqlite3
import hashlib
import os
from datetime import datetime

app = Flask(__name__)
app.secret_key = os.urandom(24)

# --- Configuration ---
DB_NAME = "nexapy_chat.db"
HOST = "0.0.0.0"
PORT = 4000

# --- Initialisation de la base de données ---
def init_db():
    conn = sqlite3.connect(DB_NAME)
    cursor = conn.cursor()
    
    # Table des utilisateurs
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS users (
            user_id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT UNIQUE NOT NULL,
            password TEXT NOT NULL,
            email TEXT UNIQUE,
            bio TEXT DEFAULT '',
            profile_pic TEXT DEFAULT '/static/default_profile.png',
            is_admin BOOLEAN DEFAULT FALSE,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )
    ''')
    
    # Table des amitiés
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS friendships (
            friendship_id INTEGER PRIMARY KEY AUTOINCREMENT,
            user1_id INTEGER NOT NULL,
            user2_id INTEGER NOT NULL,
            status TEXT DEFAULT 'pending',
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (user1_id) REFERENCES users(user_id),
            FOREIGN KEY (user2_id) REFERENCES users(user_id),
            UNIQUE(user1_id, user2_id)
        )
    ''')
    
    # Table des likes de profil
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS profile_likes (
            like_id INTEGER PRIMARY KEY AUTOINCREMENT,
            liker_id INTEGER NOT NULL,
            liked_id INTEGER NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (liker_id) REFERENCES users(user_id),
            FOREIGN KEY (liked_id) REFERENCES users(user_id),
            UNIQUE(liker_id, liked_id)
        )
    ''')
    
    # Table des conversations privées
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS conversations (
            conversation_id INTEGER PRIMARY KEY AUTOINCREMENT,
            user1_id INTEGER NOT NULL,
            user2_id INTEGER NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (user1_id) REFERENCES users(user_id),
            FOREIGN KEY (user2_id) REFERENCES users(user_id),
            UNIQUE(user1_id, user2_id)
        )
    ''')
    
    # Table des messages
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS messages (
            message_id INTEGER PRIMARY KEY AUTOINCREMENT,
            conversation_id INTEGER,
            group_id INTEGER,
            sender_id INTEGER NOT NULL,
            content TEXT NOT NULL,
            timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
            is_read BOOLEAN DEFAULT FALSE,
            FOREIGN KEY (conversation_id) REFERENCES conversations(conversation_id),
            FOREIGN KEY (group_id) REFERENCES groups(group_id),
            FOREIGN KEY (sender_id) REFERENCES users(user_id)
        )
    ''')
    
    # Table des groupes
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS groups (
            group_id INTEGER PRIMARY KEY AUTOINCREMENT,
            group_name TEXT NOT NULL,
            access_code TEXT UNIQUE NOT NULL,
            created_by INTEGER NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (created_by) REFERENCES users(user_id)
        )
    ''')
    
    # Table des membres de groupes
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS group_members (
            group_id INTEGER NOT NULL,
            user_id INTEGER NOT NULL,
            PRIMARY KEY (group_id, user_id),
            FOREIGN KEY (group_id) REFERENCES groups(group_id),
            FOREIGN KEY (user_id) REFERENCES users(user_id)
        )
    ''')
    
    conn.commit()
    conn.close()


# --- Fonctions utilitaires ---
def hash_password(password):
    return hashlib.sha256(password.encode()).hexdigest()


def get_db_connection():
    conn = sqlite3.connect(DB_NAME)
    conn.row_factory = sqlite3.Row
    return conn


# --- Routes ---
@app.route("/")
def index():
    if "user_id" in session:
        return redirect(url_for("dashboard"))
    return redirect(url_for("login"))


@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", 
                       (username, hash_password(password)))
        user = cursor.fetchone()
        conn.close()
        
        if user:
            session["user_id"] = user["user_id"]
            session["username"] = user["username"]
            session["is_admin"] = bool(user["is_admin"])
            session["profile_pic"] = user["profile_pic"]
            return redirect(url_for("dashboard"))
        else:
            return render_template_string("""
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Connexion - NexaPy</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-primary: #0a0a0a;
            --bg-secondary: #121212;
            --bg-tertiary: #1e1e1e;
            --text-primary: #ffffff;
            --text-secondary: #a0a0a0;
            --text-tertiary: #707070;
            --accent: #00bcd4;
            --accent-hover: #0097a7;
            --error: #ff5252;
            --border: #2a2a2a;
            --shadow: rgba(0, 0, 0, 0.5);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, var(--bg-primary) 0%, var(--bg-secondary) 100%);
            color: var(--text-primary);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .container {
            background-color: var(--bg-secondary);
            border-radius: 16px;
            padding: 2.5rem;
            width: 100%;
            max-width: 420px;
            box-shadow: 0 20px 60px var(--shadow);
            border: 1px solid var(--border);
        }
        
        .logo {
            text-align: center;
            margin-bottom: 2rem;
        }
        
        .logo h1 {
            font-size: 2rem;
            font-weight: 700;
            background: linear-gradient(135deg, var(--accent), var(--accent-hover));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .logo p {
            color: var(--text-secondary);
            font-size: 0.9rem;
            margin-top: 0.5rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: var(--text-secondary);
            font-size: 0.9rem;
            font-weight: 500;
        }
        
        .form-group input {
            width: 100%;
            padding: 0.9rem 1.2rem;
            background-color: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: 10px;
            color: var(--text-primary);
            font-size: 1rem;
            transition: all 0.3s;
        }
        
        .form-group input:focus {
            outline: none;
            border-color: var(--accent);
            box-shadow: 0 0 0 3px rgba(0, 188, 212, 0.1);
        }
        
        .form-group input::placeholder {
            color: var(--text-tertiary);
        }
        
        .btn {
            width: 100%;
            padding: 0.9rem;
            background: linear-gradient(135deg, var(--accent), var(--accent-hover));
            color: var(--bg-primary);
            border: none;
            border-radius: 10px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0, 188, 212, 0.2);
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 188, 212, 0.3);
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .error-message {
            color: var(--error);
            text-align: center;
            margin-bottom: 1rem;
            font-size: 0.9rem;
        }
        
        .link {
            text-align: center;
            margin-top: 1.5rem;
            color: var(--text-secondary);
            font-size: 0.9rem;
        }
        
        .link a {
            color: var(--accent);
            text-decoration: none;
            font-weight: 500;
        }
        
        .link a:hover {
            text-decoration: underline;
        }
        
        .divider {
            display: flex;
            align-items: center;
            margin: 1.5rem 0;
            color: var(--text-tertiary);
            font-size: 0.85rem;
        }
        
        .divider::before, .divider::after {
            content: "";
            flex: 1;
            border-bottom: 1px solid var(--border);
        }
        
        .divider span {
            padding: 0 1rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="logo">
            <h1>NexaPy</h1>
            <p>Connectez-vous à votre compte</p>
        </div>
        
        <p class="error-message">Nom d'utilisateur ou mot de passe incorrect.</p>
        
        <form method="POST">
            <div class="form-group">
                <label for="username">Nom d'utilisateur</label>
                <input type="text" id="username" name="username" placeholder="Entrez votre nom d'utilisateur" required>
            </div>
            <div class="form-group">
                <label for="password">Mot de passe</label>
                <input type="password" id="password" name="password" placeholder="Entrez votre mot de passe" required>
            </div>
            <button type="submit" class="btn">Se connecter</button>
        </form>
        
        <div class="divider">
            <span>ou</span>
        </div>
        
        <div class="link">
            <p>Pas de compte ? <a href="{{ url_for('register') }}">S'inscrire</a></p>
        </div>
    </div>
</body>
</html>
            """)
    
    return render_template_string("""
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Connexion - NexaPy</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-primary: #0a0a0a;
            --bg-secondary: #121212;
            --bg-tertiary: #1e1e1e;
            --text-primary: #ffffff;
            --text-secondary: #a0a0a0;
            --text-tertiary: #707070;
            --accent: #00bcd4;
            --accent-hover: #0097a7;
            --border: #2a2a2a;
            --shadow: rgba(0, 0, 0, 0.5);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, var(--bg-primary) 0%, var(--bg-secondary) 100%);
            color: var(--text-primary);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .container {
            background-color: var(--bg-secondary);
            border-radius: 16px;
            padding: 2.5rem;
            width: 100%;
            max-width: 420px;
            box-shadow: 0 20px 60px var(--shadow);
            border: 1px solid var(--border);
        }
        
        .logo {
            text-align: center;
            margin-bottom: 2rem;
        }
        
        .logo h1 {
            font-size: 2rem;
            font-weight: 700;
            background: linear-gradient(135deg, var(--accent), var(--accent-hover));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .logo p {
            color: var(--text-secondary);
            font-size: 0.9rem;
            margin-top: 0.5rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: var(--text-secondary);
            font-size: 0.9rem;
            font-weight: 500;
        }
        
        .form-group input {
            width: 100%;
            padding: 0.9rem 1.2rem;
            background-color: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: 10px;
            color: var(--text-primary);
            font-size: 1rem;
            transition: all 0.3s;
        }
        
        .form-group input:focus {
            outline: none;
            border-color: var(--accent);
            box-shadow: 0 0 0 3px rgba(0, 188, 212, 0.1);
        }
        
        .form-group input::placeholder {
            color: var(--text-tertiary);
        }
        
        .btn {
            width: 100%;
            padding: 0.9rem;
            background: linear-gradient(135deg, var(--accent), var(--accent-hover));
            color: var(--bg-primary);
            border: none;
            border-radius: 10px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0, 188, 212, 0.2);
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 188, 212, 0.3);
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .link {
            text-align: center;
            margin-top: 1.5rem;
            color: var(--text-secondary);
            font-size: 0.9rem;
        }
        
        .link a {
            color: var(--accent);
            text-decoration: none;
            font-weight: 500;
        }
        
        .link a:hover {
            text-decoration: underline;
        }
        
        .divider {
            display: flex;
            align-items: center;
            margin: 1.5rem 0;
            color: var(--text-tertiary);
            font-size: 0.85rem;
        }
        
        .divider::before, .divider::after {
            content: "";
            flex: 1;
            border-bottom: 1px solid var(--border);
        }
        
        .divider span {
            padding: 0 1rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="logo">
            <h1>NexaPy</h1>
            <p>Connectez-vous à votre compte</p>
        </div>
        
        <form method="POST">
            <div class="form-group">
                <label for="username">Nom d'utilisateur</label>
                <input type="text" id="username" name="username" placeholder="Entrez votre nom d'utilisateur" required>
            </div>
            <div class="form-group">
                <label for="password">Mot de passe</label>
                <input type="password" id="password" name="password" placeholder="Entrez votre mot de passe" required>
            </div>
            <button type="submit" class="btn">Se connecter</button>
        </form>
        
        <div class="divider">
            <span>ou</span>
        </div>
        
        <div class="link">
            <p>Pas de compte ? <a href="{{ url_for('register') }}">S'inscrire</a></p>
        </div>
    </div>
</body>
</html>
    """)


@app.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        email = request.form.get("email", "")
        bio = request.form.get("bio", "")
        
        conn = get_db_connection()
        cursor = conn.cursor()
        
        try:
            cursor.execute(
                "INSERT INTO users (username, password, email, bio) VALUES (?, ?, ?, ?)", 
                (username, hash_password(password), email, bio)
            )
            conn.commit()
            return redirect(url_for("login"))
        except sqlite3.IntegrityError as e:
            error = "Nom d'utilisateur déjà utilisé."
            if "email" in str(e):
                error = "Email déjà utilisé."
            conn.close()
            return render_template_string("""
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inscription - NexaPy</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-primary: #0a0a0a;
            --bg-secondary: #121212;
            --bg-tertiary: #1e1e1e;
            --text-primary: #ffffff;
            --text-secondary: #a0a0a0;
            --text-tertiary: #707070;
            --accent: #00bcd4;
            --accent-hover: #0097a7;
            --error: #ff5252;
            --border: #2a2a2a;
            --shadow: rgba(0, 0, 0, 0.5);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, var(--bg-primary) 0%, var(--bg-secondary) 100%);
            color: var(--text-primary);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .container {
            background-color: var(--bg-secondary);
            border-radius: 16px;
            padding: 2.5rem;
            width: 100%;
            max-width: 420px;
            box-shadow: 0 20px 60px var(--shadow);
            border: 1px solid var(--border);
        }
        
        .logo {
            text-align: center;
            margin-bottom: 2rem;
        }
        
        .logo h1 {
            font-size: 2rem;
            font-weight: 700;
            background: linear-gradient(135deg, var(--accent), var(--accent-hover));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .logo p {
            color: var(--text-secondary);
            font-size: 0.9rem;
            margin-top: 0.5rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: var(--text-secondary);
            font-size: 0.9rem;
            font-weight: 500;
        }
        
        .form-group input, .form-group textarea {
            width: 100%;
            padding: 0.9rem 1.2rem;
            background-color: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: 10px;
            color: var(--text-primary);
            font-size: 1rem;
            transition: all 0.3s;
            resize: vertical;
            min-height: 100px;
        }
        
        .form-group input:focus, .form-group textarea:focus {
            outline: none;
            border-color: var(--accent);
            box-shadow: 0 0 0 3px rgba(0, 188, 212, 0.1);
        }
        
        .form-group input::placeholder, .form-group textarea::placeholder {
            color: var(--text-tertiary);
        }
        
        .btn {
            width: 100%;
            padding: 0.9rem;
            background: linear-gradient(135deg, var(--accent), var(--accent-hover));
            color: var(--bg-primary);
            border: none;
            border-radius: 10px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0, 188, 212, 0.2);
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 188, 212, 0.3);
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .error-message {
            color: var(--error);
            text-align: center;
            margin-bottom: 1rem;
            font-size: 0.9rem;
        }
        
        .link {
            text-align: center;
            margin-top: 1.5rem;
            color: var(--text-secondary);
            font-size: 0.9rem;
        }
        
        .link a {
            color: var(--accent);
            text-decoration: none;
            font-weight: 500;
        }
        
        .link a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="logo">
            <h1>NexaPy</h1>
            <p>Créez votre compte</p>
        </div>
        
        <p class="error-message">{{ error }}</p>
        
        <form method="POST">
            <div class="form-group">
                <label for="username">Nom d'utilisateur</label>
                <input type="text" id="username" name="username" placeholder="Choisissez un nom d'utilisateur" required>
            </div>
            <div class="form-group">
                <label for="email">Email (optionnel)</label>
                <input type="email" id="email" name="email" placeholder="votre@email.com">
            </div>
            <div class="form-group">
                <label for="password">Mot de passe</label>
                <input type="password" id="password" name="password" placeholder="Choisissez un mot de passe" required>
            </div>
            <div class="form-group">
                <label for="bio">Bio (optionnel)</label>
                <textarea id="bio" name="bio" placeholder="Présentez-vous en quelques mots..."></textarea>
            </div>
            <button type="submit" class="btn">S'inscrire</button>
        </form>
        
        <div class="link">
            <p>Déjà un compte ? <a href="{{ url_for('login') }}">Se connecter</a></p>
        </div>
    </div>
</body>
</html>
            """, error=error)
        finally:
            conn.close()
    
    return render_template_string("""
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inscription - NexaPy</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-primary: #0a0a0a;
            --bg-secondary: #121212;
            --bg-tertiary: #1e1e1e;
            --text-primary: #ffffff;
            --text-secondary: #a0a0a0;
            --text-tertiary: #707070;
            --accent: #00bcd4;
            --accent-hover: #0097a7;
            --border: #2a2a2a;
            --shadow: rgba(0, 0, 0, 0.5);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, var(--bg-primary) 0%, var(--bg-secondary) 100%);
            color: var(--text-primary);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .container {
            background-color: var(--bg-secondary);
            border-radius: 16px;
            padding: 2.5rem;
            width: 100%;
            max-width: 420px;
            box-shadow: 0 20px 60px var(--shadow);
            border: 1px solid var(--border);
        }
        
        .logo {
            text-align: center;
            margin-bottom: 2rem;
        }
        
        .logo h1 {
            font-size: 2rem;
            font-weight: 700;
            background: linear-gradient(135deg, var(--accent), var(--accent-hover));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .logo p {
            color: var(--text-secondary);
            font-size: 0.9rem;
            margin-top: 0.5rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: var(--text-secondary);
            font-size: 0.9rem;
            font-weight: 500;
        }
        
        .form-group input, .form-group textarea {
            width: 100%;
            padding: 0.9rem 1.2rem;
            background-color: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: 10px;
            color: var(--text-primary);
            font-size: 1rem;
            transition: all 0.3s;
            resize: vertical;
            min-height: 100px;
        }
        
        .form-group input:focus, .form-group textarea:focus {
            outline: none;
            border-color: var(--accent);
            box-shadow: 0 0 0 3px rgba(0, 188, 212, 0.1);
        }
        
        .form-group input::placeholder, .form-group textarea::placeholder {
            color: var(--text-tertiary);
        }
        
        .btn {
            width: 100%;
            padding: 0.9rem;
            background: linear-gradient(135deg, var(--accent), var(--accent-hover));
            color: var(--bg-primary);
            border: none;
            border-radius: 10px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0, 188, 212, 0.2);
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 188, 212, 0.3);
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .link {
            text-align: center;
            margin-top: 1.5rem;
            color: var(--text-secondary);
            font-size: 0.9rem;
        }
        
        .link a {
            color: var(--accent);
            text-decoration: none;
            font-weight: 500;
        }
        
        .link a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="logo">
            <h1>NexaPy</h1>
            <p>Créez votre compte</p>
        </div>
        
        <form method="POST">
            <div class="form-group">
                <label for="username">Nom d'utilisateur</label>
                <input type="text" id="username" name="username" placeholder="Choisissez un nom d'utilisateur" required>
            </div>
            <div class="form-group">
                <label for="email">Email (optionnel)</label>
                <input type="email" id="email" name="email" placeholder="votre@email.com">
            </div>
            <div class="form-group">
                <label for="password">Mot de passe</label>
                <input type="password" id="password" name="password" placeholder="Choisissez un mot de passe" required>
            </div>
            <div class="form-group">
                <label for="bio">Bio (optionnel)</label>
                <textarea id="bio" name="bio" placeholder="Présentez-vous en quelques mots..."></textarea>
            </div>
            <button type="submit" class="btn">S'inscrire</button>
        </form>
        
        <div class="link">
            <p>Déjà un compte ? <a href="{{ url_for('login') }}">Se connecter</a></p>
        </div>
    </div>
</body>
</html>
    """)


@app.route("/dashboard")
def dashboard():
    if "user_id" not in session:
        return redirect(url_for("login"))
    
    conn = get_db_connection()
    cursor = conn.cursor()
    
    # Récupérer les conversations privées
    cursor.execute('''
        SELECT c.conversation_id, u.user_id, u.username, u.profile_pic, u.bio,
               (SELECT content FROM messages WHERE conversation_id = c.conversation_id ORDER BY timestamp DESC LIMIT 1) as last_message,
               (SELECT timestamp FROM messages WHERE conversation_id = c.conversation_id ORDER BY timestamp DESC LIMIT 1) as last_message_time
        FROM conversations c
        JOIN users u ON (u.user_id = c.user1_id OR u.user_id = c.user2_id) AND u.user_id != ?
        WHERE c.user1_id = ? OR c.user2_id = ?
        GROUP BY c.conversation_id
        ORDER BY last_message_time DESC
    ''', (session["user_id"], session["user_id"], session["user_id"]))
    conversations = cursor.fetchall()
    
    # Récupérer les groupes
    cursor.execute('''
        SELECT g.group_id, g.group_name, g.access_code,
               (SELECT content FROM messages WHERE group_id = g.group_id ORDER BY timestamp DESC LIMIT 1) as last_message,
               (SELECT timestamp FROM messages WHERE group_id = g.group_id ORDER BY timestamp DESC LIMIT 1) as last_message_time
        FROM groups g
        JOIN group_members gm ON g.group_id = gm.group_id
        WHERE gm.user_id = ?
        GROUP BY g.group_id
        ORDER BY last_message_time DESC
    ''', (session["user_id"],))
    groups = cursor.fetchall()
    
    # Récupérer les suggestions d'amis
    cursor.execute('''
        SELECT u.user_id, u.username, u.profile_pic, u.bio
        FROM users u
        WHERE u.user_id != ?
        AND u.user_id NOT IN (
            SELECT user2_id FROM friendships WHERE user1_id = ? AND status = 'accepted'
            UNION
            SELECT user1_id FROM friendships WHERE user2_id = ? AND status = 'accepted'
        )
        AND u.user_id NOT IN (
            SELECT user2_id FROM friendships WHERE user1_id = ? AND status = 'pending'
            UNION
            SELECT user1_id FROM friendships WHERE user2_id = ? AND status = 'pending'
        )
        LIMIT 5
    ''', (session["user_id"], session["user_id"], session["user_id"], session["user_id"], session["user_id"]))
    friend_suggestions = cursor.fetchall()
    
    # Récupérer les demandes d'ami en attente
    cursor.execute('''
        SELECT u.user_id, u.username, u.profile_pic, u.bio
        FROM friendships f
        JOIN users u ON f.user1_id = u.user_id
        WHERE f.user2_id = ? AND f.status = 'pending'
    ''', (session["user_id"],))
    pending_requests = cursor.fetchall()
    
    # Récupérer les amis
    cursor.execute('''
        SELECT u.user_id, u.username, u.profile_pic, u.bio
        FROM friendships f
        JOIN users u ON (
            (f.user1_id = ? AND f.user2_id = u.user_id AND f.status = 'accepted')
            OR (f.user2_id = ? AND f.user1_id = u.user_id AND f.status = 'accepted')
        )
    ''', (session["user_id"], session["user_id"]))
    friends = cursor.fetchall()
    
    conn.close()
    
    return render_template_string("""
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tableau de bord - NexaPy</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --bg-primary: #0a0a0a;
            --bg-secondary: #121212;
            --bg-tertiary: #1e1e1e;
            --bg-card: #262626;
            --text-primary: #ffffff;
            --text-secondary: #a0a0a0;
            --text-tertiary: #707070;
            --accent: #00bcd4;
            --accent-hover: #0097a7;
            --error: #ff5252;
            --success: #4caf50;
            --border: #2a2a2a;
            --shadow: rgba(0, 0, 0, 0.5);
            --sidebar-width: 320px;
            --header-height: 70px;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', sans-serif;
        }
        
        body {
            background-color: var(--bg-primary);
            color: var(--text-primary);
            min-height: 100vh;
            display: flex;
        }
        
        .sidebar {
            width: var(--sidebar-width);
            background-color: var(--bg-secondary);
            border-right: 1px solid var(--border);
            height: 100vh;
            position: fixed;
            display: flex;
            flex-direction: column;
            overflow-y: auto;
        }
        
        .sidebar-header {
            padding: 1.5rem;
            border-bottom: 1px solid var(--border);
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .sidebar-header .profile-pic {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: var(--bg-tertiary);
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1.5rem;
            color: var(--text-secondary);
            overflow: hidden;
        }
        
        .sidebar-header .profile-pic img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .sidebar-header .profile-info h3 {
            font-size: 1rem;
            font-weight: 600;
            margin-bottom: 0.2rem;
        }
        
        .sidebar-header .profile-info p {
            font-size: 0.8rem;
            color: var(--text-secondary);
        }
        
        .sidebar-section {
            padding: 1.5rem;
        }
        
        .sidebar-section h3 {
            font-size: 0.85rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: var(--text-secondary);
            margin-bottom: 1rem;
            font-weight: 600;
        }
        
        .search-bar {
            display: flex;
            align-items: center;
            gap: 0.7rem;
            background-color: var(--bg-tertiary);
            border-radius: 10px;
            padding: 0.7rem 1rem;
            margin-bottom: 1rem;
            border: 1px solid var(--border);
        }
        
        .search-bar input {
            flex: 1;
            background: transparent;
            border: none;
            color: var(--text-primary);
            font-size: 0.9rem;
        }
        
        .search-bar input:focus {
            outline: none;
        }
        
        .search-bar i {
            color: var(--text-secondary);
        }
        
        .friend-list, .group-list, .request-list {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }
        
        .friend-item, .group-item, .request-item {
            display: flex;
            align-items: center;
            gap: 0.8rem;
            padding: 0.8rem 1rem;
            border-radius: 10px;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .friend-item:hover, .group-item:hover, .request-item:hover {
            background-color: var(--bg-tertiary);
        }
        
        .friend-item .profile-pic, .request-item .profile-pic {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--bg-card);
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1rem;
            color: var(--text-secondary);
            overflow: hidden;
        }
        
        .friend-item .profile-pic img, .request-item .profile-pic img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .group-item .group-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--accent);
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1rem;
        }
        
        .friend-info, .group-info, .request-info {
            flex: 1;
            min-width: 0;
        }
        
        .friend-info h4, .group-info h4, .request-info h4 {
            font-size: 0.95rem;
            font-weight: 600;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .friend-info p, .group-info p, .request-info p {
            font-size: 0.8rem;
            color: var(--text-secondary);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .friend-actions, .request-actions {
            display: flex;
            gap: 0.5rem;
        }
        
        .friend-actions button, .request-actions button {
            background: transparent;
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            padding: 0.4rem;
            border-radius: 50%;
            transition: all 0.2s;
        }
        
        .friend-actions button:hover, .request-actions button:hover {
            background-color: var(--bg-card);
            color: var(--accent);
        }
        
        .request-actions .accept {
            color: var(--success);
        }
        
        .request-actions .reject {
            color: var(--error);
        }
        
        .new-chat-btn {
            display: flex;
            align-items: center;
            gap: 0.7rem;
            background-color: var(--accent);
            color: var(--bg-primary);
            border: none;
            border-radius: 10px;
            padding: 0.8rem 1rem;
            cursor: pointer;
            font-weight: 600;
            font-size: 0.9rem;
            margin-top: 1rem;
            transition: all 0.2s;
        }
        
        .new-chat-btn:hover {
            background-color: var(--accent-hover);
        }
        
        .main-content {
            flex: 1;
            margin-left: var(--sidebar-width);
            display: flex;
            flex-direction: column;
            height: 100vh;
        }
        
        .header {
            height: var(--header-height);
            background-color: var(--bg-secondary);
            border-bottom: 1px solid var(--border);
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 2rem;
        }
        
        .header h2 {
            font-size: 1.2rem;
            font-weight: 600;
        }
        
        .header-actions {
            display: flex;
            gap: 1rem;
        }
        
        .header-actions button {
            background: transparent;
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            padding: 0.5rem;
            border-radius: 50%;
            transition: all 0.2s;
            font-size: 1.1rem;
        }
        
        .header-actions button:hover {
            background-color: var(--bg-card);
            color: var(--accent);
        }
        
        .chat-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: var(--bg-secondary);
        }
        
        .welcome-message {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            text-align: center;
            padding: 2rem;
            color: var(--text-secondary);
        }
        
        .welcome-message i {
            font-size: 4rem;
            margin-bottom: 1rem;
            color: var(--accent);
        }
        
        .welcome-message h2 {
            font-size: 1.5rem;
            margin-bottom: 0.5rem;
            color: var(--text-primary);
        }
        
        .welcome-message p {
            max-width: 400px;
            line-height: 1.6;
        }
        
        .join-group-btn {
            display: flex;
            align-items: center;
            gap: 0.7rem;
            background-color: var(--accent);
            color: var(--bg-primary);
            border: none;
            border-radius: 10px;
            padding: 0.8rem 1rem;
            cursor: pointer;
            font-weight: 600;
            font-size: 0.9rem;
            margin-top: 1rem;
            transition: all 0.2s;
        }
        
        .join-group-btn:hover {
            background-color: var(--accent-hover);
        }
        
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                height: auto;
                position: relative;
            }
            
            .main-content {
                margin-left: 0;
            }
            
            .header {
                padding: 0 1rem;
            }
        }
    </style>
</head>
<body>
    <aside class="sidebar">
        <div class="sidebar-header">
            <div class="profile-pic">
                {% if session.get('profile_pic') %}
                    <img src="{{ session['profile_pic'] }}" alt="Photo de profil">
                {% else %}
                    <i class="fas fa-user"></i>
                {% endif %}
            </div>
            <div class="profile-info">
                <h3>{{ session['username'] }}</h3>
                <p>En ligne</p>
            </div>
        </div>
        
        <div class="sidebar-section">
            <div class="search-bar">
                <i class="fas fa-search"></i>
                <input type="text" id="searchInput" placeholder="Rechercher un utilisateur...">
            </div>
        </div>
        
        <div class="sidebar-section">
            <h3>Demandes d'ami</h3>
            {% if pending_requests %}
            <div class="request-list">
                {% for user in pending_requests %}
                <div class="request-item" data-user-id="{{ user['user_id'] }}">
                    <div class="profile-pic">
                        {% if user['profile_pic'] %}
                            <img src="{{ user['profile_pic'] }}" alt="Photo de profil">
                        {% else %}
                            <i class="fas fa-user"></i>
                        {% endif %}
                    </div>
                    <div class="request-info">
                        <h4>{{ user['username'] }}</h4>
                        <p>{{ user['bio'] if user['bio'] else 'Aucune bio' }}</p>
                    </div>
                    <div class="request-actions">
                        <button class="accept" onclick="acceptFriendRequest({{ user['user_id'] }})" title="Accepter">
                            <i class="fas fa-check"></i>
                        </button>
                        <button class="reject" onclick="rejectFriendRequest({{ user['user_id'] }})" title="Refuser">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
                {% endfor %}
            </div>
            {% else %}
            <p style="color: var(--text-tertiary); font-size: 0.85rem;">Aucune demande en attente</p>
            {% endif %}
        </div>
        
        <div class="sidebar-section">
            <h3>Amis</h3>
            {% if friends %}
            <div class="friend-list">
                {% for user in friends %}
                <div class="friend-item" onclick="startChat({{ user['user_id'] }}, 'user')">
                    <div class="profile-pic">
                        {% if user['profile_pic'] %}
                            <img src="{{ user['profile_pic'] }}" alt="Photo de profil">
                        {% else %}
                            <i class="fas fa-user"></i>
                        {% endif %}
                    </div>
                    <div class="friend-info">
                        <h4>{{ user['username'] }}</h4>
                        <p>{{ user['bio'] if user['bio'] else 'Aucune bio' }}</p>
                    </div>
                    <div class="friend-actions">
                        <button onclick="event.stopPropagation(); likeProfile({{ user['user_id'] }})" title="Liker le profil">
                            <i class="fas fa-heart"></i>
                        </button>
                    </div>
                </div>
                {% endfor %}
            </div>
            {% else %}
            <p style="color: var(--text-tertiary); font-size: 0.85rem;">Aucun ami pour l'instant</p>
            {% endif %}
        </div>
        
        <div class="sidebar-section">
            <h3>Suggestions</h3>
            {% if friend_suggestions %}
            <div class="friend-list">
                {% for user in friend_suggestions %}
                <div class="friend-item" onclick="startChat({{ user['user_id'] }}, 'user')">
                    <div class="profile-pic">
                        {% if user['profile_pic'] %}
                            <img src="{{ user['profile_pic'] }}" alt="Photo de profil">
                        {% else %}
                            <i class="fas fa-user"></i>
                        {% endif %}
                    </div>
                    <div class="friend-info">
                        <h4>{{ user['username'] }}</h4>
                        <p>{{ user['bio'] if user['bio'] else 'Aucune bio' }}</p>
                    </div>
                    <div class="friend-actions">
                        <button onclick="event.stopPropagation(); sendFriendRequest({{ user['user_id'] }})" title="Ajouter en ami">
                            <i class="fas fa-user-plus"></i>
                        </button>
                    </div>
                </div>
                {% endfor %}
            </div>
            {% else %}
            <p style="color: var(--text-tertiary); font-size: 0.85rem;">Aucune suggestion</p>
            {% endif %}
        </div>
        
        <div class="sidebar-section">
            <h3>Groupes</h3>
            {% if groups %}
            <div class="group-list">
                {% for group in groups %}
                <div class="group-item" onclick="window.location.href='/chat/group/{{ group.group_id }}'">
                    <div class="group-icon">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="group-info">
                        <h4>{{ group.group_name }}</h4>
                        <p>{{ group.last_message if group.last_message else 'Aucun message' }}</p>
                    </div>
                </div>
                {% endfor %}
            </div>
            {% else %}
            <p style="color: var(--text-tertiary); font-size: 0.85rem;">Aucun groupe</p>
            {% endif %}
            <button class="new-chat-btn" onclick="window.location.href='/create_group'">
                <i class="fas fa-plus"></i>
                Nouveau groupe
            </button>
            <button class="join-group-btn" onclick="promptJoinGroup()">
                <i class="fas fa-sign-in-alt"></i>
                Rejoindre un groupe
            </button>
        </div>
    </aside>
    
    <main class="main-content">
        <header class="header">
            <h2>Tableau de bord</h2>
            <div class="header-actions">
                <button onclick="toggleTheme()" title="Changer de thème">
                    <i class="fas fa-moon"></i>
                </button>
                <button onclick="logout()" title="Se déconnecter">
                    <i class="fas fa-sign-out-alt"></i>
                </button>
            </div>
        </header>
        
        <div class="chat-area">
            <div class="welcome-message">
                <i class="fas fa-comments"></i>
                <h2>Bienvenue sur NexaPy</h2>
                <p>Sélectionnez une conversation ou un ami pour commencer à discuter.</p>
            </div>
        </div>
    </main>
    
    <script>
        function startChat(userId, type) {
            if (type === 'user') {
                window.location.href = '/chat/user/' + userId;
            }
        }
        
        async function sendFriendRequest(userId) {
            const response = await fetch('/send_friend_request', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({user_id: userId})
            });
            if (response.ok) {
                location.reload();
            }
        }
        
        async function acceptFriendRequest(userId) {
            const response = await fetch('/accept_friend_request', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({user_id: userId})
            });
            if (response.ok) {
                location.reload();
            }
        }
        
        async function rejectFriendRequest(userId) {
            const response = await fetch('/reject_friend_request', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({user_id: userId})
            });
            if (response.ok) {
                location.reload();
            }
        }
        
        async function likeProfile(userId) {
            const response = await fetch('/like_profile', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({user_id: userId})
            });
            if (response.ok) {
                alert('Profil liké !');
            }
        }
        
        function promptJoinGroup() {
            const accessCode = prompt("Entrez le code d'accès du groupe :");
            if (accessCode) {
                joinGroup(accessCode);
            }
        }
        
        async function joinGroup(accessCode) {
            const response = await fetch('/join_group', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({access_code: accessCode})
            });
            
            if (response.ok) {
                alert('Groupe rejoint avec succès !');
                location.reload();
            } else {
                const data = await response.json();
                alert(data.error || 'Erreur lors de la tentative de rejoindre le groupe');
            }
        }
        
        function logout() {
            window.location.href = '/logout';
        }
        
        function toggleTheme() {
            alert('Fonctionnalité à implémenter');
        }
        
        document.getElementById('searchInput').addEventListener('input', async (e) => {
            const query = e.target.value;
            if (query.length < 2) return;
            
            const response = await fetch('/search_users?q=' + encodeURIComponent(query));
            const users = await response.json();
            console.log(users);
        });
    </script>
</body>
</html>
    """, 
    conversations=conversations, 
    groups=groups, 
    friend_suggestions=friend_suggestions, 
    pending_requests=pending_requests,
    friends=friends)


@app.route("/search_users")
def search_users():
    query = request.args.get("q", "")
    if len(query) < 2:
        return jsonify([])
    
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute('''
        SELECT user_id, username, profile_pic, bio
        FROM users
        WHERE username LIKE ? AND user_id != ?
        LIMIT 5
    ''', (f"%{query}%", session["user_id"]))
    users = cursor.fetchall()
    conn.close()
    
    return jsonify([{
        "user_id": user["user_id"],
        "username": user["username"],
        "profile_pic": user["profile_pic"],
        "bio": user["bio"]
    } for user in users])


@app.route("/send_friend_request", methods=["POST"])
def send_friend_request():
    if "user_id" not in session:
        return jsonify({"error": "Non autorisé"}), 401
    
    data = request.get_json()
    user2_id = data.get("user_id")
    
    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute('''
        SELECT * FROM friendships 
        WHERE (user1_id = ? AND user2_id = ?) OR (user1_id = ? AND user2_id = ?)
    ''', (session["user_id"], user2_id, user2_id, session["user_id"]))
    existing = cursor.fetchone()
    
    if existing:
        conn.close()
        return jsonify({"error": "Demande déjà envoyée ou ami existant"}), 400
    
    cursor.execute("INSERT INTO friendships (user1_id, user2_id, status) VALUES (?, ?, 'pending')", 
                   (session["user_id"], user2_id))
    conn.commit()
    conn.close()
    
    return jsonify({"success": True})


@app.route("/accept_friend_request", methods=["POST"])
def accept_friend_request():
    if "user_id" not in session:
        return jsonify({"error": "Non autorisé"}), 401
    
    data = request.get_json()
    user1_id = data.get("user_id")
    
    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute('''
        UPDATE friendships 
        SET status = 'accepted' 
        WHERE user1_id = ? AND user2_id = ? AND status = 'pending'
    ''', (user1_id, session["user_id"]))
    
    cursor.execute("INSERT OR IGNORE INTO conversations (user1_id, user2_id) VALUES (?, ?)", 
                   (session["user_id"], user1_id))
    
    conn.commit()
    conn.close()
    
    return jsonify({"success": True})


@app.route("/reject_friend_request", methods=["POST"])
def reject_friend_request():
    if "user_id" not in session:
        return jsonify({"error": "Non autorisé"}), 401
    
    data = request.get_json()
    user1_id = data.get("user_id")
    
    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute('''
        DELETE FROM friendships 
        WHERE user1_id = ? AND user2_id = ? AND status = 'pending'
    ''', (user1_id, session["user_id"]))
    
    conn.commit()
    conn.close()
    
    return jsonify({"success": True})


@app.route("/like_profile", methods=["POST"])
def like_profile():
    if "user_id" not in session:
        return jsonify({"error": "Non autorisé"}), 401
    
    data = request.get_json()
    liked_id = data.get("user_id")
    
    conn = get_db_connection()
    cursor = conn.cursor()
    
    try:
        cursor.execute("INSERT INTO profile_likes (liker_id, liked_id) VALUES (?, ?)", 
                       (session["user_id"], liked_id))
        conn.commit()
    except sqlite3.IntegrityError:
        conn.close()
        return jsonify({"error": "Profil déjà liké"}), 400
    
    conn.close()
    return jsonify({"success": True})


@app.route("/join_group", methods=["POST"])
def join_group():
    if "user_id" not in session:
        return jsonify({"error": "Non autorisé"}), 401
    
    data = request.get_json()
    access_code = data.get("access_code")
    
    if not access_code:
        return jsonify({"error": "Code d'accès requis"}), 400
    
    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute("SELECT group_id FROM groups WHERE access_code = ?", (access_code,))
    group = cursor.fetchone()
    
    if not group:
        conn.close()
        return jsonify({"error": "Code d'accès invalide"}), 404
    
    cursor.execute("SELECT * FROM group_members WHERE group_id = ? AND user_id = ?", 
                   (group["group_id"], session["user_id"]))
    existing_member = cursor.fetchone()
    
    if existing_member:
        conn.close()
        return jsonify({"error": "Vous êtes déjà membre de ce groupe"}), 400
    
    cursor.execute("INSERT INTO group_members (group_id, user_id) VALUES (?, ?)", 
                   (group["group_id"], session["user_id"]))
    conn.commit()
    conn.close()
    
    return jsonify({"success": True})


@app.route("/chat/user/<int:user_id>")
def chat_user(user_id):
    if "user_id" not in session:
        return redirect(url_for("login"))
    
    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute("SELECT * FROM users WHERE user_id = ?", (user_id,))
    user = cursor.fetchone()
    if not user:
        conn.close()
        return redirect(url_for("dashboard"))
    
    cursor.execute('''
        SELECT c.conversation_id 
        FROM conversations c 
        WHERE (c.user1_id = ? AND c.user2_id = ?) OR (c.user1_id = ? AND c.user2_id = ?)
    ''', (session["user_id"], user_id, user_id, session["user_id"]))
    conversation = cursor.fetchone()
    
    if not conversation:
        cursor.execute("INSERT INTO conversations (user1_id, user2_id) VALUES (?, ?)", 
                       (session["user_id"], user_id))
        conversation_id = cursor.lastrowid
    else:
        conversation_id = conversation["conversation_id"]
    
    cursor.execute('''
        SELECT m.message_id, m.sender_id, m.content, m.timestamp, u.username, u.profile_pic
        FROM messages m
        JOIN users u ON m.sender_id = u.user_id
        WHERE m.conversation_id = ?
        ORDER BY m.timestamp ASC
    ''', (conversation_id,))
    messages = cursor.fetchall()
    
    cursor.execute('''
        UPDATE messages 
        SET is_read = TRUE 
        WHERE conversation_id = ? AND sender_id != ?
    ''', (conversation_id, session["user_id"]))
    conn.commit()
    conn.close()
    
    return render_template_string("""
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat avec {{ user['username'] }} - NexaPy</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --bg-primary: #0a0a0a;
            --bg-secondary: #121212;
            --bg-tertiary: #1e1e1e;
            --bg-card: #262626;
            --text-primary: #ffffff;
            --text-secondary: #a0a0a0;
            --text-tertiary: #707070;
            --accent: #00bcd4;
            --accent-hover: #0097a7;
            --error: #ff5252;
            --success: #4caf50;
            --border: #2a2a2a;
            --shadow: rgba(0, 0, 0, 0.5);
            --sidebar-width: 320px;
            --header-height: 70px;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', sans-serif;
        }
        
        body {
            background-color: var(--bg-primary);
            color: var(--text-primary);
            min-height: 100vh;
            display: flex;
        }
        
        .sidebar {
            width: var(--sidebar-width);
            background-color: var(--bg-secondary);
            border-right: 1px solid var(--border);
            height: 100vh;
            position: fixed;
            display: flex;
            flex-direction: column;
            overflow-y: auto;
        }
        
        .sidebar-header {
            padding: 1.5rem;
            border-bottom: 1px solid var(--border);
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .sidebar-header .profile-pic {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: var(--bg-tertiary);
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1.5rem;
            color: var(--text-secondary);
            overflow: hidden;
        }
        
        .sidebar-header .profile-pic img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .sidebar-header .profile-info h3 {
            font-size: 1rem;
            font-weight: 600;
            margin-bottom: 0.2rem;
        }
        
        .sidebar-header .profile-info p {
            font-size: 0.8rem;
            color: var(--text-secondary);
        }
        
        .sidebar-section {
            padding: 1.5rem;
        }
        
        .sidebar-section h3 {
            font-size: 0.85rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: var(--text-secondary);
            margin-bottom: 1rem;
            font-weight: 600;
        }
        
        .search-bar {
            display: flex;
            align-items: center;
            gap: 0.7rem;
            background-color: var(--bg-tertiary);
            border-radius: 10px;
            padding: 0.7rem 1rem;
            margin-bottom: 1rem;
            border: 1px solid var(--border);
        }
        
        .search-bar input {
            flex: 1;
            background: transparent;
            border: none;
            color: var(--text-primary);
            font-size: 0.9rem;
        }
        
        .search-bar input:focus {
            outline: none;
        }
        
        .search-bar i {
            color: var(--text-secondary);
        }
        
        .friend-list, .group-list {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }
        
        .friend-item, .group-item {
            display: flex;
            align-items: center;
            gap: 0.8rem;
            padding: 0.8rem 1rem;
            border-radius: 10px;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .friend-item:hover, .group-item:hover {
            background-color: var(--bg-tertiary);
        }
        
        .friend-item.active, .group-item.active {
            background-color: var(--bg-card);
        }
        
        .friend-item .profile-pic {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--bg-card);
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1rem;
            color: var(--text-secondary);
            overflow: hidden;
        }
        
        .friend-item .profile-pic img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .group-item .group-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--accent);
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1rem;
        }
        
        .friend-info, .group-info {
            flex: 1;
            min-width: 0;
        }
        
        .friend-info h4, .group-info h4 {
            font-size: 0.95rem;
            font-weight: 600;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .friend-info p, .group-info p {
            font-size: 0.8rem;
            color: var(--text-secondary);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .new-chat-btn {
            display: flex;
            align-items: center;
            gap: 0.7rem;
            background-color: var(--accent);
            color: var(--bg-primary);
            border: none;
            border-radius: 10px;
            padding: 0.8rem 1rem;
            cursor: pointer;
            font-weight: 600;
            font-size: 0.9rem;
            margin-top: 1rem;
            transition: all 0.2s;
        }
        
        .new-chat-btn:hover {
            background-color: var(--accent-hover);
        }
        
        .main-content {
            flex: 1;
            margin-left: var(--sidebar-width);
            display: flex;
            flex-direction: column;
            height: 100vh;
        }
        
        .header {
            height: var(--header-height);
            background-color: var(--bg-secondary);
            border-bottom: 1px solid var(--border);
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 2rem;
        }
        
        .header .chat-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .header .chat-info .profile-pic {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--bg-tertiary);
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1rem;
            color: var(--text-secondary);
            overflow: hidden;
        }
        
        .header .chat-info .profile-pic img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .header .chat-info h2 {
            font-size: 1.1rem;
            font-weight: 600;
        }
        
        .header .chat-info p {
            font-size: 0.8rem;
            color: var(--text-secondary);
        }
        
        .header-actions {
            display: flex;
            gap: 1rem;
        }
        
        .header-actions button {
            background: transparent;
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            padding: 0.5rem;
            border-radius: 50%;
            transition: all 0.2s;
            font-size: 1.1rem;
        }
        
        .header-actions button:hover {
            background-color: var(--bg-card);
            color: var(--accent);
        }
        
        .chat-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: var(--bg-secondary);
            overflow-y: auto;
        }
        
        .messages {
            flex: 1;
            padding: 1.5rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
            overflow-y: auto;
        }
        
        .message {
            max-width: 70%;
            padding: 1rem;
            border-radius: 12px;
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }
        
        .message.sent {
            align-self: flex-end;
            background-color: var(--accent);
            color: var(--bg-primary);
            border-bottom-right-radius: 0;
        }
        
        .message.received {
            align-self: flex-start;
            background-color: var(--bg-card);
            border-bottom-left-radius: 0;
        }
        
        .message .message-header {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.8rem;
        }
        
        .message.sent .message-header {
            justify-content: flex-end;
        }
        
        .message .sender {
            font-weight: 600;
        }
        
        .message .timestamp {
            color: rgba(255, 255, 255, 0.7);
        }
        
        .message.received .timestamp {
            color: var(--text-secondary);
        }
        
        .message-form {
            display: flex;
            gap: 1rem;
            padding: 1.5rem;
            background-color: var(--bg-secondary);
            border-top: 1px solid var(--border);
        }
        
        .message-form input {
            flex: 1;
            padding: 0.9rem 1.2rem;
            background-color: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: 25px;
            color: var(--text-primary);
            font-size: 1rem;
            transition: all 0.3s;
        }
        
        .message-form input:focus {
            outline: none;
            border-color: var(--accent);
            box-shadow: 0 0 0 3px rgba(0, 188, 212, 0.1);
        }
        
        .message-form input::placeholder {
            color: var(--text-tertiary);
        }
        
        .message-form button {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--accent), var(--accent-hover));
            color: var(--bg-primary);
            border: none;
            cursor: pointer;
            font-size: 1.2rem;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0, 188, 212, 0.2);
        }
        
        .message-form button:hover {
            transform: scale(1.05);
            box-shadow: 0 6px 20px rgba(0, 188, 212, 0.3);
        }
        
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                height: auto;
                position: relative;
            }
            
            .main-content {
                margin-left: 0;
            }
            
            .header {
                padding: 0 1rem;
            }
            
            .message {
                max-width: 85%;
            }
        }
    </style>
</head>
<body>
    <aside class="sidebar">
        <div class="sidebar-header">
            <div class="profile-pic">
                {% if session.get('profile_pic') %}
                    <img src="{{ session['profile_pic'] }}" alt="Photo de profil">
                {% else %}
                    <i class="fas fa-user"></i>
                {% endif %}
            </div>
            <div class="profile-info">
                <h3>{{ session['username'] }}</h3>
                <p>En ligne</p>
            </div>
        </div>
        
        <div class="sidebar-section">
            <div class="search-bar">
                <i class="fas fa-search"></i>
                <input type="text" id="searchInput" placeholder="Rechercher un utilisateur...">
            </div>
        </div>
        
        <div class="sidebar-section">
            <h3>Conversations</h3>
            <div class="friend-list">
                {% for conversation in conversations %}
                <div class="friend-item" onclick="window.location.href='/chat/user/{{ conversation.user_id }}'">
                    <div class="profile-pic">
                        {% if conversation['profile_pic'] %}
                            <img src="{{ conversation['profile_pic'] }}" alt="Photo de profil">
                        {% else %}
                            <i class="fas fa-user"></i>
                        {% endif %}
                    </div>
                    <div class="friend-info">
                        <h4>{{ conversation['username'] }}</h4>
                        <p>{{ conversation['last_message'] if conversation['last_message'] else 'Aucun message' }}</p>
                    </div>
                </div>
                {% endfor %}
            </div>
        </div>
        
        <div class="sidebar-section">
            <h3>Groupes</h3>
            <div class="group-list">
                {% for group in groups %}
                <div class="group-item" onclick="window.location.href='/chat/group/{{ group.group_id }}'">
                    <div class="group-icon">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="group-info">
                        <h4>{{ group.group_name }}</h4>
                        <p>{{ group.last_message if group.last_message else 'Aucun message' }}</p>
                    </div>
                </div>
                {% endfor %}
            </div>
            <button class="new-chat-btn" onclick="window.location.href='/create_group'">
                <i class="fas fa-plus"></i>
                Nouveau groupe
            </button>
        </div>
    </aside>
    
    <main class="main-content">
        <header class="header">
            <div class="chat-info">
                <div class="profile-pic">
                    {% if user['profile_pic'] %}
                        <img src="{{ user['profile_pic'] }}" alt="Photo de profil">
                    {% else %}
                        <i class="fas fa-user"></i>
                    {% endif %}
                </div>
                <div>
                    <h2>{{ user['username'] }}</h2>
                    <p>En ligne</p>
                </div>
            </div>
            <div class="header-actions">
                <button onclick="likeProfile({{ user['user_id'] }})" title="Liker le profil">
                    <i class="fas fa-heart"></i>
                </button>
                <button onclick="toggleTheme()" title="Changer de thème">
                    <i class="fas fa-moon"></i>
                </button>
                <button onclick="logout()" title="Se déconnecter">
                    <i class="fas fa-sign-out-alt"></i>
                </button>
            </div>
        </header>
        
        <div class="chat-area">
            <div class="messages" id="messages">
                {% for message in messages %}
                <div class="message {% if message['sender_id'] == session['user_id'] %}sent{% else %}received{% endif %}">
                    <div class="message-header">
                        <span class="sender">{{ message['username'] }}</span>
                        <span class="timestamp">{{ message['timestamp'] }}</span>
                    </div>
                    <p>{{ message['content'] }}</p>
                </div>
                {% endfor %}
            </div>
            
            <form class="message-form" id="messageForm">
                <input type="text" id="messageInput" placeholder="Écrivez un message..." required>
                <button type="submit"><i class="fas fa-paper-plane"></i></button>
            </form>
        </div>
    </main>
    
    <script>
        const conversationId = {{ conversation_id }};
        const receiverId = {{ user['user_id'] }};
        
        document.getElementById('messageForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const input = document.getElementById('messageInput');
            const content = input.value;
            
            if (!content.trim()) return;
            
            const response = await fetch('/send_message', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    conversation_id: conversationId,
                    content: content
                })
            });
            
            if (response.ok) {
                input.value = '';
                const data = await response.json();
                
                const messagesDiv = document.getElementById('messages');
                const messageDiv = document.createElement('div');
                messageDiv.className = 'message sent';
                messageDiv.innerHTML = `
                    <div class="message-header">
                        <span class="sender">${data.username}</span>
                        <span class="timestamp">${data.timestamp}</span>
                    </div>
                    <p>${data.content}</p>
                `;
                messagesDiv.appendChild(messageDiv);
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
            }
        });
        
        setInterval(async () => {
            const response = await fetch('/get_messages?conversation_id=' + conversationId);
            if (response.ok) {
                const messages = await response.json();
                const messagesDiv = document.getElementById('messages');
                messagesDiv.innerHTML = messages.map(msg => `
                    <div class="message ${msg.sender_id == {{ session['user_id'] }} ? 'sent' : 'received'}">
                        <div class="message-header">
                            <span class="sender">${msg.username}</span>
                            <span class="timestamp">${msg.timestamp}</span>
                        </div>
                        <p>${msg.content}</p>
                    </div>
                `).join('');
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
            }
        }, 2000);
        
        async function likeProfile(userId) {
            const response = await fetch('/like_profile', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({user_id: userId})
            });
            if (response.ok) {
                alert('Profil liké !');
            }
        }
        
        function logout() {
            window.location.href = '/logout';
        }
        
        function toggleTheme() {
            alert('Fonctionnalité à implémenter');
        }
    </script>
</body>
</html>
    """, 
    user=user, 
    messages=messages,
    conversation_id=conversation_id)


@app.route("/send_message", methods=["POST"])
def send_message():
    if "user_id" not in session:
        return jsonify({"error": "Non autorisé"}), 401
    
    data = request.get_json()
    conversation_id = data.get("conversation_id")
    content = data.get("content")
    
    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute("INSERT INTO messages (conversation_id, sender_id, content) VALUES (?, ?, ?)", 
                   (conversation_id, session["user_id"], content))
    conn.commit()
    
    cursor.execute('''
        SELECT m.message_id, m.sender_id, m.content, m.timestamp, u.username
        FROM messages m
        JOIN users u ON m.sender_id = u.user_id
        WHERE m.message_id = ?
    ''', (cursor.lastrowid,))
    message = cursor.fetchone()
    conn.close()
    
    return jsonify({
        "message_id": message["message_id"],
        "sender_id": message["sender_id"],
        "content": message["content"],
        "timestamp": message["timestamp"],
        "username": message["username"]
    })


@app.route("/get_messages")
def get_messages():
    conversation_id = request.args.get("conversation_id")
    if not conversation_id or "user_id" not in session:
        return jsonify([])
    
    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute('''
        SELECT m.message_id, m.sender_id, m.content, m.timestamp, u.username
        FROM messages m
        JOIN users u ON m.sender_id = u.user_id
        WHERE m.conversation_id = ?
        ORDER BY m.timestamp ASC
    ''', (conversation_id,))
    messages = cursor.fetchall()
    conn.close()
    
    return jsonify([{
        "message_id": message["message_id"],
        "sender_id": message["sender_id"],
        "content": message["content"],
        "timestamp": message["timestamp"],
        "username": message["username"]
    } for message in messages])


@app.route("/create_group", methods=["GET", "POST"])
def create_group():
    if "user_id" not in session:
        return redirect(url_for("login"))
    
    if request.method == "POST":
        group_name = request.form["group_name"]
        access_code = request.form["access_code"]
        
        conn = get_db_connection()
        cursor = conn.cursor()
        
        try:
            cursor.execute("INSERT INTO groups (group_name, access_code, created_by) VALUES (?, ?, ?)", 
                           (group_name, access_code, session["user_id"]))
            group_id = cursor.lastrowid
            cursor.execute("INSERT INTO group_members (group_id, user_id) VALUES (?, ?)", 
                           (group_id, session["user_id"]))
            conn.commit()
            return redirect(url_for("dashboard"))
        except sqlite3.IntegrityError:
            return "Code d'accès déjà utilisé."
        finally:
            conn.close()
    
    return render_template_string("""
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Créer un groupe - NexaPy</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --bg-primary: #0a0a0a;
            --bg-secondary: #121212;
            --bg-tertiary: #1e1e1e;
            --text-primary: #ffffff;
            --text-secondary: #a0a0a0;
            --text-tertiary: #707070;
            --accent: #00bcd4;
            --accent-hover: #0097a7;
            --border: #2a2a2a;
            --shadow: rgba(0, 0, 0, 0.5);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, var(--bg-primary) 0%, var(--bg-secondary) 100%);
            color: var(--text-primary);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .container {
            background-color: var(--bg-secondary);
            border-radius: 16px;
            padding: 2.5rem;
            width: 100%;
            max-width: 500px;
            box-shadow: 0 20px 60px var(--shadow);
            border: 1px solid var(--border);
        }
        
        .logo {
            text-align: center;
            margin-bottom: 2rem;
        }
        
        .logo h1 {
            font-size: 2rem;
            font-weight: 700;
            background: linear-gradient(135deg, var(--accent), var(--accent-hover));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .logo p {
            color: var(--text-secondary);
            font-size: 0.9rem;
            margin-top: 0.5rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: var(--text-secondary);
            font-size: 0.9rem;
            font-weight: 500;
        }
        
        .form-group input {
            width: 100%;
            padding: 0.9rem 1.2rem;
            background-color: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: 10px;
            color: var(--text-primary);
            font-size: 1rem;
            transition: all 0.3s;
        }
        
        .form-group input:focus {
            outline: none;
            border-color: var(--accent);
            box-shadow: 0 0 0 3px rgba(0, 188, 212, 0.1);
        }
        
        .form-group input::placeholder {
            color: var(--text-tertiary);
        }
        
        .btn {
            width: 100%;
            padding: 0.9rem;
            background: linear-gradient(135deg, var(--accent), var(--accent-hover));
            color: var(--bg-primary);
            border: none;
            border-radius: 10px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0, 188, 212, 0.2);
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 188, 212, 0.3);
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .link {
            text-align: center;
            margin-top: 1.5rem;
        }
        
        .link a {
            color: var(--accent);
            text-decoration: none;
            font-weight: 500;
        }
        
        .link a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="logo">
            <h1>NexaPy</h1>
            <p>Créer un nouveau groupe</p>
        </div>
        
        <form method="POST">
            <div class="form-group">
                <label for="group_name">Nom du groupe</label>
                <input type="text" id="group_name" name="group_name" placeholder="Ex: Les développeurs Python" required>
            </div>
            <div class="form-group">
                <label for="access_code">Code d'accès</label>
                <input type="text" id="access_code" name="access_code" placeholder="Ex: PYTHON2024" required>
            </div>
            <button type="submit" class="btn">Créer le groupe</button>
        </form>
        
        <div class="link">
            <p><a href="{{ url_for('dashboard') }}">Retour au tableau de bord</a></p>
        </div>
    </div>
</body>
</html>
    """)


@app.route("/chat/group/<int:group_id>")
def chat_group(group_id):
    if "user_id" not in session:
        return redirect(url_for("login"))
    
    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute("SELECT * FROM groups WHERE group_id = ?", (group_id,))
    group = cursor.fetchone()
    if not group:
        conn.close()
        return redirect(url_for("dashboard"))
    
    cursor.execute("SELECT * FROM group_members WHERE group_id = ? AND user_id = ?", 
                   (group_id, session["user_id"]))
    if not cursor.fetchone():
        conn.close()
        return redirect(url_for("dashboard"))
    
    cursor.execute('''
        SELECT m.message_id, m.sender_id, m.content, m.timestamp, u.username, u.profile_pic
        FROM messages m
        JOIN users u ON m.sender_id = u.user_id
        WHERE m.group_id = ?
        ORDER BY m.timestamp ASC
    ''', (group_id,))
    messages = cursor.fetchall()
    
    cursor.execute('''
        UPDATE messages 
        SET is_read = TRUE 
        WHERE group_id = ? AND sender_id != ?
    ''', (group_id, session["user_id"]))
    conn.commit()
    
    conn.close()
    
    return render_template_string("""
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat - {{ group['group_name'] }} - NexaPy</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --bg-primary: #0a0a0a;
            --bg-secondary: #121212;
            --bg-tertiary: #1e1e1e;
            --bg-card: #262626;
            --text-primary: #ffffff;
            --text-secondary: #a0a0a0;
            --text-tertiary: #707070;
            --accent: #00bcd4;
            --accent-hover: #0097a7;
            --error: #ff5252;
            --success: #4caf50;
            --border: #2a2a2a;
            --shadow: rgba(0, 0, 0, 0.5);
            --sidebar-width: 320px;
            --header-height: 70px;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', sans-serif;
        }
        
        body {
            background-color: var(--bg-primary);
            color: var(--text-primary);
            min-height: 100vh;
            display: flex;
        }
        
        .sidebar {
            width: var(--sidebar-width);
            background-color: var(--bg-secondary);
            border-right: 1px solid var(--border);
            height: 100vh;
            position: fixed;
            display: flex;
            flex-direction: column;
            overflow-y: auto;
        }
        
        .sidebar-header {
            padding: 1.5rem;
            border-bottom: 1px solid var(--border);
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .sidebar-header .profile-pic {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: var(--bg-tertiary);
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1.5rem;
            color: var(--text-secondary);
            overflow: hidden;
        }
        
        .sidebar-header .profile-pic img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .sidebar-header .profile-info h3 {
            font-size: 1rem;
            font-weight: 600;
            margin-bottom: 0.2rem;
        }
        
        .sidebar-header .profile-info p {
            font-size: 0.8rem;
            color: var(--text-secondary);
        }
        
        .sidebar-section {
            padding: 1.5rem;
        }
        
        .sidebar-section h3 {
            font-size: 0.85rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: var(--text-secondary);
            margin-bottom: 1rem;
            font-weight: 600;
        }
        
        .search-bar {
            display: flex;
            align-items: center;
            gap: 0.7rem;
            background-color: var(--bg-tertiary);
            border-radius: 10px;
            padding: 0.7rem 1rem;
            margin-bottom: 1rem;
            border: 1px solid var(--border);
        }
        
        .search-bar input {
            flex: 1;
            background: transparent;
            border: none;
            color: var(--text-primary);
            font-size: 0.9rem;
        }
        
        .search-bar input:focus {
            outline: none;
        }
        
        .search-bar i {
            color: var(--text-secondary);
        }
        
        .friend-list, .group-list {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }
        
        .friend-item, .group-item {
            display: flex;
            align-items: center;
            gap: 0.8rem;
            padding: 0.8rem 1rem;
            border-radius: 10px;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .friend-item:hover, .group-item:hover {
            background-color: var(--bg-tertiary);
        }
        
        .group-item.active {
            background-color: var(--bg-card);
        }
        
        .friend-item .profile-pic {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--bg-card);
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1rem;
            color: var(--text-secondary);
            overflow: hidden;
        }
        
        .friend-item .profile-pic img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .group-item .group-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--accent);
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1rem;
        }
        
        .friend-info, .group-info {
            flex: 1;
            min-width: 0;
        }
        
        .friend-info h4, .group-info h4 {
            font-size: 0.95rem;
            font-weight: 600;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .friend-info p, .group-info p {
            font-size: 0.8rem;
            color: var(--text-secondary);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .new-chat-btn {
            display: flex;
            align-items: center;
            gap: 0.7rem;
            background-color: var(--accent);
            color: var(--bg-primary);
            border: none;
            border-radius: 10px;
            padding: 0.8rem 1rem;
            cursor: pointer;
            font-weight: 600;
            font-size: 0.9rem;
            margin-top: 1rem;
            transition: all 0.2s;
        }
        
        .new-chat-btn:hover {
            background-color: var(--accent-hover);
        }
        
        .main-content {
            flex: 1;
            margin-left: var(--sidebar-width);
            display: flex;
            flex-direction: column;
            height: 100vh;
        }
        
        .header {
            height: var(--header-height);
            background-color: var(--bg-secondary);
            border-bottom: 1px solid var(--border);
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 2rem;
        }
        
        .header .chat-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .header .chat-info .group-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--accent);
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1rem;
        }
        
        .header .chat-info h2 {
            font-size: 1.1rem;
            font-weight: 600;
        }
        
        .header .chat-info p {
            font-size: 0.8rem;
            color: var(--text-secondary);
        }
        
        .header-actions {
            display: flex;
            gap: 1rem;
        }
        
        .header-actions button {
            background: transparent;
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            padding: 0.5rem;
            border-radius: 50%;
            transition: all 0.2s;
            font-size: 1.1rem;
        }
        
        .header-actions button:hover {
            background-color: var(--bg-card);
            color: var(--accent);
        }
        
        .chat-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: var(--bg-secondary);
            overflow-y: auto;
        }
        
        .messages {
            flex: 1;
            padding: 1.5rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
            overflow-y: auto;
        }
        
        .message {
            max-width: 70%;
            padding: 1rem;
            border-radius: 12px;
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }
        
        .message.sent {
            align-self: flex-end;
            background-color: var(--accent);
            color: var(--bg-primary);
            border-bottom-right-radius: 0;
        }
        
        .message.received {
            align-self: flex-start;
            background-color: var(--bg-card);
            border-bottom-left-radius: 0;
        }
        
        .message .message-header {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.8rem;
        }
        
        .message.sent .message-header {
            justify-content: flex-end;
        }
        
        .message .sender {
            font-weight: 600;
        }
        
        .message .timestamp {
            color: rgba(255, 255, 255, 0.7);
        }
        
        .message.received .timestamp {
            color: var(--text-secondary);
        }
        
        .message-form {
            display: flex;
            gap: 1rem;
            padding: 1.5rem;
            background-color: var(--bg-secondary);
            border-top: 1px solid var(--border);
        }
        
        .message-form input {
            flex: 1;
            padding: 0.9rem 1.2rem;
            background-color: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: 25px;
            color: var(--text-primary);
            font-size: 1rem;
            transition: all 0.3s;
        }
        
        .message-form input:focus {
            outline: none;
            border-color: var(--accent);
            box-shadow: 0 0 0 3px rgba(0, 188, 212, 0.1);
        }
        
        .message-form input::placeholder {
            color: var(--text-tertiary);
        }
        
        .message-form button {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--accent), var(--accent-hover));
            color: var(--bg-primary);
            border: none;
            cursor: pointer;
            font-size: 1.2rem;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0, 188, 212, 0.2);
        }
        
        .message-form button:hover {
            transform: scale(1.05);
            box-shadow: 0 6px 20px rgba(0, 188, 212, 0.3);
        }
        
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                height: auto;
                position: relative;
            }
            
            .main-content {
                margin-left: 0;
            }
            
            .header {
                padding: 0 1rem;
            }
            
            .message {
                max-width: 85%;
            }
        }
    </style>
</head>
<body>
    <aside class="sidebar">
        <div class="sidebar-header">
            <div class="profile-pic">
                {% if session.get('profile_pic') %}
                    <img src="{{ session['profile_pic'] }}" alt="Photo de profil">
                {% else %}
                    <i class="fas fa-user"></i>
                {% endif %}
            </div>
            <div class="profile-info">
                <h3>{{ session['username'] }}</h3>
                <p>En ligne</p>
            </div>
        </div>
        
        <div class="sidebar-section">
            <div class="search-bar">
                <i class="fas fa-search"></i>
                <input type="text" id="searchInput" placeholder="Rechercher un utilisateur...">
            </div>
        </div>
        
        <div class="sidebar-section">
            <h3>Conversations</h3>
            <div class="friend-list">
                {% for conversation in conversations %}
                <div class="friend-item" onclick="window.location.href='/chat/user/{{ conversation.user_id }}'">
                    <div class="profile-pic">
                        {% if conversation['profile_pic'] %}
                            <img src="{{ conversation['profile_pic'] }}" alt="Photo de profil">
                        {% else %}
                            <i class="fas fa-user"></i>
                        {% endif %}
                    </div>
                    <div class="friend-info">
                        <h4>{{ conversation['username'] }}</h4>
                        <p>{{ conversation['last_message'] if conversation['last_message'] else 'Aucun message' }}</p>
                    </div>
                </div>
                {% endfor %}
            </div>
        </div>
        
        <div class="sidebar-section">
            <h3>Groupes</h3>
            <div class="group-list">
                {% for g in groups %}
                <div class="group-item {% if g.group_id == group.group_id %}active{% endif %}" onclick="window.location.href='/chat/group/{{ g.group_id }}'">
                    <div class="group-icon">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="group-info">
                        <h4>{{ g.group_name }}</h4>
                        <p>{{ g.last_message if g.last_message else 'Aucun message' }}</p>
                    </div>
                </div>
                {% endfor %}
            </div>
            <button class="new-chat-btn" onclick="window.location.href='/create_group'">
                <i class="fas fa-plus"></i>
                Nouveau groupe
            </button>
        </div>
    </aside>
    
    <main class="main-content">
        <header class="header">
            <div class="chat-info">
                <div class="group-icon">
                    <i class="fas fa-users"></i>
                </div>
                <div>
                    <h2>{{ group['group_name'] }}</h2>
                    <p>Groupe • Code: {{ group['access_code'] }}</p>
                </div>
            </div>
            <div class="header-actions">
                <button onclick="toggleTheme()" title="Changer de thème">
                    <i class="fas fa-moon"></i>
                </button>
                <button onclick="logout()" title="Se déconnecter">
                    <i class="fas fa-sign-out-alt"></i>
                </button>
            </div>
        </header>
        
        <div class="chat-area">
            <div class="messages" id="messages">
                {% for message in messages %}
                <div class="message {% if message['sender_id'] == session['user_id'] %}sent{% else %}received{% endif %}">
                    <div class="message-header">
                        <span class="sender">{{ message['username'] }}</span>
                        <span class="timestamp">{{ message['timestamp'] }}</span>
                    </div>
                    <p>{{ message['content'] }}</p>
                </div>
                {% endfor %}
            </div>
            
            <form class="message-form" id="messageForm">
                <input type="text" id="messageInput" placeholder="Écrivez un message..." required>
                <button type="submit"><i class="fas fa-paper-plane"></i></button>
            </form>
        </div>
    </main>
    
    <script>
        const groupId = {{ group.group_id }};
        
        document.getElementById('messageForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const input = document.getElementById('messageInput');
            const content = input.value;
            
            if (!content.trim()) return;
            
            const response = await fetch('/send_group_message', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    group_id: groupId,
                    content: content
                })
            });
            
            if (response.ok) {
                input.value = '';
                const data = await response.json();
                
                const messagesDiv = document.getElementById('messages');
                const messageDiv = document.createElement('div');
                messageDiv.className = 'message sent';
                messageDiv.innerHTML = `
                    <div class="message-header">
                        <span class="sender">${data.username}</span>
                        <span class="timestamp">${data.timestamp}</span>
                    </div>
                    <p>${data.content}</p>
                `;
                messagesDiv.appendChild(messageDiv);
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
            }
        });
        
        setInterval(async () => {
            const response = await fetch('/get_group_messages?group_id=' + groupId);
            if (response.ok) {
                const messages = await response.json();
                const messagesDiv = document.getElementById('messages');
                messagesDiv.innerHTML = messages.map(msg => `
                    <div class="message ${msg.sender_id == {{ session['user_id'] }} ? 'sent' : 'received'}">
                        <div class="message-header">
                            <span class="sender">${msg.username}</span>
                            <span class="timestamp">${msg.timestamp}</span>
                        </div>
                        <p>${msg.content}</p>
                    </div>
                `).join('');
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
            }
        }, 2000);
        
        function logout() {
            window.location.href = '/logout';
        }
        
        function toggleTheme() {
            alert('Fonctionnalité à implémenter');
        }
    </script>
</body>
</html>
    """, group=group, messages=messages)


@app.route("/send_group_message", methods=["POST"])
def send_group_message():
    if "user_id" not in session:
        return jsonify({"error": "Non autorisé"}), 401
    
    data = request.get_json()
    group_id = data.get("group_id")
    content = data.get("content")
    
    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute("SELECT * FROM group_members WHERE group_id = ? AND user_id = ?", 
                   (group_id, session["user_id"]))
    if not cursor.fetchone():
        conn.close()
        return jsonify({"error": "Non autorisé"}), 401
    
    cursor.execute("INSERT INTO messages (group_id, sender_id, content) VALUES (?, ?, ?)", 
                   (group_id, session["user_id"], content))
    conn.commit()
    
    cursor.execute('''
        SELECT m.message_id, m.sender_id, m.content, m.timestamp, u.username
        FROM messages m
        JOIN users u ON m.sender_id = u.user_id
        WHERE m.message_id = ?
    ''', (cursor.lastrowid,))
    message = cursor.fetchone()
    conn.close()
    
    return jsonify({
        "message_id": message["message_id"],
        "sender_id": message["sender_id"],
        "content": message["content"],
        "timestamp": message["timestamp"],
        "username": message["username"]
    })


@app.route("/get_group_messages")
def get_group_messages():
    group_id = request.args.get("group_id")
    if not group_id or "user_id" not in session:
        return jsonify([])
    
    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute("SELECT * FROM group_members WHERE group_id = ? AND user_id = ?", 
                   (group_id, session["user_id"]))
    if not cursor.fetchone():
        conn.close()
        return jsonify([])
    
    cursor.execute('''
        SELECT m.message_id, m.sender_id, m.content, m.timestamp, u.username
        FROM messages m
        JOIN users u ON m.sender_id = u.user_id
        WHERE m.group_id = ?
        ORDER BY m.timestamp ASC
    ''', (group_id,))
    messages = cursor.fetchall()
    conn.close()
    
    return jsonify([{
        "message_id": message["message_id"],
        "sender_id": message["sender_id"],
        "content": message["content"],
        "timestamp": message["timestamp"],
        "username": message["username"]
    } for message in messages])


@app.route("/logout")
def logout():
    session.clear()
    return redirect(url_for("login"))


# --- Lancement du serveur ---
if __name__ == "__main__":
    init_db()
    app.run(host=HOST, port=PORT, debug=True)