<?php
require_once '../config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Only POST method allowed', null, 405);
}

try {
    $user = validateToken($conn);
    
    if (!isset($_FILES['profile_image']) || $_FILES['profile_image']['error'] !== UPLOAD_ERR_OK) {
        sendResponse(false, 'No image file uploaded or upload error', null, 400);
    }
    
    $uploadDir = __DIR__ . '/../../kumawat/uploads/profile/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    $file = $_FILES['profile_image'];
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $maxSize = 2 * 1024 * 1024; // 2MB
    
    // Validate file type
    if (!in_array($file['type'], $allowedTypes)) {
        sendResponse(false, 'Invalid file type. Only JPEG, PNG, GIF, and WebP are allowed', null, 400);
    }
    
    // Validate file size
    if ($file['size'] > $maxSize) {
        sendResponse(false, 'File size too large. Maximum 2MB allowed', null, 400);
    }
    
    // Generate unique filename
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = 'profile_' . $user['id'] . '_' . time() . '.' . $ext;
    $filepath = $uploadDir . $filename;
    
    // Move uploaded file
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        $imageUrl = 'uploads/profile/' . $filename;
        
        // Update user profile image in database
        $stmt = $conn->prepare("UPDATE users SET profile_image = ? WHERE id = ?");
        $stmt->bind_param("si", $imageUrl, $user['id']);
        
        if ($stmt->execute()) {
            sendResponse(true, 'Profile image uploaded successfully', [
                'filename' => $filename,
                'url' => $imageUrl,
                'size' => $file['size'],
                'type' => $file['type']
            ]);
        } else {
            // Delete uploaded file if database update fails
            unlink($filepath);
            sendResponse(false, 'Failed to update profile image in database', null, 500);
        }
    } else {
        sendResponse(false, 'Failed to upload image', null, 500);
    }
    
} catch (Exception $e) {
    sendResponse(false, 'Upload failed: ' . $e->getMessage(), null, 500);
}
?>
