<?php
// /var/www/html/profile.php
session_start();
require_once 'config.php';
include 'header.php';

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

// POST handling (update or delete)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $uploadDir = __DIR__ . '/uploads/profiles/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

    // delete?
    if (isset($_POST['delete_picture'])) {
        // remove file if any
        if (!empty($_SESSION['user']['profile_picture']) && file_exists(__DIR__ . '/' . $_SESSION['user']['profile_picture'])) {
            @unlink(__DIR__ . '/' . $_SESSION['user']['profile_picture']);
        }
        $stmt = $pdo->prepare("UPDATE utilisateurs SET profile_picture = NULL WHERE id = ?");
        $stmt->execute([$userId]);
        $_SESSION['user']['profile_picture'] = null;
        header('Location: profile.php'); exit;
    }

    // update (bio + optional file)
    $bio = trim($_POST['bio'] ?? '');
    $profilePath = $_SESSION['user']['profile_picture'] ?? null;
    if (!empty($_FILES['profile_picture']['name'])) {
        $fname = time() . '_' . preg_replace('/[^A-Za-z0-9_.-]/', '', basename($_FILES['profile_picture']['name']));
        $target = $uploadDir . $fname;
        if (in_array(strtolower(pathinfo($fname, PATHINFO_EXTENSION)), ['jpg','jpeg','png']) && move_uploaded_file($_FILES['profile_picture']['tmp_name'], $target)) {
            $profilePath = 'uploads/profiles/' . $fname;
        } else {
            $message = "❌ Problème lors de l'upload (format jpg/png uniquement).";
        }
    }
    // update DB
    $stmt = $pdo->prepare("UPDATE utilisateurs SET bio = ?, profile_picture = ? WHERE id = ?");
    $stmt->execute([$bio, $profilePath, $userId]);

    // sync session
    $_SESSION['user']['bio'] = $bio;
    $_SESSION['user']['profile_picture'] = $profilePath;
    header('Location: profile.php'); exit;
}

// fetch fresh data
$stmt = $pdo->prepare("SELECT username, bio, profile_picture FROM utilisateurs WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<!-- include the HTML/CSS you prefer (same as earlier). -->
<?php include 'footer.php'; ?>

