<?php
header('Content-Type: application/json');

// Check if file and user_id are present
if (!isset($_FILES['file']) || !isset($_POST['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit;
}

$userId = $_POST['user_id'];
$file = $_FILES['file'];

// Validate user ID
if (empty($userId)) {
    echo json_encode(['success' => false, 'message' => 'Invalid user ID']);
    exit;
}

// Validate file
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
$maxFileSize = 5 * 1024 * 1024; // 5MB

if (!in_array($file['type'], $allowedTypes)) {
    echo json_encode(['success' => false, 'message' => 'Invalid file type. Only images, PDFs, and Word documents are allowed.']);
    exit;
}

if ($file['size'] > $maxFileSize) {
    echo json_encode(['success' => false, 'message' => 'File too large. Maximum size is 5MB.']);
    exit;
}

// Create uploads directory if it doesn't exist
$uploadDir = 'uploads/';
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// Create user-specific directory
$userDir = $uploadDir . $userId . '/';
if (!file_exists($userDir)) {
    mkdir($userDir, 0755, true);
}

// Generate unique filename
$fileExt = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = uniqid('doc_') . '.' . $fileExt;
$filePath = $userDir . $filename;

// Move uploaded file
if (move_uploaded_file($file['tmp_name'], $filePath)) {
    // Update JSON file
    $jsonFile = 'data.json';
    $jsonData = file_exists($jsonFile) ? json_decode(file_get_contents($jsonFile), true) : [];
    
    if (isset($jsonData[$userId])) {
        // Update document path in user's main data
        $jsonData[$userId]['main']['document_path'] = $filePath;
        
        // Save the updated JSON
        if (file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT))) {
            echo json_encode(['success' => true, 'message' => 'File uploaded and user record updated successfully']);
        } else {
            // File uploaded but JSON update failed
            echo json_encode(['success' => false, 'message' => 'File uploaded but failed to update user record']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'User not found in data file']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to upload file']);
}
?>