<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

// Step 1: Check if logged in
if (!isset($_SESSION['email'])) {
  exit('Not authorized: No session email.');
}

$email = $_SESSION['email'];
echo "Email: $email<br>";

$targetDir = "profile-pictures/";
$filename = md5($email) . ".jpg";
$targetFile = $targetDir . $filename;

if (!is_dir($targetDir)) {
  mkdir($targetDir, 0755, true);
}

if (!isset($_FILES['profilePic'])) {
  exit("No file uploaded.");
}

if ($_FILES['profilePic']['error'] !== UPLOAD_ERR_OK) {
  exit("Upload error code: " . $_FILES['profilePic']['error']);
}

$tmpName = $_FILES['profilePic']['tmp_name'];
$mimeType = mime_content_type($tmpName);
echo "MIME Type: $mimeType<br>";

if (!in_array($mimeType, ['image/jpeg', 'image/png', 'image/jpg'])) {
  exit("Invalid file type: $mimeType");
}

if (move_uploaded_file($tmpName, $targetFile)) {
  echo "Upload successful.<br>";
  echo "<a href='profile.php'>Go back to profile</a>";
} else {
  exit("Failed to move uploaded file.");
}