<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\CodeRequest;
use App\Jobs\GenerateCodes;
use App\Models\Code;
use App\Models\Department;
use App\Models\Settings;
use Illuminate\Support\Facades\DB;
use Exception;

class CodeController extends Controller
{
    /**
     * Route used for the admin navigation bar.
     * Redirects to the first department's codes page.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function first()
    {
        return redirect()->route('admin.departments.codes.index', Department::firstOrFail()->id);
    }

    /**
     * Display a listing of the resource.
     *
     * @param \App\Models\Department $department
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Department $department)
    {
        $codes = $department->codes()
                            ->orderBy('semester')
                            ->orderBy('code')
                            ->get()
                            ->groupBy('semester');

        $totalAvailableCodes = $department->codes()->available()->count();
        $totalUsedCodes = $department->codes()->used()->count();

        $departments = Department::all();

        return view('admin.codes.index', compact(
            'department',
            'departments',
            'codes',
            'totalAvailableCodes',
            'totalUsedCodes'
        ));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @param \App\Models\Department $department
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create(Department $department)
    {
        $departments = Department::orderBy('name')
                                 ->get()
                                 ->mapWithKeys(function (Department $department) {
                                     return [$department->id => $department->name];
                                 });

        return view('admin.codes.create', compact('department'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \App\Http\Requests\Admin\CodeRequest $request
     * @param \App\Models\Department $department
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(CodeRequest $request, Department $department)
    {
        GenerateCodes::dispatch(
            $department,
            $request->get('semester'),
            $request->get('batch')
        );

        return redirect()->route('admin.departments.codes.index', $department->id)->with('success', 'Кодови успешно генерисани.');
    }

    public function publish()
    {
        Settings::set(Code::CODES_PUBLIC_SETTING, true);

        return redirect()->back()
            ->with('success', 'Страница са кодовима је објављена.');
    }

    public function delete(Department $department)
    {

        DB::table("codes")
            ->where("used", "=", 0)
            ->where("department_id", "=", $department->id)
            ->delete();
        
        return redirect()->back()
            ->with('success', 'Сви неискоришћени кодови за студијски програм ' . $department->name . ' су успешно обрисани.');
       
    }

    public function hide()
    {
        Settings::set(Code::CODES_PUBLIC_SETTING, false);

        return redirect()->back()
            ->with('success', 'Страница са кодовима је сакривена.');
    }

    /**
     * @param \App\Models\Department $department
     * @param $semester
     * @return \Illuminate\View\View
     */
    public function print(Department $department, $semester)
    {
        return view('admin.codes.print', [
            'department' => $department,
            'semester' => $semester,
            'codes' => $department->codes()->forSemester($semester)->get(),
        ]);
    }
}
