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

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

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Not authenticated'
    ]);
    exit;
}

try {
    $userId = getUserId();
    $chatId = isset($_POST['chat_id']) ? (int)$_POST['chat_id'] : 0;
    
    // Validate chat membership
    if ($chatId) {
        $database = \App\Database::getInstance();
        $db = $database->getConnection();
        
        $chatClass = new \App\Chat($db);
        if (!$chatClass->isMember($chatId, $userId)) {
            http_response_code(403);
            echo json_encode([
                'success' => false,
                'message' => 'You are not a member of this chat'
            ]);
            exit;
        }
    }
    
    // Check if file was uploaded
    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        $error = $_FILES['file']['error'] ?? 'No file uploaded';
        $errorMessages = [
            UPLOAD_ERR_INI_SIZE => 'File exceeds upload_max_filesize',
            UPLOAD_ERR_FORM_SIZE => 'File exceeds MAX_FILE_SIZE',
            UPLOAD_ERR_PARTIAL => 'File was only partially uploaded',
            UPLOAD_ERR_NO_FILE => 'No file was uploaded',
            UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder',
            UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
            UPLOAD_ERR_EXTENSION => 'File upload stopped by extension'
        ];
        
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => $errorMessages[$error] ?? 'File upload error: ' . $error
        ]);
        exit;
    }
    
    $file = $_FILES['file'];
    $fileName = $file['name'];
    $fileSize = $file['size'];
    $fileTmpName = $file['tmp_name'];
    $fileType = $file['type'];
    $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    
    // Define allowed file types
    $allowedImages = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $allowedDocs = ['pdf', 'doc', 'docx', 'xls', 'xlsx'];
    $allowedExtensions = array_merge($allowedImages, $allowedDocs);
    
    // Validate file extension
    if (!in_array($fileExtension, $allowedExtensions)) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Invalid file type. Allowed: ' . implode(', ', $allowedExtensions)
        ]);
        exit;
    }
    
    // Validate file size (10MB max)
    $maxSize = 10 * 1024 * 1024; // 10MB
    if ($fileSize > $maxSize) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'File too large. Maximum size is 10MB'
        ]);
        exit;
    }
    
    // Create upload directory if it doesn't exist
    $uploadDir = __DIR__ . '/../../assets/uploads/chat/';
    if (!file_exists($uploadDir)) {
        if (!mkdir($uploadDir, 0755, true)) {
            throw new \Exception('Failed to create upload directory');
        }
    }
    
    // Verify directory is writable
    if (!is_writable($uploadDir)) {
        throw new \Exception('Upload directory is not writable: ' . $uploadDir);
    }
    
    // Generate unique filename
    $uniqueName = 'chat_' . uniqid() . '_' . time() . '.' . $fileExtension;
    $uploadPath = $uploadDir . $uniqueName;
    
    // Determine file type
    $isImage = in_array($fileExtension, $allowedImages);
    $messageType = $isImage ? 'image' : 'document';
    
    // Move uploaded file
    if (!move_uploaded_file($fileTmpName, $uploadPath)) {
        throw new \Exception('Failed to move uploaded file');
    }
    
    // Optimize image if needed
    if ($isImage) {
        try {
            $image = null;
            
            switch ($fileExtension) {
                case 'jpg':
                case 'jpeg':
                    $image = imagecreatefromjpeg($uploadPath);
                    break;
                case 'png':
                    $image = imagecreatefrompng($uploadPath);
                    break;
                case 'gif':
                    $image = imagecreatefromgif($uploadPath);
                    break;
                case 'webp':
                    $image = imagecreatefromwebp($uploadPath);
                    break;
            }
            
            if ($image) {
                // Get current dimensions
                $width = imagesx($image);
                $height = imagesy($image);
                
                // Resize if larger than 1200px
                $maxDimension = 1200;
                if ($width > $maxDimension || $height > $maxDimension) {
                    $ratio = $width / $height;
                    
                    if ($width > $height) {
                        $newWidth = $maxDimension;
                        $newHeight = $maxDimension / $ratio;
                    } else {
                        $newHeight = $maxDimension;
                        $newWidth = $maxDimension * $ratio;
                    }
                    
                    $newImage = imagecreatetruecolor($newWidth, $newHeight);
                    
                    // Preserve transparency for PNG and GIF
                    if ($fileExtension == 'png' || $fileExtension == 'gif') {
                        imagecolortransparent($newImage, imagecolorallocatealpha($newImage, 0, 0, 0, 127));
                        imagealphablending($newImage, false);
                        imagesavealpha($newImage, true);
                    }
                    
                    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
                    
                    // Save optimized image
                    switch ($fileExtension) {
                        case 'jpg':
                        case 'jpeg':
                            imagejpeg($newImage, $uploadPath, 85);
                            break;
                        case 'png':
                            imagepng($newImage, $uploadPath, 8);
                            break;
                        case 'gif':
                            imagegif($newImage, $uploadPath);
                            break;
                        case 'webp':
                            imagewebp($newImage, $uploadPath, 85);
                            break;
                    }
                    
                    imagedestroy($newImage);
                }
                
                imagedestroy($image);
            }
            
        } catch (\Exception $e) {
            error_log('Image optimization error: ' . $e->getMessage());
            // Continue even if optimization fails
        }
    }
    
    // Generate URL
    $fileUrl = APP_URL . '/assets/uploads/chat/' . $uniqueName;
    
    // Success response
    echo json_encode([
        'success' => true,
        'file_url' => $fileUrl,
        'file_type' => $messageType,
        'file_name' => $fileName,
        'file_size' => $fileSize
    ]);
    
} catch (\Exception $e) {
    error_log('File upload error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Upload failed: ' . $e->getMessage(),
        'error' => APP_DEBUG ? $e->getTraceAsString() : null
    ]);
}