<?php
session_start();
include 'db_config.php'; 
if (!isset($_SESSION['user_id'])) {
    header('Location: login.html');
    exit();
}

$user_id = $_SESSION['user_id'];

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["profilePhoto"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

if (isset($_POST["submit"])) {
    $check = getimagesize($_FILES["profilePhoto"]["tmp_name"]);
    if ($check !== false) {
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

if ($_FILES["profilePhoto"]["size"] > 5000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

$allowed_formats = ['jpg', 'jpeg', 'png', 'gif'];
if (!in_array($imageFileType, $allowed_formats)) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}

if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
} else {
    if (move_uploaded_file($_FILES["profilePhoto"]["tmp_name"], $target_file)) {
        $stmt = $conn->prepare("UPDATE users SET profile_photo_url = ? WHERE id = ?");
        $stmt->bind_param("si", $target_file, $user_id);

        if ($stmt->execute()) {
            echo "The file ". basename($_FILES["profilePhoto"]["name"]). " has been uploaded.";
            header('Location: account.php'); 
        } else {
            echo "Sorry, there was an error updating your profile photo.";
        }
        $stmt->close();
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

$conn->close();
?>