<?php
// Enhanced upload_handler.php for multiple document management
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_FILES['file'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$user_id = $_POST['user_id'] ?? '';
$document_name = $_POST['document_name'] ?? '';

if (empty($user_id)) {
    echo json_encode(['success' => false, 'message' => 'User ID required']);
    exit;
}

if (empty($document_name)) {
    echo json_encode(['success' => false, 'message' => 'Document name required']);
    exit;
}

// Read the existing data
$jsonFilePath = 'data.json';
if (!file_exists($jsonFilePath)) {
    echo json_encode(['success' => false, 'message' => 'Data file not found']);
    exit;
}

$jsonContent = file_get_contents($jsonFilePath);
$data = json_decode($jsonContent, true);

if (!isset($data[$user_id])) {
    echo json_encode(['success' => false, 'message' => 'User not found']);
    exit;
}

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

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

$file = $_FILES['file'];
$fileExtension = pathinfo($file['name'], PATHINFO_EXTENSION);
$uniqueFileName = 'doc_' . uniqid() . '.' . $fileExtension;
$targetPath = $userDir . $uniqueFileName;

if (move_uploaded_file($file['tmp_name'], $targetPath)) {
    // Initialize document_path array if it doesn't exist
    if (!isset($data[$user_id]['document_path'])) {
        $data[$user_id]['document_path'] = [];
    }
    
    // Add new document to the array
    $newDocument = [
        'name' => $document_name,
        'path' => $targetPath,
        'upload_date' => date('Y-m-d H:i:s'),
        'original_filename' => $file['name']
    ];
    
    $data[$user_id]['document_path'][] = $newDocument;
    
    // Save updated data back to JSON file
    if (file_put_contents($jsonFilePath, json_encode($data, JSON_PRETTY_PRINT))) {
        echo json_encode([
            'success' => true,
            'message' => 'Document uploaded successfully',
            'file_path' => $targetPath,
            'document_name' => $document_name
        ]);
    } else {
        // If JSON save failed, delete the uploaded file
        unlink($targetPath);
        echo json_encode(['success' => false, 'message' => 'Failed to update database']);
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to save file',
        'error' => error_get_last()
    ]);
}
?>