<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Course;
use App\Models\ClassRoom;
use Illuminate\Http\Request;
use App\Mail\MailNotification;
use App\Models\StudentSubscribe;
use App\Jobs\MailNotificationQueue;
use Illuminate\Support\Facades\Mail;
use App\Http\Requests\StoreClassRoomRequest;
use App\Http\Requests\UpdateClassRoomRequest;

class ClassRoomController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $courses = Course::active()->get();
        $trainers = User::train()->active()->get();
        $coordinators = User::coordinate()->active()->get();
        $rooms = ClassRoom::with('course', 'trainer', 'students')->get();
        return view('class-room.list')->with([
            'rooms' => $rooms,
            'courses' => $courses,
            'trainers' => $trainers,
            'coordinators' => $coordinators
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StoreClassRoomRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreClassRoomRequest $request)
    {
        $newClassRoom = new ClassRoom();
        $request->validate([
            'name' => 'required',
            'place' => 'required',
            'courseId' => 'required|numeric',
            'trainerId' => 'required|numeric',
            'coordinatorId' => 'required|numeric',
        ], [
            'name.required' => 'يرجى ادخال  الإسم',
            'place.required' => 'يرجى ادخال  المكان',
            'courseId.required' => 'يرجى تحديد  البرنامج',
            'trainerId.required' => 'يرجى تحديد  المشرف',
            'coordinatorId.required' => 'يرجى تحديد  المنسق',
        ]);
        try {
            $newClassRoom->name = $request->name;
            $newClassRoom->place = $request->place;
            $newClassRoom->course_id = $request->courseId;
            $newClassRoom->trainer_id = $request->trainerId;
            $newClassRoom->coordinator_id = $request->coordinatorId;
            $newClassRoom->save();
            //send email and notification to trainer to tell him
            $trainer = User::find($newClassRoom->trainer_id);

            //send email and notification to coordinator to tell him
            $coordinator = User::find($newClassRoom->coordinator_id);

            $courseName = Course::find($newClassRoom->course_id)->title;

            //mail notification parameter
            $content = 'مرحبا ' . $trainer->name . ' لقد تم تعيينك مشرف على برنامج ' . $courseName;
            $route = 'trainer_dash';
            $trainerEmail = $trainer->email;
            $subjectEmail = 'إشراف على برنامج ';

            //mail notification parameter
            $contentCoordinator = 'مرحبا ' . $coordinator->name . ' لقد تم تعيينك منسق على برنامج ' . $courseName;
            $subjectEmailCoordinator = 'تنسيق برنامج ';
            $coordinatorEmail = $coordinator->email;
            //end email parameter 
            NotificationController::sendNotificationFromAdmin($newClassRoom->trainer_id, $content, $route, 2);
            NotificationController::sendNotificationFromAdmin($newClassRoom->coordinator_id, $content, $route, 2);
            try {
                MailNotificationQueue::dispatch($content, $route, $trainerEmail, $subjectEmail);
                MailNotificationQueue::dispatch($contentCoordinator, $route, $coordinatorEmail, $subjectEmailCoordinator);
            } catch (\Throwable $th) {
                return back()->with(['warning' => 'لم يتم إسال الإيميلات']);
            }
            return back()->with(['success' => 'تم إضافة بيانات الدورة التدريبية بنجاح']);
        } catch (\Throwable $th) {
            return back()->with(['error' => 'لم يتم إضافة بيانات الدورة التدريبية  ']);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\UpdateClassRoomRequest  $request
     * @param  \App\Models\ClassRoom  $classRoom
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateClassRoomRequest $request, ClassRoom $classRoom)
    {
        // return $request;
        $request->validate([
            'name' => 'required',
            'place' => 'required',
            'courseId' => 'required|numeric',
            'trainerId' => 'required|numeric',
            'coordinatorId' => 'required|numeric',
        ], [
            'name.required' => 'يرجى ادخال  الإسم',
            'place.required' => 'يرجى ادخال  المكان',
            'courseId.required' => 'يرجى تحديد  البرنامج',
            'trainerId.required' => 'يرجى تحديد  المشرف',
            'coordinatorId.required' => 'يرجى تحديد  المنسق',
        ]);
        try {
            $updateClassRoom = ClassRoom::find($request->id);
            //if new trainer id not equal old send notification to trainer
            if ($updateClassRoom != $request->trainerId) {
                // return "send notfication to trainer";
            }

            $updateClassRoom->name = $request->name;
            $updateClassRoom->place = $request->place;
            $updateClassRoom->course_id = $request->courseId;
            $updateClassRoom->trainer_id = $request->trainerId;
            $updateClassRoom->update();
            return back()->with(['success' => 'تم إضافة تعديل بياناتالدورة التدريبية بنجاح']);
        } catch (\Throwable $th) {
            return back()->with(['error' => 'لم يتم تعديل بياناتالدورة التدريبية  ']);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\ClassRoom  $classRoom
     * @return \Illuminate\Http\Response
     */
    public function destroy(ClassRoom $classRoom, Request $request)
    {
        try {
            ClassRoom::find($request->id)->delete();
            return back()->with(['success' => 'تمت حذفالدورة التدريبية بنجاح']);
        } catch (\Throwable $th) {
            return back()->with(['error' => 'لم يتم حذفالدورة التدريبية ']);
        }
    }
    /**
     * [This method using to active and not active ]
     *
     * @param Request $request
     *
     * @return [type]
     *
     */
    public function toggle(Request $request)
    {
        try {
            $room = ClassRoom::find($request->id);
            $room->is_active *= -1;
            $room->save();
            return back()->with(['success' => 'تمت تحديث البيانات بنجاح']);
        } catch (\Throwable $th) {
            return back()->with(['error' => 'لم يتم تحديث البيانات']);
        }
    }

    public function studentCertificate($roomId)
    {
        $classRoom = ClassRoom::find($roomId);

         $studentId = StudentSubscribe::with('student')
            ->where('room_id', $roomId)
            ->get()->map(function ($item) {
                return $item->student_id;
            });

         $students = User::whereIn('id',$studentId)->get();
         
         return view('studentCertificates.list')->with(['students'=>$students,'classRoom'=>$classRoom]);

    }

}
