<?php
session_start();
if (!isset($_SESSION['nurse_id'])) {
    header("Location: login.php");
    exit();
}
include '../include/config.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['profile_pic'])) {
    $nurse_id = $_SESSION['nurse_id'];
    $upload_dir = '../uploads/';
    
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    $file_extension = strtolower(pathinfo($_FILES['profile_pic']['name'], PATHINFO_EXTENSION));
    $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
    
    if (in_array($file_extension, $allowed_extensions)) {
        $filename = 'nurse_' . $nurse_id . '_' . time() . '.' . $file_extension;
        $filepath = $upload_dir . $filename;
        
        if (move_uploaded_file($_FILES['profile_pic']['tmp_name'], $filepath)) {
            $conn->query("UPDATE nurses SET profile_pic = '$filename' WHERE nurse_id = $nurse_id");
            $_SESSION['success'] = "Profile picture updated successfully!";
        } else {
            $_SESSION['error'] = "Failed to upload image.";
        }
    } else {
        $_SESSION['error'] = "Invalid file type. Only JPG, PNG, GIF allowed.";
    }
    
    header("Location: dashboard.php");
    exit();
}
?>