<?php
session_start();
$conn = new mysqli("localhost", "kkfxoaad", "Bitok@2025", "kkfxoaad_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)) {
      $_SESSION['profile_pic'] = $newName;

      $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();
