<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\ClassRoom;
use App\Models\Certificate;
use Illuminate\Http\Request;
use App\Jobs\MailNotificationQueue;

class CertificateController extends Controller
{
    public function store(Request $request)
    {
        // return $request;
        try{
        $room = ClassRoom::with('course')->find($request->classRoomId);
        if($request->studentsId==null)
            return back()->with(['error'=>'يرجى إضافة متدرب واحد على الأقل']);
        foreach ($request->studentsId as $studentId) {
            $certificate = Certificate::where('student_id',$studentId)->where('room_id',$request->classRoomId)->first();
             if(!isset($certificate))
             {
                        $newCertificate = new Certificate();
                        $newCertificate->room_id = $request->classRoomId;
                        $newCertificate->student_id = $studentId;
                        $student = User::find($newCertificate->student_id);
                        $studentName=$student->name;
                        $roomName = $room->name;
                        $courseName= $room->course->title;
                        $newCertificate->save();
                    $content = 'مرحبا ' . $studentName . ' لقد تم صرف شهادة لك الدورة التدريبية    ' . $roomName.' برنامج '.$courseName;
                    $route = 'get_certificate/'.$newCertificate->id;
                    $email = $student->email;//change to $student->email;
                    $subjectEmail = '  شهادة في برنامج ';
                
                    NotificationController::sendNotificationFromAdmin($student->id, $content, $route, 9);
                    try {
                        MailNotificationQueue::dispatch($content,$route,$email,$subjectEmail);
                    } catch (\Throwable$th) {
                        return back()->with(['warning' => 'لم يتم إسال الإيميلات']);
                    }
                } 
        }
        return back()->with(['success' => 'تم صرف الشهادات  للطلاب بنجاح']);
    } catch (\Throwable $th) {
        return back()->with(['error' => 'لم يتم صرف الشهادات للطلاب  ']);
    }
    }

    public function spent($certificateId)
    {
         $certificateInfo = Certificate::find($certificateId);
         if($certificateInfo->student->certificate_name==null)
         return back()->with(['error'=>'يرجى التعديل على اسمك الذي سيظهر في الشهادة']);
    //    return [$certificateInfo->room->course->title,$certificateInfo->student->certificate_name];

        return view('certificate.certificate')->with('certificateInfo',$certificateInfo);
    }
}
