<?php

namespace App\Http\Controllers;

use App\Models\Course;
use App\Models\Level;
use App\Models\Period;
use App\Models\Rhythm;
use App\Models\Student;
use App\Traits\FiltersSearchableLevels;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\QueryBuilder;

class CourseController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->middleware('permission:courses.view');
    }

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): View
    {
        $defaultPeriod = Period::get_default_period();
        $rhythms = Rhythm::all();
        $levels = Level::all();
        $isAllowedToEdit = backpack_user()->hasPermissionTo('courses.edit') ? 1 : 0;
        $mode = $request->mode ?? 'view';
        $student = Student::with('enrollments')->find($request->student_id) ?? collect(['']);
        $enrollment_id = $request->enrollment_id ?? 'none';

        $filters = session()->get('courses.filters', []);

        return view(
            'courses.list',
            compact('defaultPeriod', 'isAllowedToEdit', 'rhythms', 'levels', 'mode', 'student', 'enrollment_id', 'filters')
        );
    }

    public function search()
    {
        session()->put('courses.filters', request('filter'));

        return QueryBuilder::for(Course::class)->whereNull('partner_id')
        ->with('room')->withCount('events')->withCount('children')->withCount('enrollments')
        ->allowedFilters([
            'name',
            AllowedFilter::exact('period_id'),
            AllowedFilter::exact('rhythm_id'),
            AllowedFilter::custom('searchable_levels', new FiltersSearchableLevels()),
            AllowedFilter::exact('teacher_id'),
        ])
        ->get();
    }

    public function redirectToUserPreferredView()
    {
        return match (backpack_user()->preferred_course_view) {
            'blocks' => redirect(route('get-courses-list')),
            default => redirect(route('course.index')),
        };
    }

    public function switchViews(Request $request): RedirectResponse
    {
        switch ($request->view) {
            case 'blocks':
                backpack_user()->update(['preferred_course_view' => 'blocks']);

                return redirect(route('get-courses-list'));

            default:
                backpack_user()->update(['preferred_course_view' => 'list']);

                return redirect(route('course.index'));
        }
    }
}
