<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Exam;
use App\Models\Question;
use App\Models\UploadedExam;
use App\Models\StudentAnswer;
use App\Models\StudentSubscribe;
use App\Jobs\MailNotificationQueue;
use App\Http\Requests\StoreUploadedExamRequest;
use App\Http\Requests\UpdateUploadedExamRequest;

class UploadedExamController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    public function list($roomId)
    {
        $subscriber = StudentSubscribe::where('room_id',$roomId)->first();
        $uploadedExamsIds = UploadedExam::where('subscribe_id',$subscriber->id)->get()->map(function ($item)
        {
            return $item->id;
        })->toArray();

        $examTypes = [
            '0'=>'قبلي',
            '1'=>'بعدي',
            '2'=>'اجتياز',
        ]; 
        $exams = Exam::where('room_id',$roomId)->where('is_active',1)->get()->except($uploadedExamsIds);
        return view('student.exam')->with(['exams'=>$exams,'examTypes'=>$examTypes]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StoreUploadedExamRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreUploadedExamRequest $request)
    {
        // return $request;
        try {
            // get new date tame using carbon api
            $now = Carbon::now();
            $exam = Exam::where('is_active', 1)->find($request->examId);
            $studentSubscribeId = StudentSubscribe::where('room_id',$exam->room->id)->where('student_id',$request->studentId)->first()->id;
            // 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
            $uploadedExam = UploadedExam::where('subscribe_id', $request->studentId)->where('exam_id', $request->examId)->first();
            if (isset($uploadedExam))
                return redirect()->route('user_dash')->with(['info' => 'لقد تجاوزت هذا الاختبار']);

            // save exam that student answered
            $uploadedExam = new UploadedExam();
            $uploadedExam->exam_id = $request->examId;
            $uploadedExam->subscribe_id = $studentSubscribeId;
            $uploadedExam->save();

            // get all exam questions
             $questions = Question::where('exam_id', $request->examId)->where('type', 1)->get();

            // foreach for save all student answers
            foreach ($questions as $question) {
                $studentAnswer = new StudentAnswer();
                $studentAnswer->uploaded_exam_id = $uploadedExam->id;
                $studentAnswer->question_id = $question->id;

                // chick if student is check this answer or save null
                if (isset($request->answer["$question->id"]))
                    $studentAnswer->answer = $request->answer["$question->id"];
                    
                $studentAnswer->save();
                if ($studentAnswer->answer == $question->correct_answer_id)
                    $studentAnswer->mark = $question->mark;
                else
                    $studentAnswer->mark = 0;
                $studentAnswer->update();
            }

             $trainer = $exam->room->trainer;
             $content = ' لقد تم  رفع اختبار جديد في برنامج   ' .$exam->room->name.' في دورة '.$exam->room->course->title;
             $route = 'trainer_dash';
             //end email parameter 
             NotificationController::sendNotificationFromAdmin($trainer->id, $content, $route, 6);
             NotificationController::sendNotificationToAdmin($content,'admin_dash',6);
            if ($exam->type == 2)
                return redirect()->route('evaluation_show', $studentSubscribeId)->with(['success' => 'احسنت :) لقد تم رفع اجابتك بنجاح نتمنا لك كل النجاح... نرجو منك ملئ هذا الاستبيان لمساعدتنا في في تقدم الافضل فرأيك يهمنا']);
            
            return redirect()->route('user_dash')->with(['success' => 'احسنت :) لقد تم رفع اجابتك بنجاح نتمنا لك كل النجاح']);
        } catch (\Throwable $th) {
            return back()->with('error', 'عذرا هناك خطأ لم يتم رفع اجابتك');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\UploadedExam  $uploadedExam
     * @return \Illuminate\Http\Response
     */
    public function show(UploadedExam $uploadedExam)
    {
        //
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\UpdateUploadedExamRequest  $request
     * @param  \App\Models\UploadedExam  $uploadedExam
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateUploadedExamRequest $request, UploadedExam $uploadedExam)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\UploadedExam  $uploadedExam
     * @return \Illuminate\Http\Response
     */
    public function destroy(UploadedExam $uploadedExam)
    {
        //
    }
}
