<?php
/**
 * File Upload API
 * Handles file uploads for studies, publications, profiles
 */

header('Content-Type: application/json');
require_once '../config/config.php';

// Check if user is logged in
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$userId = getCurrentUserId();
$method = $_SERVER['REQUEST_METHOD'];

if ($method !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

try {
    // Check if file was uploaded
    if (!isset($_FILES['file'])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'No file uploaded']);
        exit;
    }
    
    $file = $_FILES['file'];
    $uploadType = isset($_POST['type']) ? sanitize($_POST['type']) : 'general'; // general, profile, study, publication
    $relatedId = isset($_POST['related_id']) ? (int)$_POST['related_id'] : null;
    
    // Check for upload errors
    if ($file['error'] !== UPLOAD_ERR_OK) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'File upload error']);
        exit;
    }
    
    // Check file size
    if ($file['size'] > MAX_FILE_SIZE) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'File too large. Maximum size: ' . (MAX_FILE_SIZE / 1048576) . 'MB']);
        exit;
    }
    
    // Get file extension
    $fileName = $file['name'];
    $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    
    // Check if file type is allowed
    if (!in_array($fileExt, ALLOWED_FILE_TYPES)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'File type not allowed']);
        exit;
    }
    
    // Generate unique filename
    $newFileName = uniqid() . '_' . time() . '.' . $fileExt;
    
    // Determine upload directory based on type
    $uploadDir = UPLOADS_PATH . '/' . $uploadType . '/';
    
    // Create directory if it doesn't exist
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    $uploadPath = $uploadDir . $newFileName;
    
    // Move uploaded file
    if (!move_uploaded_file($file['tmp_name'], $uploadPath)) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to save file']);
        exit;
    }
    
    // Save file info to database
    $db = getDB();
    $stmt = $db->prepare("
        INSERT INTO uploads (user_id, filename, original_filename, file_path, file_size, file_type, upload_type, related_id)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    $filePath = $uploadType . '/' . $newFileName;
    $stmt->execute([
        $userId,
        $newFileName,
        $fileName,
        $filePath,
        $file['size'],
        $fileExt,
        $uploadType,
        $relatedId
    ]);
    
    $uploadId = $db->lastInsertId();
    
    // Log activity
    logActivity('file_uploaded', 'uploads', $uploadId, null, [
        'filename' => $fileName,
        'type' => $uploadType
    ]);
    
    echo json_encode([
        'success' => true,
        'message' => 'File uploaded successfully',
        'upload_id' => $uploadId,
        'filename' => $newFileName,
        'original_filename' => $fileName,
        'file_path' => $filePath,
        'file_url' => UPLOADS_URL . '/' . $filePath,
        'file_size' => $file['size'],
        'file_type' => $fileExt
    ]);
    
} catch (Exception $e) {
    error_log("Upload API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal server error']);
}
?>
