<?php
session_start();
$conn = new mysqli("localhost", "root", "", "bella");

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

$userId = $_SESSION['user_id'];

if (isset($_FILES['profile_pic']) && $_FILES['profile_pic']['error'] === UPLOAD_ERR_OK) {
  $fileTmp = $_FILES['profile_pic']['tmp_name'];
  $fileName = basename($_FILES['profile_pic']['name']);
  $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
  $allowed = ['jpg', 'jpeg', 'png', 'gif'];

  if (in_array($fileExt, $allowed)) {
    $newName = "uploads/profile_$userId." . $fileExt;
    if (move_uploaded_file($fileTmp, $newName)) {
      // Optional: store path in session
      $_SESSION['profile_pic'] = $newName;

      // Optional: Save path to DB
      $stmt = $conn->prepare("UPDATE users SET profile_pic = ? WHERE id = ?");
      $stmt->bind_param("si", $newName, $userId);
      $stmt->execute();
      $stmt->close();
    }
  }
}

$conn->close();
header("Location: profile.php");
exit();
