<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include '../include/config.php';

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

$patient_id = $_SESSION['patient_id'];

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['profile_photo'])) {
    $target_dir = "../uploads/";
    
    // Create directory if not exists
    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    
    $file_extension = strtolower(pathinfo($_FILES['profile_photo']['name'], PATHINFO_EXTENSION));
    $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    
    if (in_array($file_extension, $allowed)) {
        $new_filename = "patient_" . $patient_id . "_" . time() . "." . $file_extension;
        $target_file = $target_dir . $new_filename;
        
        if (move_uploaded_file($_FILES['profile_photo']['tmp_name'], $target_file)) {
            $profile_path = "uploads/" . $new_filename;
            
            // Check if profile_picture column exists
            $check = $conn->query("SHOW COLUMNS FROM patients LIKE 'profile_picture'");
            if ($check->num_rows == 0) {
                $conn->query("ALTER TABLE patients ADD COLUMN profile_picture VARCHAR(255) DEFAULT NULL");
            }
            
            $stmt = $conn->prepare("UPDATE patients SET profile_picture = ? WHERE patient_id = ?");
            $stmt->bind_param("ss", $profile_path, $patient_id);
            if ($stmt->execute()) {
                $_SESSION['success'] = "Profile picture updated!";
            } else {
                $_SESSION['error'] = "Database update failed.";
            }
            $stmt->close();
        } else {
            $_SESSION['error'] = "Failed to upload image.";
        }
    } else {
        $_SESSION['error'] = "Only JPG, PNG, GIF, WEBP files are allowed.";
    }
}

header("Location: dashboard.php");
exit();
?>