IMMREX7

aku nok ndi : /home/spdtg/www/schoolmis/app/Http/Controllers/School/Exam/
File Up :
aku nok ndi : /home/spdtg/www/schoolmis/app/Http/Controllers/School/Exam/ExamMasterController.php

<?php

namespace App\Http\Controllers\School\Exam;

use Illuminate\Http\Request;
use App\Http\Controllers\School\SchoolController;
use DB;
use Auth;
use Session;
use Exception;
use App\Http\SendNotificationApi;
use Illuminate\Support\Facades\Validator;

class ExamMasterController extends SchoolController {

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) {
        $classes = ['' => '-- Select Class --'] + \App\ClassM::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->orderBy('idClass')->get()->pluck('className', 'idClass')->toArray();
        $section = ['' => '-- Select Section --'];
        $subject = ['' => '-- Select Subject --'];
        $questions = ['' => '-- Select Questions --', 'mcq' => 'MCQ Questions', 'images_questions' => 'Image to Questions'
            , 'question_image' => 'Questions to Images', 'image_image' => 'Image to Image', 'math_type' => 'Math Type', 'short' => 'Short Question'
            , 'long' => 'Long Question', 'image_long' => 'Image for Long Question', 'paragraph_mcq' => 'Paragraph MCQ','paragraph_short' => 'Paragraph Short Question'];
        $exams = \App\ExamMcq::join('subjects', 'exam_mcq.idSubject', 'subjects.idSubject')
                        ->select('exam_mcq.*', 'subjects.subjectName')
                        ->where('exam_mcq.idSchool', Auth::guard('school')->user()->idSchool)->where('exam_mcq.idFinancialYear', Session::get('idFinancialYear'))->orderBy('idMcq', "DESC")->paginate(10);
                        if ($request->ajax()) {
                            $exams = \App\ExamMcq::join('subjects', 'exam_mcq.idSubject', 'subjects.idSubject')
                                    ->select('exam_mcq.*', 'subjects.subjectName')
                                    ->where('exam_mcq.idSchool', Auth::guard('school')->user()->idSchool)->where('exam_mcq.idFinancialYear', Session::get('idFinancialYear'));
                            $search = $request->input('search.value');
                            $start = $request->input('start');
                            $length = $request->input('length');
                            $totalFiltered = 0;
                            $totalData = 0;
                            if (isset($search)) {
                                $filter = \App\ExamMcq::join('subjects', 'exam_mcq.idSubject', 'subjects.idSubject')
                                                ->select('exam_mcq.*', 'subjects.subjectName')
                                                ->where('exam_mcq.idSchool', Auth::guard('school')->user()->idSchool)->where('exam_mcq.idFinancialYear', Session::get('idFinancialYear'))->where('examName', 'LIKE', "%{$search}%")->orderBy('idMcq', "DESC")->count();
                                $exams = $exams->where('examName', 'LIKE', "%{$search}%")->orderBy('idMcq', "DESC")->skip($start)->take($length)->get();
                                $totalFiltered = $filter;
                            } else {
                                $exams = $exams->orderBy('idMcq', "DESC")->skip($start)->take($length)->get();
                                $totalData = \App\ExamMcq::join('subjects', 'exam_mcq.idSubject', 'subjects.idSubject')
                                                ->select('exam_mcq.*', 'subjects.subjectName')
                                                ->where('exam_mcq.idSchool', Auth::guard('school')->user()->idSchool)->where('exam_mcq.idFinancialYear', Session::get('idFinancialYear'))->count();
                                $totalFiltered = $totalData;
                            }
                
                
                            $data = array();
                            foreach ($exams as $value) {
                                $nestedData = array();
                                array_push($nestedData, $value->examName);
                                array_push($nestedData, $value->classM->className);
                                if (isset($value->section->sectionName)) {
                                    array_push($nestedData, $value->section->sectionName);
                                } else
                                    array_push($nestedData, "All Section");
                                array_push($nestedData, $value->subjectName);
                                array_push($nestedData, $value->examDate);
                                array_push($nestedData, $value->totalMarks);
                                array_push($nestedData, '<a href="https://online-login.online/school/exam/master/' . $value->idMcq . '" class="btn btn-raised btn-primary waves-effect btn-round">View</a><a href="https://online-login.online/school/exam/master/' . $value->idMcq . '/edit" class="btn btn-raised btn-info waves-effect btn-round">Edit</a><button class="btn btn-raised btn-danger waves-effect btn-round js-sweetalert" data-id="'.$value->idMcq.'" data-type="confirm">DELETE</button>');
                                $questions = DB::table('exam_ques_types')->where('idExam', $value->idMcq)->sum('questions');
                                $total = \App\ExamQuestions::where('idMcq', $value->idMcq)->count();
                                if ($questions == $total)
                                    array_push($nestedData, '<a href="#"  class="btn btn-primary waves-effect btn-round">Done </a>');
                                else
                                    array_push($nestedData, '<a href="https://online-login.online/school/exam/addquestions/' . $value->idMcq . '"  class="btn btn-danger waves-effect btn-round">Pending</a>');
                                array_push($data, $nestedData);
                            }
                
                            $json_data = array(
                                "draw" => intval($request->input('draw')),
                                "recordsTotal" => intval($totalData),
                                "recordsFiltered" => intval($totalFiltered),
                                "data" => $data
                            );
                            return json_encode($json_data);
                        }       
        return view('schools.exams.exam_master', compact('classes', 'section', 'subject', 'exams', 'questions'));
    }



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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     * */
    public function store(Request $request) {
        $rules = [
            'idClass' => 'required',
            'idSection' => 'required',
            'idSubject' => 'required',
            'totalTime' => 'required',
            'totalMarks' => 'required',
        ];
        if ($request->has('examName')) {
            $rules += ['examName' => 'required'];
        }
        $messages = [
            'examDate.required' => 'Exam Date must be selected',
        ];
        $this->validate($request, $rules, $messages);

        $mcq = \App\ExamMcq::where('idClass', $request->idClass)
                ->where('idSection', $request->idSection)
                ->where('examDate', $request->examDate)
                ->first();

        if (isset($mcq->idMcq)) {

            return response()->json(['errors' => "Two exam cannot be schedule on same time for same class and section"], 422, ['app-status' => 'failed']);
        }

        $mcq = new \App\ExamMcq();
        $mcq->idSchool = Auth::guard('school')->user()->idSchool;
        $mcq->idFinancialYear = getFinancialYear();
        $mcq->idClass = $request->idClass;
        if ($request->idSection != "all") {
            $mcq->idSection = $request->idSection;
        }
        $mcq->idSubject = $request->idSubject;
        $mcq->examName = $request->examName;
        $mcq->examDate = \Carbon\Carbon::parse($request->examDate)->format('Y-m-d H:i:s');
        $mcq->examTime = $request->totalTime;

        if ($request->totalTime == "00:00") {
            if ($request->ajax()) {
                return response()->json(['errors' => "Exam time should be greater than zero"], 422, ['app-status' => 'failed']);
            }
        }

        $mcq->totalMarks = $request->totalMarks;
        try {
            DB::beginTransaction();
            $marks = 0;
            foreach ($request->questions as $key => $value) {
                $marks = $marks + ( $value['marks'] * $value['total'] );
            }
            if ($request->totalMarks != $marks) {
                throw new Exception("Marks total is incorrect Expected :" . $request->totalMarks . " and Total : " . $marks, 1);
            }
            $mcq->save();
            foreach ($request->questions as $key => $value) {
                DB::table('exam_ques_types')->insert(
                        ['idExam' => $mcq->idMcq, 'typeName' => $value['type'], 'questions' => $value['total'], 'marks' => $value['marks']]
                );
            }
            DB::commit();

            $reg_ids = DB::table('students')
                            ->join('parents', 'students.father_mobile', '=', 'parents.mobile')
                            ->select('parents.idFirebase')->where('students.idClass', $request->idClass);

            if ($request->idSection != "all")
                $reg_ids = $reg_ids->where('students.idSection', $request->idSection);

            $reg_ids = $reg_ids->where('students.idFinancialYear', Session::get('idFinancialYear'))
                            ->where('students.idSchool', Auth::guard('school')->user()->idSchool)
                            ->get()->pluck('idFirebase')->toArray();
            SendNotificationApi::sendNotification($reg_ids, "Exam : " . $request->examName . " has been created which is schedule to be on " . $request->examDate);

            $reg_ids = DB::table('students')
                            ->join('parents', 'students.mother_mobile', '=', 'parents.mobile')
                            ->select('parents.idFirebase')->where('students.idClass', $request->idClass);

            if ($request->idSection != "all")
                $reg_ids = $reg_ids->where('students.idSection', $request->idSection);

            $reg_ids = $reg_ids->where('students.idFinancialYear', Session::get('idFinancialYear'))
                            ->where('students.idSchool', Auth::guard('school')->user()->idSchool)
                            ->get()->pluck('idFirebase')->toArray();
            SendNotificationApi::sendNotification($reg_ids, "Exam : " . $request->examName . " has been created which is schedule to be on " . $request->examDate);
        } catch (Exception $e) {
            DB::rollback();
            if ($request->ajax()) {
                return response()->json(['errors' => $e->getMessage()], 422, ['app-status' => 'failed']);
            }
        }
        flash('Exam has been saved successfully.');
        if ($request->ajax()) {
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id) {
        $template = \App\ExamMcq::join('subjects', 'exam_mcq.idSubject', 'subjects.idSubject')->select('exam_mcq.*', 'subjects.subjectName')->findOrfail($id);
        $paper = DB::table('exam_ques_types')->where('idExam', $id)->get();

        $classes = ['' => '-- Select Class --'] + \App\ClassM::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->orderBy('idClass')->get()->pluck('className', 'idClass')->toArray();
        $section = ['' => '-- Select Section --'];
        $subject = ['' => '-- Select Subject --'];
        $questions = ['' => '-- Select Questions --', 'mcq' => 'MCQ Questions', 'images_questions' => 'Image to Questions'
            , 'question_image' => 'Questions to Images', 'image_image' => 'Image to Image', 'math_type' => 'Math Type', 'short' => 'Short Question'
            , 'long' => 'Long Question', 'image_long' => 'Image for Long Question', 'paragraph_mcq' => 'Paragraph MCQ','paragraph_short' => 'Paragraph Short Question'];
        $show = true;
        $exams = \App\ExamMcq::join('subjects', 'exam_mcq.idSubject', 'subjects.idSubject')
                        ->join('classes', 'exam_mcq.idClass', 'classes.idClass')
                        ->select('exam_mcq.*', 'subjects.subjectName', 'classes.className')
                        ->where('exam_mcq.idSchool', Auth::guard('school')->user()->idSchool)->where('exam_mcq.idFinancialYear', Session::get('idFinancialYear'))->paginate(10);

        return view('schools.exams.exam_master', compact('classes', 'section', 'subject', 'exams', 'questions', 'template', 'paper', 'show'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id) {
        $template = \App\ExamMcq::join('subjects', 'exam_mcq.idSubject', 'subjects.idSubject')->select('exam_mcq.*', 'subjects.subjectName')->findOrfail($id);
        $paper = DB::table('exam_ques_types')->where('idExam', $id)->get();

        $classes = ['' => '-- Select Class --'] + \App\ClassM::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->orderBy('idClass')->get()->pluck('className', 'idClass')->toArray();
        $subject = ['' => '-- Select Subject --'];
        $section = ['' => 'All Section'];
        if ($template->idSection != null) {
            $subject = ['' => '-- Select Subject --'] + \App\Subject::where('idClass', $template->idClass)->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                            ->orderBy('idSubject')->get()->pluck('subjectName', 'idSubject')->toArray();
            $section = ['' => '-- Select Section --'] + \App\Section::where('idClass', $template->idClass)->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                            ->orderBy('idSection')->get()->pluck('sectionName', 'idSection')->toArray();
        } else
            $subject = ['' => '-- Select Subject --'] + \App\Subject::where('idClass', $template->idClass)->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                            ->orderBy('idSubject')->get()->pluck('subjectName', 'idSubject')->toArray();

        $questions = ['' => '-- Select Questions --', 'mcq' => 'MCQ Questions', 'images_questions' => 'Image to Questions'
            , 'question_image' => 'Questions to Images', 'image_image' => 'Image to Image', 'math_type' => 'Math Type', 'short' => 'Short Question'
            , 'long' => 'Long Question', 'image_long' => 'Image for Long Question', 'paragraph_mcq' => 'Paragraph MCQ','paragraph_short' => 'Paragraph Short Question'];

        $exams = \App\ExamMcq::join('subjects', 'exam_mcq.idSubject', 'subjects.idSubject')
                        ->join('classes', 'exam_mcq.idClass', 'classes.idClass')
                        ->select('exam_mcq.*', 'subjects.subjectName', 'classes.className')
                        ->where('exam_mcq.idSchool', Auth::guard('school')->user()->idSchool)->where('exam_mcq.idFinancialYear', Session::get('idFinancialYear'))->paginate(10);

        return view('schools.exams.exam_master', compact('classes', 'section', 'subject', 'exams', 'questions', 'template', 'paper'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id) {
        $mcq = \App\ExamMcq::findOrfail($id);
        if (isset($request->idClass)) {
            $mcq->idClass = $request->idClass;
        }

        if ($request->idSection != "all") {
            $mcq->idSection = $request->idSection;
        }

        if (isset($request->idSubject)) {
            $mcq->idSubject = $request->idSubject;
        }
        if (isset($request->examName)) {
            $mcq->examName = $request->examName;
        }
        if (isset($request->examDate)) {
            $mcq->examDate = \Carbon\Carbon::parse($request->examDate)->format('Y-m-d H:i:s');
        }
        if (isset($request->totalTime)) {
            $mcq->examTime = $request->totalTime;
        }
        DB::beginTransaction();
        $marks = 0;
        foreach ($request->questions as $key => $value) {
            $marks = $marks + ( $value['marks'] * $value['total'] );
        }
        if ($request->totalMarks != $marks) {
            DB::rollback();
            flash('Exam has been not saved marks are not equal');
            if ($request->ajax()) {
                return response()->json(['errors' => "Marks total is incorrect Expected :" . $request->totalMarks . " and Total : " . $marks], 422, ['app-status' => 'failed']);
            }
        } else {
            DB::table('exam_ques_types')->where('idExam', $id)->delete();
            foreach ($request->questions as $key => $value) {
                DB::table('exam_ques_types')->insert(
                        ['idExam' => $mcq->idMcq, 'typeName' => $value['type'], 'questions' => $value['total'], 'marks' => $value['marks']]
                );
            }
            $mcq->totalMarks = $request->totalMarks;
            $mcq->update();
            DB::commit();
            flash('Exam has been saved successfully.');
            if ($request->ajax()) {
                return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            }
        }

        if ($request->ajax()) {
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        } else
            return redirect('school/exam/master/' . $id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id) {
        $template = \App\ExamMcq::findOrfail($id);
        DB::table('exam_ques_types')->where('idExam', $template->idMcq)->delete();
        \App\ExamQuestions::where('idMcq', $template->idMcq)->delete();
        DB::table('exam_mcq_response')->where('idExam', $template->idMcq)->delete();
        DB::table('exam_mcq_results')->where('idExam', $template->idMcq)->delete();
        $template->delete();
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function getTemplates() {
        $exams = array();
        return view('schools.exams.exam_questions', compact('exams'));
    }

    public function getTemplate(Request $request) {

        $exams = \App\ExamMcq::join('subjects', 'exam_mcq.idSubject', 'subjects.idSubject')
                        ->select('exam_mcq.*', 'subjects.subjectName')
                        ->where('exam_mcq.idSchool', Auth::guard('school')->user()->idSchool)->where('exam_mcq.idFinancialYear', Session::get('idFinancialYear'));

        $search = $request->input('search.value');
        $start = $request->input('start');
        $length = $request->input('length');
        $totalFiltered = 0;
        $totalData = 0;
        if (isset($search)) {
            $filter = \App\ExamMcq::join('subjects', 'exam_mcq.idSubject', 'subjects.idSubject')
                            ->select('exam_mcq.*', 'subjects.subjectName')
                            ->where('exam_mcq.idSchool', Auth::guard('school')->user()->idSchool)->where('exam_mcq.idFinancialYear', Session::get('idFinancialYear'))->where('examName', 'LIKE', "%{$search}%")->orderBy('idMcq', "DESC")->count();
            $exams = $exams->where('examName', 'LIKE', "%{$search}%")->orderBy('idMcq', "DESC")->skip($start)->take($length)->get();
            $totalFiltered = $filter;
        } else {
            $exams = $exams->orderBy('idMcq', "DESC")->skip($start)->take($length)->get();
            $totalData = \App\ExamMcq::join('subjects', 'exam_mcq.idSubject', 'subjects.idSubject')
                            ->select('exam_mcq.*', 'subjects.subjectName')
                            ->where('exam_mcq.idSchool', Auth::guard('school')->user()->idSchool)->where('exam_mcq.idFinancialYear', Session::get('idFinancialYear'))->count();
            $totalFiltered = $totalData;
        }


        $data = array();
        foreach ($exams as $value) {
            $nestedData = array();
            array_push($nestedData, $value->examName);
            array_push($nestedData, $value->classM->className);
            if (isset($value->section->sectionName)) {
                array_push($nestedData, $value->section->sectionName);
            } else
                array_push($nestedData, "All Section");
            array_push($nestedData, $value->subjectName);
            array_push($nestedData, $value->examDate);
            array_push($nestedData, $value->totalMarks);
            array_push($nestedData, '<a href="https://online-login.online/school/exam/addquestions/' . $value->idMcq . '" class="btn btn-raised btn-primary waves-effect btn-round">Add Question</a><a href="https://online-login.online/school/exam/addquestions/' . $value->idMcq . '/show" class="btn btn-raised btn-info waves-effect btn-round">View</a>');
            $questions = DB::table('exam_ques_types')->where('idExam', $value->idMcq)->sum('questions');
            $total = \App\ExamQuestions::where('idMcq', $value->idMcq)->count();
            if ($questions == $total)
                array_push($nestedData, '<a href="#"  class="btn btn-primary waves-effect btn-round">Done </a>');
            else
                array_push($nestedData, '<a href="https://online-login.online/school/exam/addquestions/' . $value->idMcq . '"  class="btn btn-danger waves-effect btn-round">Pending</a>');
            array_push($data, $nestedData);
        }

        $json_data = array(
            "draw" => intval($request->input('draw')),
            "recordsTotal" => intval($totalData),
            "recordsFiltered" => intval($totalFiltered),
            "data" => $data
        );
        return json_encode($json_data);
    }

    public function storeQuestions(Request $request) {
        if (count($request->mcq) == 0) {
            if ($request->ajax()) {
                return response()->json(['errors' => "No more question to add "], 422, ['app-status' => 'failed']);
            }
        }
        DB::beginTransaction();
        try {
            foreach ($request->mcq as $key => $value) {

                $paper = DB::table('exam_ques_types')->where('idType', $value['id'])->first();

                $questions = new \App\ExamQuestions();

                if (isset($value['paraText'])) {
                    $mcqparagrah = \App\ExamParagraph::where('idMcq', '=', $paper->idExam)->where('paraText', '=', $value['paraText'])->first();
                    if (empty($mcqparagrah)) {
                        $mcqparagrah = new \App\ExamParagraph();
                        $paraafterextraspace = preg_replace('/\s\s+/', ' ', $value['paraText']);
                        $mcqparagrah->paraText =  $paraafterextraspace;
                        $mcqparagrah->idMcq = $paper->idExam;
                        $mcqparagrah->save();
                    }
                }

                if ($request->hasFile('mcq.' . $key . '.questions')) {

                    if ($request->file('mcq')[$key]['questions']->getClientOriginalExtension() != 'png' && $request->file('mcq')[$key]['questions']->getClientOriginalExtension() != 'jpg' && $request->file('mcq')[$key]['questions']->getClientOriginalExtension() != 'jpeg') {
                        if ($request->ajax()) {
                            DB::rollback();
                            return response()->json(['errors' => "Only .jpeg and .png images are allowed"], 422, ['app-status' => 'failed']);
                        }
                    }

                    $size = filesize($request->file('mcq')[$key]['questions']);

                    if ($size > 200000) {
                        if ($request->ajax()) {
                            DB::rollback();
                            return response()->json(['errors' => "Size should be less than 200KB original size is " . $size / 1000 . "KB for QNo. : " . $key], 422, ['app-status' => 'failed']);
                        }
                    }

                    $file = $request->file('mcq')[$key]['questions'];
                    $nw = 'mcq_' . $value['id'] . '_' . $key . '.' . $file->getClientOriginalExtension();
                    $file->storeAs('public/schools/' . Auth::guard('school')->user()->idSchool . '/mcq/', $nw);
                    $questions->question = $nw;
                    //$isQuestion = true;
                } else if (isset($value['questions'])) {
                    //$isQuestion = true;
                    $qfterextraspace = preg_replace('/\s\s+/', ' ', $value['questions']);
                    $questions->question = $qfterextraspace;
                }else{
                    //dd('here');
                    $qfterextraspace = preg_replace('/\s\s+/', ' ', $value['questionsparamcq']);
                    $questions->question = $qfterextraspace;
                    $questions->idParagraph = $mcqparagrah->idParagraph;   
                }


                //if($isQuestion){
                if (isset($value['marks'])) {
                    $questions->marks = $value['marks'];
                } else {
                    if ($request->ajax()) {
                        DB::rollback();
                        return response()->json(['errors' => "Marks not given for QNO. : " . $key], 422, ['app-status' => 'failed']);
                    }
                }

                $questions->idMcq = $paper->idExam;
                $questions->questionType = $paper->typeName;

                if ($paper->typeName != "short" && $paper->typeName != "long" && $paper->typeName != "mage_long") {


                    if ($request->hasFile('mcq.' . $key . '.optionsA')) {

                        if ($request->file('mcq')[$key]['optionsA']->getClientOriginalExtension() != 'png' && $request->file('mcq')[$key]['optionsA']->getClientOriginalExtension() != 'jpg' && $request->file('mcq')[$key]['optionsA']->getClientOriginalExtension() != 'jpeg') {
                            if ($request->ajax()) {
                                DB::rollback();
                                return response()->json(['errors' => "Only .jpeg and .png images are allowed"], 422, ['app-status' => 'failed']);
                            }
                        }

                        $size = filesize($request->file('mcq')[$key]['optionsA']);

                        if ($size > 200000) {
                            if ($request->ajax()) {
                                DB::rollback();
                                return response()->json(['errors' => "Size should be less than 200KB original size is " . $size / 1000 . "KB for QNo. : " . $key], 422, ['app-status' => 'failed']);
                            }
                        }

                        $file = $request->file('mcq')[$key]['optionsA'];
                        $nw = 'mcq_' . $value['id'] . '_' . $key . 'a' . '.' . $file->getClientOriginalExtension();
                        $file->storeAs('public/schools/' . Auth::guard('school')->user()->idSchool . '/mcq/', $nw);
                        $questions->answerA = $nw;
                    } else
                    if (isset($value['optionsA']))
                        $questions->answerA = $value['optionsA'];

                    if ($request->hasFile('mcq.' . $key . '.optionsB')) {

                        if ($request->file('mcq')[$key]['optionsB']->getClientOriginalExtension() != 'png' && $request->file('mcq')[$key]['optionsB']->getClientOriginalExtension() != 'jpg' && $request->file('mcq')[$key]['optionsB']->getClientOriginalExtension() != 'jpeg') {
                            if ($request->ajax()) {
                                DB::rollback();
                                return response()->json(['errors' => "Only .jpeg and .png images are allowed"], 422, ['app-status' => 'failed']);
                            }
                        }

                        $size = filesize($request->file('mcq')[$key]['optionsB']);

                        if ($size > 200000) {
                            if ($request->ajax()) {
                                DB::rollback();
                                return response()->json(['errors' => "Size should be less than 200KB original size is " . $size / 1000 . "KB for QNo. : " . $key], 422, ['app-status' => 'failed']);
                            }
                        }

                        $file = $request->file('mcq')[$key]['optionsB'];
                        $nw = 'mcq_' . $value['id'] . '_' . $key . 'b' . '.' . $file->getClientOriginalExtension();
                        $file->storeAs('public/schools/' . Auth::guard('school')->user()->idSchool . '/mcq/', $nw);
                        $questions->answerB = $nw;
                    } else
                    if (isset($value['optionsB']))
                        $questions->answerB = $value['optionsB'];

                    if ($request->hasFile('mcq.' . $key . '.optionsC')) {

                        if ($request->file('mcq')[$key]['optionsC']->getClientOriginalExtension() != 'png' && $request->file('mcq')[$key]['optionsC']->getClientOriginalExtension() != 'jpg' && $request->file('mcq')[$key]['optionsC']->getClientOriginalExtension() != 'jpeg') {
                            if ($request->ajax()) {
                                DB::rollback();
                                return response()->json(['errors' => "Only .jpeg and .png images are allowed"], 422, ['app-status' => 'failed']);
                            }
                        }

                        $size = filesize($request->file('mcq')[$key]['optionsC']);

                        if ($size > 200000) {
                            if ($request->ajax()) {
                                DB::rollback();
                                return response()->json(['errors' => "Size should be less than 200KB original size is " . $size / 1000 . "KB for QNo. : " . $key], 422, ['app-status' => 'failed']);
                            }
                        }

                        $file = $request->file('mcq')[$key]['optionsC'];
                        $nw = 'mcq_' . $value['id'] . '_' . $key . 'c' . '.' . $file->getClientOriginalExtension();
                        $file->storeAs('public/schools/' . Auth::guard('school')->user()->idSchool . '/mcq/', $nw);
                        $questions->answerC = $nw;
                    } else
                    if (isset($value['optionsC']))
                        $questions->answerC = $value['optionsC'];

                    if ($request->hasFile('mcq.' . $key . '.optionsD')) {

                        if ($request->file('mcq')[$key]['optionsD']->getClientOriginalExtension() != 'png' && $request->file('mcq')[$key]['optionsD']->getClientOriginalExtension() != 'jpg' && $request->file('mcq')[$key]['optionsD']->getClientOriginalExtension() != 'jpeg') {
                            if ($request->ajax()) {
                                DB::rollback();
                                return response()->json(['errors' => "Only .jpeg and .png images are allowed"], 422, ['app-status' => 'failed']);
                            }
                        }

                        $size = filesize($request->file('mcq')[$key]['optionsD']);

                        if ($size > 200000) {
                            if ($request->ajax()) {
                                DB::rollback();
                                return response()->json(['errors' => "Size should be less than 200KB original size is " . $size / 1000 . "KB for QNo. : " . $key], 422, ['app-status' => 'failed']);
                            }
                        }

                        $file = $request->file('mcq')[$key]['optionsD'];
                        $nw = 'mcq_' . $value['id'] . '_' . $key . 'd' . '.' . $file->getClientOriginalExtension();
                        $file->storeAs('public/schools/' . Auth::guard('school')->user()->idSchool . '/mcq/', $nw);
                        $questions->answerD = $nw;
                    } else
                    if (isset($value['optionsD']))
                        $questions->answerD = $value['optionsD'];
                }

                if (isset($value['correct'])) {
                    $questions->answerCorrect = $value['correct'];
                }


                $isQues = DB::table('exam_mcq_questions')
                        ->where('question', $questions->question)
                        ->where('questionType', $paper->typeName)
                        ->where('answerA', $questions->answerA)
                        ->where('answerB', $questions->answerB)
                        ->where('answerC', $questions->answerC)
                        ->where('answerD', $questions->answerD)
                        ->where('answerCorrect', $questions->answerCorrect)
                        ->where('marks', $questions->marks)
                        ->first();
                if (!isset($isQues->idQuestions)) {
                    if (isset($questions->question)) {
                        $questions->save();
                    }
                }
                //}
            }
        } catch (\Exception $e) {
            \DB::rollback();
            if ($request->ajax()) {
                return response()->json(['errors' => "Please fill the fields Properly. " . $e->getMessage()], 422, ['app-status' => 'success']);
            }
        }

        DB::commit();
        flash('Exam Question has been saved successfully.');
        if ($request->ajax()) {
            return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
        }
    }

    public function showQuestions($id) {
        $template = \App\ExamMcq::join('subjects', 'exam_mcq.idSubject', 'subjects.idSubject')->select('exam_mcq.*', 'subjects.subjectName')->findOrfail($id);
        $papers = DB::table('exam_ques_types')->where('idExam', $id)->get();
        $storedQuestions = \App\ExamQuestions::where('idMcq', $id)->groupBy('questionType','marks')->select(DB::raw('count(*) as qtotal'),'questionType','marks')->get();
        
        $completedQuestions = array();
        $qno = 1;
        foreach($storedQuestions as $ques){
            $index = $ques->marks.$ques->questionType;
            $completedQuestions[$index] = $ques->qtotal;
        }
        //dd($completedQuestions,$storedQuestions);
        $paperData = array();
        foreach ($papers as $qtypes){
            if(isset($completedQuestions[$qtypes->marks.$qtypes->typeName]))
            {
                if($qtypes->questions != $completedQuestions[$qtypes->marks.$qtypes->typeName]){
                    $qno = $qno + $completedQuestions[$qtypes->marks.$qtypes->typeName];
                    array_push($paperData,$qtypes);
                }else{
                    $qno = $qno + $qtypes->questions;
                }
            }else array_push($paperData,$qtypes); 
        }
        $paper = (object)$paperData;
        //dd($completedQuestions,$storedQuestions,$papers,$paper );
        
        $questions = ['' => '-- Select Questions --', 'mcq' => 'MCQ Questions', 'images_questions' => 'Image to Questions'
            , 'question_image' => 'Questions to Images', 'image_image' => 'Image to Image', 'math_type' => 'Math Type', 'short' => 'Short Question'
            , 'long' => 'Long Question', 'image_long' => 'Image for Long Question', 'paragraph_mcq' => 'Paragraph MCQ','paragraph_short' => 'Paragraph Short Question'];
        $options = ['' => '-- Select Correct Option --', 'A' => 'Option A', 'B' => 'Option B', 'C' => 'Option C', 'D' => 'Option D'];
        return view('schools.exams.exam_questions', compact('template', 'paper', 'questions', 'options','papers','qno'));
    }

    public function viewQuestions($id) {
        $template = \App\ExamMcq::join('subjects', 'exam_mcq.idSubject', 'subjects.idSubject')->select('exam_mcq.*', 'subjects.subjectName')->findOrfail($id);
        $paper = DB::table('exam_ques_types')->where('idExam', $id)->get();
        $show = true;
        $qno = 1;
        $papers = array();
        $questions = ['' => '-- Select Questions --', 'mcq' => 'MCQ Questions', 'images_questions' => 'Image to Questions'
            , 'question_image' => 'Questions to Images', 'image_image' => 'Image to Image', 'math_type' => 'Math Type', 'short' => 'Short Question'
            , 'long' => 'Long Question', 'image_long' => 'Image for Long Question','paragraph_mcq' => 'Paragraph MCQ','paragraph_short' => 'Paragraph Short Question'];
        $options = ['' => '-- Select Correct Option --', 'A' => 'Option A', 'B' => 'Option B', 'C' => 'Option C', 'D' => 'Option D'];
        return view('schools.exams.exam_questions', compact('template', 'paper', 'questions', 'options', 'show','papers','qno'));
    }

}

Copyright © 2021 - 2025 IMMREX7