<?php

namespace App\Modules\Timetable\Http\Controllers;

use App\Facades\General;
use App\Modules\Staff\Model\Staff;
use App\Modules\Student\Model\Section;
use App\Modules\Student\Model\StudentClass;
use App\Modules\Student\Model\Subject;
use App\Modules\Student\Model\Student;
use App\Modules\Timetable\Model\Timetable;
use App\Modules\Timetable\Requests\StoreTimetable;
use Exception;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use Illuminate\View\View;

class TimetableController extends Controller
{
    /**
     * Module variable
     *
     * @var array
     */
    protected $moduleName;

    /**
     * Class Constructor.
     *
     * @return string
     */
    public function __construct()
    {
        $this->moduleName = $this->getModuleName();
    }

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function index(Request $request)
    {
        $data['studentClasses'] = StudentClass::getStudentClasses();
        $data['sections']       = Section::getSections();
        $data['weekDay']        = General::getWeekDays();
        $data['subjects']       = Subject::getSubjects();
        $data['teachers']       = Staff::getTeachers();

        General::userLog('SL000901', ['action_module' => $this->moduleName]);

        return View('timetable::index', ['moduleName' => $this->moduleName, 'data' => $data]);
    }

    /**
     * Teacher timetable
     *
     * @param Request $request
     * @return Factory|View
     */
    public function teacherTimetable(Request $request)
    {

        General::userLog('SL000901', ['action_module' => 'teacher-timetable']);

        return View('timetable::teacher', ['moduleName' => 'teacher-timetable']);
    }

    /**
     * Student table
     *
     * @param Request $request
     * @return Factory|View
     */
    public function studentTimetable(Request $request)
    {

        General::userLog('SL000901', ['action_module' => 'teacher-timetable']);

        return View('timetable::student', ['moduleName' => 'teacher-timetable']);
    }

    /**
     * return the calendar events
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getCalendarEvents(Request $request)
    {
        $scheduledTimeTable = Timetable::getScheduledEvents($request);

        return response()->json($scheduledTimeTable);
    }

    /**
     * return the calendar events
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getTeacherEvents(Request $request)
    {
        $scheduledTimeTable = Timetable::getScheduledEvents($request);

        return response()->json($scheduledTimeTable);
    }

    /**
     * return the calendar events for student
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getStudentEvents(Request $request)
    {
        $scheduledTimeTable = Timetable::getScheduledEvents($request);

        return response()->json($scheduledTimeTable);
    }

    public function checkAvailability(Request $request)
    {
        if ($request->ajax()) {
            return Timetable::getDatatableTeacherAvailability($request);
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        return View('timetable::createOrUpdate')->with('moduleName', $this->moduleName);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param StoreTimetable $request
     * @return JsonResponse
     */
    public function store(StoreTimetable $request)
    {

        if(!Timetable::validateTeacherAvailability($request)){
            return response()->json(["status" => 'already booked', "status_code" => 202], 202);
        }

        if ($request->ajax()) {
            // Add student details into student table
            $timetable = Timetable::addUpdateTimetable($request);

            Session::flash('success',
                trans('locale.success_add_msg', array('module_name' => ucfirst($this->moduleName))));

            General::userLog('SL000902', [
                'action_module' => $this->moduleName,
                'parent_id'     => $timetable->id,
                'event_data'    => ['name' => $timetable->class_id,
                                    'url'  => route($this->moduleName . '.edit', $timetable->id)]
            ]);

            return response()->json(["status" => 'added', "status_code" => 200], 200);
        }

        return response()->json(["status" => 'Bad request', "status_code" => 401], 401);
    }

    /**
     * Display the specified resource.
     *
     * @param Student $student
     * @return Factory|View
     */
    public function show($student)
    {
       /* $options = array();
        $options['with'] = ["user", "studentClass", "castCategory", "guardian"];
        $student = (new Student())->findById($student, $options);

        General::userLog('SL000904', [
            'action_module' => $this->moduleName,
            'parent_id'     => $student->id,
            'event_data'    => ['name' => $student->user->name,
                                'url'  => route($this->moduleName . '.show', $student->id)]
        ]);

        return View('student::show', compact('student'))->with('moduleName', $this->moduleName);*/
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param $timetable
     * @return JsonResponse
     */
    public function edit($timetable)
    {
        if (request()->ajax()) {
            $data = Timetable::findOrFail($timetable);

            return response()->json(['result' => $data], 200);
        }

        return response()->json(['result' => 'Bad request'], 401);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param $timetable
     * @return JsonResponse
     */
    public function update(Request $request, $timetable)
    {
        if ($request->ajax()) {

            // Validate the slot is available for the teacher
            if(!Timetable::validateTeacherAvailability($request, $timetable)){
                return response()->json(["status" => 'already booked', "status_code" => 202], 202);
            }

            // update timetable details into storage
            $timetable = Timetable::addUpdateTimetable($request, $timetable);

            General::userLog('SL000902', [
                'action_module' => $this->moduleName,
                'parent_id'     => $timetable->id,
                'event_data'    => ['name' => $timetable->class_id,
                                    'url'  => route($this->moduleName . '.edit', $timetable->id)]
            ]);

            return response()->json(["status" => 'updated'], 200);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Student $student
     * @return RedirectResponse
     * @throws Exception
     */
    public function destroy($student)
    {
        $student = (new Student())->findById($student);
        General::userLog('SL000905', [
            'action_module' => $this->moduleName,
            'parent_id'     => $student->id,
            'event_data'    => ['name' => $student->user->name]
        ]);

        Session::flash('success',
            trans('locale.success_delete_msg', array('module_name' => ucfirst($this->moduleName))));
        $student->delete();

        return redirect()->route($this->moduleName . '.index');
    }

    /**
     * Get Module name.
     *
     * @return string
     */
    public function getModuleName()
    {
        return "timetable";
    }
}
