<?php

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

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

class LibraryController extends Controller
{
    /**
     * Get library content (quizzes or flashcards)
     * 
     * @param Request $request
     * @param string $type - 'quiz' or 'flashcard'
     * @return \Illuminate\Http\JsonResponse
     */
    public function getLibrary(Request $request, $type)
    {
        try {
            $user = $request->user();
            
            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized'
                ], 401);
            }
            
            // Validate type parameter
            if (!in_array($type, ['quiz', 'flashcard'])) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid type. Use quiz or flashcard'
                ], 400);
            }
            
            // Build query to fetch library items
            $query = DB::table('lms_course_lessons')
                ->join('lms_course_sections', 'lms_course_lessons.section_id', '=', 'lms_course_sections.id')
                ->join('lms_courses', 'lms_course_sections.course_id', '=', 'lms_courses.id')
                ->select(
                    'lms_course_lessons.id',
                    'lms_course_lessons.title',
                    'lms_courses.title as course_name',
                    'lms_courses.id as course_id',
                    'lms_course_lessons.passing_score',
                    'lms_course_lessons.questions',
                    'lms_course_lessons.flashcards',
                    'lms_course_lessons.created_at',
                    'lms_course_lessons.updated_at'
                )
                ->where('lms_course_lessons.type', $type)
                ->where('lms_courses.created_by', $user->id);
            
            // Filter based on type
            if ($type === 'quiz') {
                $query->whereNotNull('lms_course_lessons.questions')
                      ->whereRaw('JSON_LENGTH(lms_course_lessons.questions) > 0');
            } else {
                $query->whereNotNull('lms_course_lessons.flashcards')
                      ->whereRaw('JSON_LENGTH(lms_course_lessons.flashcards) > 0');
            }
            
            $items = $query->orderBy('lms_course_lessons.created_at', 'desc')->get();
            
            // Parse JSON fields and clean up response
            $items = $items->map(function ($item) use ($type) {
                if ($type === 'quiz') {
                    // Parse questions JSON
                    $item->questions = $item->questions ? json_decode($item->questions, true) : [];
                    // Remove flashcards field from response
                    unset($item->flashcards);
                } else {
                    // Parse flashcards JSON
                    $item->flashcards = $item->flashcards ? json_decode($item->flashcards, true) : [];
                    // Remove questions and passing_score from response
                    unset($item->questions);
                    unset($item->passing_score);
                }
                
                return $item;
            });
            
            Log::info("Library fetch successful", [
                'type' => $type,
                'user_id' => $user->id,
                'count' => $items->count()
            ]);
            
            return response()->json([
                'success' => true,
                'data' => $items
            ]);
            
        } catch (\Exception $e) {
            Log::error("Library fetch failed", [
                'type' => $type,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch library content',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }
}
