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

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

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

// Fetch current user data
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

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

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

        if (empty($email)) {
            $error = 'L\'email ne peut pas être vide.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Email invalide.';
        } elseif (!password_verify($current_password, $user['password'])) {
            $error = 'Mot de passe actuel incorrect.';
        } else {
            // Update password if provided
            if (!empty($new_password)) {
                if ($new_password !== $confirm_password) {
                    $error = 'Les nouveaux mots de passe ne correspondent pas.';
                } else {
                    $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                    $stmt = $db->prepare("UPDATE users SET email = ?, password = ? WHERE id = ?");
                    $stmt->execute([$email, $hashed_password, $user_id]);
                    $success = 'Profil et mot de passe mis à jour avec succès.';
                }
            } else {
                $stmt = $db->prepare("UPDATE users SET email = ? WHERE id = ?");
                $stmt->execute([$email, $user_id]);
                $success = 'Profil mis à jour avec succès.';
            }
            
            // Refresh user data
            $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mon Profil - Nexus</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: #000;
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            color: #fff;
            background-image: radial-gradient(circle at 50% 50%, #1a2a4a 0%, #000 70%);
            background-attachment: fixed;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }
        .profile-container {
            background: rgba(10, 15, 30, 0.95);
            border: 1px solid #4c566a;
            padding: 30px;
            width: 100%;
            max-width: 500px;
            box-shadow: 0 0 20px rgba(0,0,0,0.8);
        }
        h2 { text-transform: uppercase; color: #88c0d0; border-bottom: 1px solid #4c566a; padding-bottom: 10px; margin-top: 0; display: flex; align-items: center; gap: 10px; }
        .form-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 5px; color: #8c92a3; font-size: 14px; }
        input { width: 100%; padding: 10px; background: #000; border: 1px solid #4c566a; color: #fff; box-sizing: border-box; }
        .password-section { margin-top: 25px; border-top: 1px solid #2d3545; padding-top: 15px; }
        .password-section h3 { font-size: 14px; text-transform: uppercase; color: #ebcb8b; margin-top: 0; }
        button { width: 100%; padding: 12px; background: #5e81ac; border: none; color: #fff; font-weight: bold; cursor: pointer; text-transform: uppercase; margin-top: 10px; transition: background 0.2s; }
        button:hover { background: #81a1c1; }
        .alert { padding: 10px; margin-bottom: 20px; font-size: 14px; }
        .alert-error { background: rgba(191, 97, 106, 0.2); border: 1px solid #bf616a; color: #bf616a; }
        .alert-success { background: rgba(163, 190, 140, 0.2); border: 1px solid #a3be8c; color: #a3be8c; }
        .nav-links { display: flex; justify-content: space-between; margin-top: 25px; border-top: 1px solid #2d3545; padding-top: 15px; font-size: 13px; }
        .nav-links a { color: #88c0d0; text-decoration: none; }
        .nav-links a:hover { text-decoration: underline; }
        .username-display { font-size: 18px; color: #81a1c1; margin-bottom: 20px; padding: 5px 10px; background: rgba(0,0,0,0.3); border-radius: 4px; display: inline-block; }
    </style>
</head>
<body>
    <div class="profile-container">
        <h2><i class="fa-solid fa-user-gear"></i> Gestion du Compte</h2>
        
        <div class="username-display">
            <i class="fa-solid fa-id-card"></i> @<?php echo htmlspecialchars($user['username']); ?>
        </div>

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

        <form method="POST">
            <input type="hidden" name="action" value="update_profile">
            
            <div class="form-group">
                <label>Adresse Email</label>
                <input type="email" name="email" required value="<?php echo htmlspecialchars($user['email']); ?>">
            </div>

            <div class="password-section">
                <h3>Changer le mot de passe (Optionnel)</h3>
                <div class="form-group">
                    <label>Nouveau mot de passe</label>
                    <input type="password" name="new_password" placeholder="Laisser vide pour ne pas changer">
                </div>
                <div class="form-group">
                    <label>Confirmer le nouveau mot de passe</label>
                    <input type="password" name="confirm_password">
                </div>
            </div>

            <div class="form-group" style="margin-top: 20px;">
                <label>Mot de passe actuel (requis pour valider)</label>
                <input type="password" name="current_password" required>
            </div>

            <button type="submit">Enregistrer les modifications</button>
        </form>

        <div class="nav-links">
            <a href="index.php"><i class="fa-solid fa-arrow-left"></i> Retour au Nexus</a>
            <a href="auth.php?logout=1" style="color: #bf616a;"><i class="fa-solid fa-right-from-bracket"></i> Déconnexion</a>
        </div>
    </div>
</body>
</html>
