<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Course;
use App\Models\Material;
use App\Models\PastQuestion;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;

class MaterialController extends Controller
{
    public function index(Request $request): View|\Illuminate\Http\JsonResponse
    {
        if ($request->boolean('ajax')) {
            if ($request->tab === 'past_questions') {
                $pastQuestions = PastQuestion::with('course')
                    ->withCount('questions')
                    ->where('is_active', true)
                    ->when($request->course_id, fn ($q) => $q->where('course_id', $request->course_id))
                    ->when($request->year, fn ($q) => $q->where('year', $request->year))
                    ->when($request->search, function ($q) use ($request) {
                        $search = $request->search;

                        $q->where(function ($query) use ($search) {
                            $query->where('title', 'like', "%{$search}%")
                                ->orWhere('description', 'like', "%{$search}%")
                                ->orWhere('year', 'like', "%{$search}%")
                                ->orWhere('batch', 'like', "%{$search}%")
                                ->orWhereHas('course', function ($courseQuery) use ($search) {
                                    $courseQuery->where('name', 'like', "%{$search}%");
                                });
                        });
                    })
                    ->orderByDesc('year')
                    ->latest()
                    ->limit(50)
                    ->get()
                    ->map(fn ($item) => [
                        'id' => $item->id,
                        'title' => $item->title ?? ($item->course?->name . ' Past Questions'),
                        'description' => $item->description,
                        'course' => $item->course?->name,
                        'year' => $item->year,
                        'batch' => $item->batch,
                        'questions_count' => $item->questions_count,
                        'url' => route('user.past-questions.show', $item),
                    ]);

                return response()->json([
                    'past_questions' => $pastQuestions,
                    'materials' => [],
                ]);
            }

            $materials = Material::with('course')
                ->where('is_active', true)
                ->when($request->course_id, fn ($q) => $q->where('course_id', $request->course_id))
                ->when($request->type, fn ($q) => $q->where('type', $request->type))
                ->when($request->search, function ($q) use ($request) {
                    $search = $request->search;

                    $q->where(function ($query) use ($search) {
                        $query->where('title', 'like', "%{$search}%")
                            ->orWhere('description', 'like', "%{$search}%")
                            ->orWhere('type', 'like', "%{$search}%")
                            ->orWhereHas('course', function ($courseQuery) use ($search) {
                                $courseQuery->where('name', 'like', "%{$search}%");
                            });
                    });
                })
                ->latest()
                ->limit(50)
                ->get()
                ->map(fn ($item) => [
                    'id' => $item->id,
                    'title' => $item->title,
                    'description' => $item->description,
                    'course' => $item->course?->name,
                    'type' => strtoupper($item->type ?? 'pdf'),
                    'is_premium' => (bool) $item->is_premium,
                    'url' => ($item->type === 'link' && $item->external_url)
                        ? $item->external_url
                        : asset($item->file_path),
                ]);

            return response()->json([
                'materials' => $materials,
                'past_questions' => [],
            ]);
        }

        $courses = Course::where('is_active', true)
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        return view('user.materials.index', compact('courses'));
    }

    public function show(Material $material): View
    {
        $material->load('course');

        return view('user.materials.show', compact('material'));
    }

    public function download(Material $material): StreamedResponse
    {
        return Storage::download($material->file_path, $material->file_name ?? basename($material->file_path));
    }
}