<?php

namespace App\Http\Controllers\Api\V1\Lms;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class FileUploadController extends Controller
{
    /**
     * Upload file for lesson attachments and course resources.
     */
    public function upload(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                'file' => 'required|file|max:51200', // 50MB max
                'type' => 'required|string|in:lesson_attachment,assignment_attachment,course_resource',
            ]);

            $file = $request->file('file');
            $type = $request->input('type');
            
            // Get file extension
            $extension = $file->getClientOriginalExtension();
            
            // Allowed file types
            $allowedExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'zip', 'jpg', 'jpeg', 'png', 'gif', 'mp4', 'mov'];
            
            if (!in_array(strtolower($extension), $allowedExtensions)) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'File type not allowed. Allowed types: ' . implode(', ', $allowedExtensions),
                ], 422);
            }
            
            // Generate unique filename
            $originalName = $file->getClientOriginalName();
            $filename = Str::slug(pathinfo($originalName, PATHINFO_FILENAME)) . '-' . time() . '.' . $extension;
            
            // Store file based on type
            $folder = match($type) {
                'lesson_attachment' => 'lms/lesson-attachments',
                'assignment_attachment' => 'lms/assignment-attachments',
                'course_resource' => 'lms/course-resources',
                default => 'lms/uploads',
            };
            
            $path = $file->storeAs($folder, $filename, 'public');
        
            // Generate the full URL
            $url = asset('storage/' . $path);

            return response()->json([
                'status' => 'success',
                'data' => [
                    'url' => $url,
                    'path' => $path,
                    'filename' => $filename,
                    'original_name' => $originalName,
                    'size' => $file->getSize(),
                    'mime_type' => $file->getMimeType(),
                ],
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed',
                'errors' => $e->errors(),
            ], 422);
        } catch (\Exception $e) {
            Log::error('File upload error: ' . $e->getMessage(), [
                'file' => $request->file('file')?->getClientOriginalName(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'status' => 'error',
                'message' => 'File upload failed: ' . $e->getMessage(),
            ], 500);
        }
    }
}
