<?php
/**
 * ============================================================================
 * chat/upload-file.php - Upload File API
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

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

// Check if user is logged in
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit();
}

$userId = getUserId();
$chatId = isset($_POST['chat_id']) ? (int)$_POST['chat_id'] : 0;

// Validate chat access
if (!$chatId) {
    echo json_encode(['success' => false, 'error' => 'Invalid chat']);
    exit();
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $chatClass = new \App\Chat($db);
    
    // Verify user is a member of the chat
    if (!$chatClass->isMember($chatId, $userId)) {
        echo json_encode(['success' => false, 'error' => 'Access denied']);
        exit();
    }
    
    // Check if file was uploaded
    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'error' => 'No file uploaded']);
        exit();
    }
    
    $file = $_FILES['file'];
    
    // Validate file size (5MB max)
    $maxSize = 5 * 1024 * 1024; // 5MB
    if ($file['size'] > $maxSize) {
        echo json_encode(['success' => false, 'error' => 'File too large (max 5MB)']);
        exit();
    }
    
    // Determine file type
    $mimeType = $file['type'];
    $fileType = 'document';
    
    if (strpos($mimeType, 'image/') === 0) {
        $fileType = 'image';
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    } else {
        $allowedTypes = [
            'application/pdf',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ];
    }
    
    if (!in_array($mimeType, $allowedTypes)) {
        echo json_encode(['success' => false, 'error' => 'File type not allowed']);
        exit();
    }
    
    // Generate unique filename
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = uniqid('chat_') . '_' . time() . '.' . $extension;
    
    // Create upload directory if it doesn't exist
    $uploadDir = __DIR__ . '/../assets/uploads/chat/';
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    $uploadPath = $uploadDir . $filename;
    
    // Move uploaded file
    if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
        $fileUrl = APP_URL . '/assets/uploads/chat/' . $filename;
        
        echo json_encode([
            'success' => true,
            'file_url' => $fileUrl,
            'file_type' => $fileType,
            'file_name' => $file['name']
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to save file']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>