<?php

namespace App\Http\Controllers;

use App\Facades\UserSurvey;
use App\Models\Code;
use App\Models\Department;
use App\Models\Settings;
use Illuminate\Support\Facades\Auth;

class CodesController extends Controller
{
    public function index()
    {
        if (Auth::user() && UserSurvey::isOngoing()) {
            return UserSurvey::redirectToNextQuestion();
        }

        if (!Settings::get(Code::CODES_PUBLIC_SETTING)) {
            return redirect()->route('home');
        }

        return redirect()->route('codes.showall');
    }

    public function show(Department $department)
    {
        if (Auth::user() && UserSurvey::isOngoing()) {
            return UserSurvey::redirectToNextQuestion();
        }

        if (!Settings::get(Code::CODES_PUBLIC_SETTING)) {
            return redirect()->route('home');
        }
    
       
        $codes = $department->codes()
                            ->available()
                            ->orderBy('semester', 'asc')
                            ->get()
                            ->groupBy('semester');

        return view('codes', [
            'departmentCodes' => $codes,
            'department' => $department,
            'departments' => Department::all(),
        ]);
    }

    public function showall(Department $department)
    {
        if (Auth::user() && UserSurvey::isOngoing()) {
            return UserSurvey::redirectToNextQuestion();
        }

        if (!Settings::get(Code::CODES_PUBLIC_SETTING)) {
            return redirect()->route('home');
        }
    
        $department = new Department();
        $codes = Code::all();

        return view('codes', [
            'departmentCodes' => $codes,
            'department' => $department,
            'departments' => Department::all(),
        ]);
    }

}
