<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreExamRequest;
use App\Http\Requests\UpdateExamRequest;
use App\Jobs\MailNotificationQueue;
use App\Models\ClassRoom;
use App\Models\Exam;
use App\Models\Option;
use App\Models\Question;
use App\Models\StudentSubscribe;
use App\Models\UploadedExam;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ExamController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($type)
    {
        $rooms = ClassRoom::active()->get();
        $exams = Exam::with('questions', 'room')->get()->map(function ($item) {
            $item->count_questions = $item->questions->count();
            return $item;
        });
        return view('exams.list')->with(['exams'=> $exams,'rooms'=>$rooms]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $rooms = ClassRoom::active()->get();
        return view('exams.add_exams')->with('rooms', $rooms);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StoreExamRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreExamRequest $request)
    {
        //    return $request;
        $request->validate([
            'typeExams' => 'required',
            'roomClass' => 'required',
            'expireTime' => 'required',
        ], [
            'typeExams.required' => 'يرجى اختيار نوع الاختبار .',
            'roomClass.required' => 'يرجى إختيار الجموعة  .',
            'expireTime.required' => 'يرجى تحديد وقت وتاريخ الإنتهاء .']);
        try {
            $students = StudentSubscribe::where('room_id', $request->roomClass)->get()->map(function ($item) {
                return $item->student;
            });
            $room = ClassRoom::find($request->roomClass);

            $newExam = new Exam();
            $newExam->room_id = $request->roomClass;
            $newExam->type = $request->typeExams;
            $newExam->expire = $request->expireTime;
            $newExam->save();

            $this->saveQuestion($newExam->id,
                $request->quation,
                $request->aneswerSelect,
                $request->typeQuation,
                $request->mark,
                $request->option);
            //called method send notification student
            $this->sendNotificationExam($students, $newExam->type, $room->name, $room->course->title, $newExam->id);
            return redirect()->route('exam_list', $request->roomClass)->with(['success' => 'تم   إضافة الإختبار بنجاح']);
        } catch (\Throwable$th) {
            return redirect()->route('exam_list', $request->roomClass)->with(['error' => 'لم يتم إضافة الإختبار  ']);
        }

    }

    /**
     * [This function will be used
     * to store question in question table
     * ]
     *
     * @param mixed $examId
     * @param mixed $question
     * @param mixed $answerSelect
     * @param mixed $typeQuestion
     * @param mixed $mark
     * @param mixed $options
     *
     * @return [bool]
     *
     */
    public function saveQuestion($examId, $question, $answerSelect, $typeQuestion, $mark, $options)
    {
        try {
            for ($i = 0; $i < count($question); $i++) {

                $newQuestion = new Question();
                $newQuestion->exam_id = $examId;
                $newQuestion->question_txt = $question[$i];
                $newQuestion->type = $typeQuestion[$i];
                $newQuestion->mark = $mark[$i];
                $newQuestion->save();
                $questionId = $newQuestion->id;
                $answerId = $this->saveOption($questionId, $options[$i], $answerSelect[$i]);
                $newQuestion->correct_answer_id = $answerId;
                $newQuestion->update();
            }
            return true;
        } catch (\Throwable$th) {
            return false;
        }
    }
    public function saveOption($questionId, $options, $answerSelect)
    {
        $answerId = 0;
        for ($i = 0; $i < count($options); $i++) {
            $newOption = new Option();
            $newOption->answer = $options[$i];
            $newOption->question_id = $questionId;
            $newOption->save();
            if ($i == $answerSelect[0]) {
                $answerId = $newOption->id;
            }
        }
        return $answerId;
    }
    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Exam  $exam
     * @return \Illuminate\Http\Response
     */
    public function show($examId)
    {
        try {
            // get new date tame using carbon api
            $now = Carbon::now();
            $exam = Exam::where('is_active', 1)->with('questions')->find($examId);

            // check if exam is expired or ont
            if ($now->addHour(3) >= $exam->expire) {
                return redirect()->route('user_dash')->with(['info' => 'عذرا هذا الاختبار انتهى وقت تسليمه']);
            }

            // check if student is answered this exam
            $is_answered = UploadedExam::where('subscribe_id', Auth::id())->where('exam_id', $examId)->first();
            if (isset($is_answered)) {
                return redirect()->route('user_dash')->with(['info' => 'لقد تجاوزت هذا الاختبار']);
            }
            return view('exams.page_exam')->with([
                'exam' => $exam,
            ]);
        } catch (\Throwable$th) {
            return back()->with('error', 'عذرا هناك خطأ لا يمكن فتح هذا الاختبار');
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Exam  $exam
     * @return \Illuminate\Http\Response
     */
    public function edit(Exam $exam)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\UpdateExamRequest  $request
     * @param  \App\Models\Exam  $exam
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateExamRequest $request, Exam $exam)
    {
        // return $request;
        try{
        $updateExam =  Exam::find($request->id);
        $updateExam->room_id = $request->roomClass;
        $updateExam->type = $request->typeExams;
        $updateExam->expire = $request->expireTime;
        $updateExam->save();
        return back()->with(['success' => 'تمت تحديث البيانات بنجاح']);
    } catch (\Throwable$th) {
        return back()->with(['error' => 'لم يتم تحديث البيانات']);
    }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Exam  $exam
     * @return \Illuminate\Http\Response
     */
    public function destroy(Exam $exam,Request $request)
    {
        try {
            Exam::find($request->id)->delete();
            return back()->with(['success' => 'تمت حذف الاختبار بنجاح']);
        } catch (\Throwable$th) {
            return back()->with(['error' => 'لم يتم حذف الاختبار ']);
        }
    }
    /**
     * [Description for sendNotificationExam]
     *
     * @param mixed $students
     * @param mixed $typeExam
     * @param mixed $roomName
     * @param mixed $courseName
     * @param mixed $examId
     *
     * @return [boolean]
     *
     */
    public function sendNotificationExam($students, $typeExam, $roomName, $courseName, $examId)
    {
        $type = '';
        if ($typeExam == 0) {
            $type = ' قبلي ';
        } else if ($typeExam == 1) {
            $type = ' بعدي ';
        } else {
            $type = ' اجتياز ';
        }

        try {
            foreach ($students as $student) {
                $content = 'مرحبا ' . $student->name . ' لقد تم   إضافة اختبار  ' . $type . ' في  ' . $roomName . ' لبرنامج ' . $courseName;
                $route = 'exam_show/'.$examId;
                $email = $student->email; //change to $student->email;
                $subjectEmail = '  اختبار ';

                NotificationController::sendNotificationFromAdmin($student->id, $content, $route, 3);
                try {
                    MailNotificationQueue::dispatch($content, $route, $email, $subjectEmail);
                } catch (\Throwable$th) {
                    return back()->with(['warning' => 'لم يتم إسال الإيميلات']);
                }

            }
            return true;
        } catch (\Throwable$th) {
            return false;
        }
    }
    public function toggle(Request $request)
    {
        try {
            $Exam = Exam::find($request->id);
            $Exam->is_active *= -1;
            $Exam->save();
            return back()->with(['success' => 'تمت تحديث البيانات بنجاح']);
        } catch (\Throwable$th) {
            return back()->with(['error' => 'لم يتم تحديث البيانات']);
        }
    }
}
