<?php

namespace App\Http\Controllers\Coaching;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\Models\Test;
use App\Models\TestQuestion;
use App\Models\TestOption;
use App\Models\TestSubject;
use App\Models\TestLanguage;
use App\Models\PackageChapter;
use App\Models\PackageTopic;
use App\Models\ExamType;
use App\Models\SavedQuestion;
use App\Models\ImportFileData;
use App\Models\PackageSubject;
use App\Models\CoachingFacultySubject;
use App\Models\CoachingFaculty;
use App\Models\TestFaculty;
use App\Models\TestPackage;
use App\Models\BankQuestion;
use App\Models\BankQuestionLang;
use App\Models\BankQuestionAnswer;
use App\Models\QuestionAssigned;
use App\Models\CoachingMaster;
use Excel;
use DB;
use URL;

/**
 * Class TestQuestionController.
 */
class TestQuestionController extends Controller
{
    /**
     * @var model
     * @var testModel
     * @var examTypeModel
     * @var testSubjectModel
     * @var packageSubjectModel
     * @var packageChapterModel
     * @var packageTopicModel
     * @var savedQuestionModel
     * @var importFileDataModel
     * @var coachingFacultyModel
     * @var testFacultyModel
     * @var testLanguageModel
     * @var bankQuestionModel
     * @var bankQuestionLangModel
     * @var bankQuestionAnswerModel
     * @var questionAssignedModel
     * @var testPackageModel
     * @var bankQuestionModel
     * @var coachingMasterModel
     */
    protected $model;
    protected $testModel;
    protected $examTypeModel;
    protected $testSubjectModel;
    protected $packageSubjectModel;
    protected $packageChapterModel;
    protected $packageTopicModel;
    protected $savedQuestionModel;
    protected $importFileDataModel;
    protected $testQuestionLangModel;
    protected $testQuestionAnswerModel;
    protected $coachingFacultyModel;
    protected $testOptionModel;
    protected $testFacultyModel;
    protected $testLanguageModel;
    protected $testPackageModel;
    protected $bankQuestionModel;
    protected $coachingMasterModel;
    protected $bankQuestionLangModel;
    protected $bankQuestionAnswerModel;
    protected $questionAssignedModel;

    /**
     * TestQuestionController constructor.
     *
     * @param model $model
     */
    public function __construct()
    {
        $this->model = new TestQuestion;
        $this->testModel = new Test;
        $this->examTypeModel = new ExamType;
        $this->testSubjectModel = new TestSubject;
        $this->packageSubjectModel = new PackageSubject;
        $this->packageChapterModel = new PackageChapter;
        $this->packageTopicModel = new PackageTopic;
        $this->savedQuestionModel = new SavedQuestion;
        $this->importFileDataModel = new ImportFileData;
        $this->coachingFacultyModel = new CoachingFaculty;
        $this->testOptionModel = new TestOption;
        $this->testFacultyModel = new TestFaculty;
        $this->testLanguageModel = new TestLanguage;
        $this->testPackageModel = new TestPackage;
        $this->bankQuestionModel = new BankQuestion;
        $this->coachingMasterModel = new CoachingMaster;
        $this->bankQuestionLangModel = new BankQuestionLang;
        $this->bankQuestionAnswerModel = new BankQuestionAnswer;
        $this->questionAssignedModel = new QuestionAssigned;
    }

    /**
     * Test list method.
     *
     */
    public function index(Request $req) 
    {
        $id = base64_decode($req->test_id);
        $test_languages = $this->testLanguageModel->where('test_id', $id)->groupBy('language_id')->get();
        $test_lang = [];
        if($test_languages){
            foreach ($test_languages as $key => $lang_val) {
                array_push($test_lang, $lang_val->language_id);
            }
        } else {
            $test_lang = [1,2];
        }
        $question_in_all_language = 0;
        if($req->post()){
            $test_id = base64_decode($req->test_id);
            //dd($req->post());
            $draw = $req->draw;
            $row = $req->start;
            $rowperpage = $req->length; // Rows display per page
            $columnIndex = $req->order[0]['column']; // Column index
            $columnName = $req->columns[$columnIndex]['data'] ? $req->columns[$columnIndex]['data'] : 'id'; // Column name
            $columnSortOrder = $req->order[0]['dir']; // asc or desc
            
            
            ## Total number of records without filtering
            $questiontotalRecord = $this->model
                                    ->select(DB::raw('*, test_questions.id'))
                                    ->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')
                                    ->where('test_id', $test_id)
                                    ->count();

            ## Total number of record with filtering
            $questiontotalRecordwithFilter = $this->model
                                                ->select(DB::raw('*, test_questions.id'))
                                                ->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')
                                                ->where('test_id', $test_id);

            ## Fetch records
            if($columnName == 'question'){
                $columnName = 'bank_questions.question';
            } 
            if($columnName == 'positive_mark'){
                $columnName = 'test_questions.positive_mark';
            }
            if($columnName == 'negative_mark'){
                $columnName = 'test_questions.negative_mark';
            }
            
            if($columnName == 'question_check' || $columnName == 'serial_no'){
                $questions = $this->model
                            ->select(DB::raw('*,test_questions.positive_mark,test_questions.negative_mark, test_questions.id'))
                            ->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')
                            ->where('test_id', $test_id)
                            ->skip($row)
                            ->take($rowperpage);
            } else {
                $questions = $this->model
                            ->select(DB::raw('*,test_questions.positive_mark,test_questions.negative_mark, test_questions.id'))
                            ->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')
                            ->where('test_id', $test_id)
                            ->orderBy($columnName, $columnSortOrder)
                            ->skip($row)
                            ->take($rowperpage);
            }
            

            if($req->subject_filter){
                $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('subject_id', $req->subject_filter);
                $questions = $questions->where('subject_id', $req->subject_filter);
            }
            if($req->chapter_filter){
                $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('chapter_id', $req->chapter_filter);
                $questions = $questions->where('chapter_id', $req->chapter_filter);
            }
            if($req->topic_filter){
                $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('topic_id', $req->topic_filter);
                $questions = $questions->where('topic_id', $req->topic_filter);
            }
            if($req->question_type_filter){
                $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('question_type', $req->question_type_filter);
                $questions = $questions->where('question_type', $req->question_type_filter);
            }
            if($req->difficulty_level_filter){
                $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('difficulty_level', $req->difficulty_level_filter);
                $questions = $questions->where('difficulty_level', $req->difficulty_level_filter);
            }

            $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->count();
            $questions = $questions->get(); 
            //echo $quizes->toSql(); die;
            //echo '<pre>';print_r($quizes);die;
            $data = array();
            $status_btn = '';
            $all_langs = 0;
            if($questions){
                foreach($questions as $key => $question){
                    $question_in_all_language = 0;
                    $languages_added = $this->bankQuestionLangModel->where('question_id', $question->bank_question_id)->select('language_id')->groupBy('question_id')->count();
                    if($languages_added < count($test_lang)){
                        $question_in_all_language = 1;
                        $all_langs = 1;
                    }
                    if(count($test_lang) > 1){
                        $question_data = $this->bankQuestionLangModel->where(['question_id'=>$question->bank_question_id, 'language_id'=>1])->first();
                        if(!$question_data){
                            $question_data = $this->bankQuestionLangModel->where(['question_id'=>$question->bank_question_id, 'language_id'=>2])->first();
                        }
                    } else {
                        $question_data = $this->bankQuestionLangModel->where(['question_id'=>$question->bank_question_id, 'language_id'=>$test_lang[0]])->first();
                    }
                    $data[] = array( 
                        "question_check"=>'<label class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input single_chk '.(($question_in_all_language == 1) ? 'single_lang_color' : '').'" name="chk[]" value="'.base64_encode($question->id).'
                                "/>
                                <span class="custom-control-label"></span>
                              </label>',
                        "serial_no"=>($key + $row + 1),
                        "question"=>\Illuminate\Support\Str::words($question_data->question, 15, $end=' ...'),
                        "positive_mark"=>'<button class="btn btn-block fs-12 font-medium right_marks_btn">'.$question->positive_mark.'</button><input type="text" data-id="'.base64_encode($question->id).'" data-type="1" class="right_marks_input" value="'.$question->positive_mark.'" style="display:none;">',
                        "negative_mark"=>'<button class="btn btn-block fs-12 font-medium negatiive_marks_btn">'.$question->negative_mark.'</button><input type="text" data-id="'.base64_encode($question->id).'" data-type="2" class="negatiive_marks_input" value="'.$question->negative_mark.'" style="display:none;">',
                        "action"=>'<a href="'.url('coaching-master/test_series_manager/test/question/edit/'.base64_encode($test_id).'/'.base64_encode($question->id)).'" class="action-btn reverse">
                                <img src="'.asset('admin/images/pen.svg').'" alt="" />
                              </a><a href="javascript:void(0)" class="action-btn reverse delete_question" data-id="'.base64_encode($question->id).'">
                                <img src="'.asset('admin/images/bin.svg').'" alt="" />
                              </a>',

                    );
                }
            }
            $question_in_all_language = 0;
            $total_question_added = $this->model->where('test_id', $id)->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')->count();
            $languages_added = $this->model->where('test_id', $id)->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')->join('bank_question_langs','bank_questions.id','=','bank_question_langs.question_id')->count();
            if($languages_added < $total_question_added * count($test_lang)){
                $question_in_all_language = 1;
                $all_langs = 1;
            }

            $response = array(
                "draw" => intval($draw),
                "iTotalRecords" => $questiontotalRecord,
                "iTotalDisplayRecords" => $questiontotalRecordwithFilter,
                "aaData" => $data,
                "question_in_all_language"=>$question_in_all_language,
                "all_langs"=>$all_langs
            );

            echo json_encode($response);die;
        }
        if($req->test_id){
            $subjects = $this->testSubjectModel->where('test_id', $id)->select('subject_id')->groupBy('subject_id')->get();
            $questiontotal = $this->model->where('test_id', $id)->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')->count();
            
            $test_details = $this->testModel->find($id);
            $update = $this->testPackageModel->where('id', $test_details->test_package_id)->update(['coaching_last_url'=>request()->path()]);
            $update = $this->testModel->where('id', $test_details->id)->update(['coaching_test_last_url'=>request()->path()]);
            if($test_details){
                return view('coaching.pages.test.question.list')
                            ->withSubjects($subjects)
                            ->withQuestiontotalRecord($questiontotal)
                            ->withTestDetails($test_details);
            } else {
                return redirect()->route('coaching.test_series_manager.test.list', base64_encode($test_details->test_package_id));
            }            
        } else {
            return redirect()->route('coaching.test_series_manager.test.list', base64_encode($test_details->test_package_id));
        } 
    }

    /**
     * Test Question list method.
     *
     */
    public function list(Request $req) 
    {
        $id = base64_decode($req->test_id);
        $test_languages = $this->testLanguageModel->where('test_id', $id)->get();
        $test_lang = [];
        if($test_languages){
            foreach ($test_languages as $key => $lang_val) {
                array_push($test_lang, $lang_val->language_id);
            }
        } else {
            $test_lang = [1,2];
        }
        if($req->post()){
            $test_id = base64_decode($req->test_id);
            //dd($req->post());
            $draw = $req->draw;
            $row = $req->start;
            $rowperpage = $req->length; // Rows display per page
            $columnIndex = $req->order[0]['column']; // Column index
            $columnName = $req->columns[$columnIndex]['data'] ? $req->columns[$columnIndex]['data'] : 'id'; // Column name
            $columnSortOrder = $req->order[0]['dir']; // asc or desc
            
            
            ## Total number of records without filtering
            $questiontotalRecord = $this->model
                                    ->select(DB::raw('*, test_questions.id'))
                                    ->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')
                                    ->where('test_id', $test_id)
                                    ->count();

            ## Total number of record with filtering
            $questiontotalRecordwithFilter = $this->model
                                                ->select(DB::raw('*, test_questions.id'))
                                                ->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')
                                                ->where('test_id', $test_id);

            ## Fetch records
            if($columnName == 'question'){
                $columnName = 'bank_questions.question';
            } 
            if($columnName == 'positive_mark') {
                $columnName = 'test_questions.positive_mark';
            }
            if($columnName == 'negative_mark') {
                $columnName = 'test_questions.negative_mark';
            }
            if($columnName == 'question_check' || $columnName == 'serial_no'){
                $questions = $this->model
                            ->select(DB::raw('*,test_questions.positive_mark,test_questions.negative_mark, test_questions.id'))
                            ->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')
                            ->where('test_id', $test_id)
                            ->skip($row)
                            ->take($rowperpage);
            } else {
                $questions = $this->model
                            ->select(DB::raw('*,test_questions.positive_mark,test_questions.negative_mark, test_questions.id'))
                            ->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')
                            ->where('test_id', $test_id)
                            ->orderBy($columnName, $columnSortOrder)
                            ->skip($row)
                            ->take($rowperpage);
            }
            

            if($req->subject_filter){
                $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('subject_id', $req->subject_filter);
                $questions = $questions->where('subject_id', $req->subject_filter);
            }
            if($req->chapter_filter){
                $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('chapter_id', $req->chapter_filter);
                $questions = $questions->where('chapter_id', $req->chapter_filter);
            }
            if($req->topic_filter){
                $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('topic_id', $req->topic_filter);
                $questions = $questions->where('topic_id', $req->topic_filter);
            }
            if($req->question_type_filter){
                $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('question_type', $req->question_type_filter);
                $questions = $questions->where('question_type', $req->question_type_filter);
            }
            if($req->difficulty_level_filter){
                $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('difficulty_level', $req->difficulty_level_filter);
                $questions = $questions->where('difficulty_level', $req->difficulty_level_filter);
            }

            $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->count();
            $questions = $questions->get(); 
            //echo $quizes->toSql(); die;
            //echo '<pre>';print_r($quizes);die;
            $data = array();
            $status_btn = '';
            if($questions){
                foreach($questions as $key => $question){
                    if(count($test_lang) > 1){
                        $question_data = $this->bankQuestionLangModel->where(['question_id'=>$question->bank_question_id, 'language_id'=>1])->first();
                        if(!$question_data){
                            $question_data = $this->bankQuestionLangModel->where(['question_id'=>$question->bank_question_id, 'language_id'=>2])->first();
                        }
                    } else {
                        $question_data = $this->bankQuestionLangModel->where(['question_id'=>$question->bank_question_id, 'language_id'=>$test_lang[0]])->first();
                    }
                    $data[] = array( 
                        "serial_no"=>($key + $row + 1),
                        "question"=>\Illuminate\Support\Str::words($question_data->question, 15, $end=' ...'),
                        "positive_mark"=>'<button class="btn btn-block fs-12 font-medium">'.$question->positive_mark.'</button>',
                        "negative_mark"=>'<button class="btn btn-block fs-12 font-medium">'.$question->negative_mark.'</button>',
                        "action"=>'<a href="'.url('coaching-master/test_series_manager/test/question/view/'.base64_encode($test_id).'/'.base64_encode($question->bank_question_id)).'" class="action-btn reverse">
                              <img src="'.asset('admin/images/eye.svg').'" alt="" />
                              </a>',
                    );
                }
            }
            

            $response = array(
                "draw" => intval($draw),
                "iTotalRecords" => $questiontotalRecord,
                "iTotalDisplayRecords" => $questiontotalRecordwithFilter,
                "aaData" => $data
            );

            echo json_encode($response);die;
        }
        if($req->test_id){
            $questiontotal = $this->model->where('test_id', $id)->count();
            $easyquestiontotal = $this->model->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')->where(['test_id' => $id, 'difficulty_level'=> 1])->count();
            $mediumquestiontotal = $this->model->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')->where(['test_id' => $id, 'difficulty_level'=> 2])->count();
            $hardquestiontotal = $this->model->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')->where(['test_id' => $id, 'difficulty_level'=> 3])->count();
            $engquestiontotal = $this->model
                                    ->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')
                                    ->join('bank_question_langs','bank_question_langs.question_id' ,'=', 'bank_questions.id')
                                    ->where(['test_id' => $id, 'language_id'=> 1])->groupBy('question_id')->count();
            $hindiquestiontotal = $this->model
                                        ->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')
                                        ->join('bank_question_langs','bank_question_langs.question_id' ,'=', 'bank_questions.id')
                                        ->where(['test_id' => $id, 'language_id'=> 2])->groupBy('question_id')->count();
            $test_details = $this->testModel->find($id);
            $subjects = $this->testSubjectModel->where('test_id', $id)->select('subject_id')->groupBy('subject_id')->get();
            $package_details = $this->testPackageModel->find($test_details->test_package_id);
            if($test_details){
                return view('coaching.pages.test.question.details_list')
                             ->withSubjects($subjects)
                             ->withPackageDetails($package_details)
                            ->withQuestiontotalRecord($questiontotal)
                            ->withEasyQuestiontotalRecord($easyquestiontotal)
                            ->withMediumQuestiontotalRecord($mediumquestiontotal)
                            ->withHardQuestiontotalRecord($hardquestiontotal)
                            ->withEngQuestiontotalRecord($engquestiontotal)
                            ->withHindiQuestiontotalRecord($hindiquestiontotal)
                            ->withTestDetails($test_details);
            } else {
                return redirect()->route('coaching.test_series_manager.test.list', base64_encode($test_details->test_package_id));
            }            
        } else {
            return redirect()->route('coaching.test_series_manager.test.list', base64_encode($test_details->test_package_id));
        } 
    }

    /**Get details ethod.
     *
     * @param $req
     *
     * @return json
     */
    public function get_details_list(Request $req) 
    {
        if($req->post()){
            $type = $req->type;
            $html = '';
            if($type == 'subject'){
                $details = $this->packageChapterModel->where('subject_id', $req->id)->orderBy('chapter')->get(); 
                $html = '<option value="">--Select--</option>';
                foreach ($details as $key => $detail) {
                    $html .= '<option value="'.$detail->id.'">'.$detail->chapter.'</option>';
                }  
            }
            if($type == 'chapter'){
                $details = $this->packageTopicModel->where('chapter_id', $req->id)->orderBy('topic')->get();
                $html = '<option value="">--Select--</option>';
                foreach ($details as $key => $detail) {
                    $html .= '<option value="'.$detail->id.'">'.$detail->topic.'</option>';
                }   
            }             
             
            $response = array('status'=>200, 'message'=>'success', 'result'=>$html);    
            return response()->json($response);
        }
    }

    /**
     * Question view details method.
     *
     * @param $req
     *
     * @return view load
     */
    public function view(Request $req) 
    {
        $testDetails = $this->testModel->find(base64_decode($req->test_id));
        if($req->ques_id){
            $id = base64_decode($req->ques_id);            
            $details = $this->model
                            // ->select(DB::raw('bank_questions.*'))
                            ->join('bank_questions','bank_questions.id','=','test_questions.bank_question_id')
                            ->leftJoin('coaching_faculties','coaching_faculties.id','=','bank_questions.coaching_faculty')
                            ->leftJoin('package_subjects','package_subjects.id','=','bank_questions.subject_id')
                            ->leftJoin('package_chapters','package_chapters.id','=','bank_questions.chapter_id')
                            ->leftJoin('package_topics','package_topics.id','=','bank_questions.topic_id')
                            ->where('bank_question_id', $id)
                            ->first();
            // dd($details);
            $answerDetailsEng = $this->bankQuestionAnswerModel->where(['language_id'=> 1, 'question_id'=>$id])->get();
            $answerDetailsHindi = $this->bankQuestionAnswerModel->where(['language_id'=> 2, 'question_id'=>$id])->get();
            $quesDetailsEng = $this->bankQuestionLangModel->where(['language_id'=> 1, 'question_id'=>$id])->first();
            $quesDetailsHindi = $this->bankQuestionLangModel->where(['language_id'=> 2, 'question_id'=>$id])->first();
            if($details){
                return view('coaching.pages.test.question.view')
                    ->withAnswerDetailsEng($answerDetailsEng)
                    ->withAnswerDetailsHindi($answerDetailsHindi)
                    ->withQuesDetailsEng($quesDetailsEng)
                    ->withQuesDetailsHindi($quesDetailsHindi)
                    ->withTestDetails($testDetails)
                    ->withDetails($details);
            } else {
                return redirect()->route('coaching.test_series_manager.test.list', base64_encode($testDetails->test_package_id));
            }
        } else {
            return redirect()->route('coaching.test_series_manager.test.list', base64_encode($testDetails->test_package_id));
        } 
    }

    /**Question update marks method.
     *
     * @param $req
     *
     * @return json
     */
    public function update_question_marks(Request $req) 
    {
        if($req->post()){
            $type = $req->type;
            $test_id = base64_decode($req->id);
            $marks = $req->mark;
            $all_questions = $this->model->where('test_id', $test_id)->get();
            $question_not_updated = [];
            if($all_questions){
                foreach ($all_questions as $key => $question) {
                    if($type == 'positive' && $question->negative_mark < $marks){
                        $this->model->where('id', $question->id)->update(['positive_mark' => $marks]);                
                    } elseif($type == 'negative' && $question->positive_mark > $marks){
                        $this->model->where('id', $question->id)->update(['negative_mark' => $marks]);                
                    } else {
                        array_push($question_not_updated, $question->id);
                    }
                }
            }
            $response = array('status'=>200, 'message'=>'success', 'result'=>$question_not_updated);    
            return response()->json($response);
        }
    }

    /**Question update individula marks method.
     *
     * @param $req
     *
     * @return json
     */
    public function test_question_marks_save(Request $req) 
    {
        if($req->post()){
            $type = $req->type;
            $question_id = base64_decode($req->id);
            $marks = $req->mark;
            $question = $this->model->where('id', $question_id)->first();
            $question_not_updated = [];
            if($question){
                if($type == '1'){
                    if($question->negative_mark < $marks){
                        $this->model->where('id', $question_id)->update(['positive_mark' => $marks]); 
                        $response = array('status'=>200, 'message'=>'success', 'result'=>$question_not_updated);  
                    } else {
                        $response = array('status'=>201, 'message'=>'Mark should be greater than negative mark', 'result'=>[]);   
                    }
                                    
                } else {
                    if($question->positive_mark > $marks){
                        $this->model->where('id', $question_id)->update(['negative_mark' => $marks]); 
                        $response = array('status'=>200, 'message'=>'success', 'result'=>$question_not_updated); 
                    } else {
                        $response = array('status'=>201, 'message'=>'Mark should be less than positive mark', 'result'=>[]);   
                    }              
                }
            }
            return response()->json($response);
        }
    }

    /**
     * Question delete method.
     *
     * @param $req
     *
     * @return json
     */
    public function delete(Request $req) 
    {
        $response = [];
        if($req->id){
            $id = base64_decode($req->id);
            $question_details = $this->model->find($id);
            $this->model->where('id', $id)->delete(); 
            $this->questionAssignedModel->where(['section_type'=>1, 'section_id'=>$question_details->test_id,'bank_question_id'=>$question_details->bank_question_id])->delete();
            $total_question = $this->model->where('test_id', $question_details->test_id)->count();
            $testDetails = $this->testModel->find($question_details->test_id);
            $report_question = $this->testPackageModel
                                    ->leftJoin('package_reviews','package_reviews.package_id','=','test_packages.id')
                                    ->leftJoin('package_review_details','package_review_details.package_review_id','=','package_reviews.id')
                                    ->leftJoin('reported_sections','package_reviews.id','=','reported_sections.package_review_id')
                                    ->where(['package_id'=>$testDetails->test_package_id, 'test_id'=>$testDetails->id, 'bank_question_id'=>$question_details->bank_question_id])
                                    ->select('reported_sections.id')
                                    ->get();
            if($report_question){
                foreach ($report_question as $key => $report) {
                    DB::table('reported_sections')->where('id', $report->id)->delete();
                }
            }
            $response = array('status'=>200, 'message'=>'success', 'result'=>[], 'total_set' => $total_question); 
            return response()->json($response);
        }
    }

    /**
     * Question delete all method.
     *
     * @param $req
     *
     * @return json
     */
    public function delete_all(Request $req) 
    {
        $response = [];
        $ids = $req->ids;
        foreach ($ids as $key => $value) {
            $id = base64_decode($value);
            $question_details = $this->model->find($id);
            if($question_details){
                $this->model->where('id', $id)->delete(); 
                $this->questionAssignedModel->where(['section_type'=>1, 'section_id'=>$question_details->test_id,'bank_question_id'=>$question_details->bank_question_id])->delete();
            }
        }
        $total_question = $this->model->where('test_id', $question_details->test_id)->count();
        $response = array('status'=>200, 'message'=>'success', 'result'=>[], 'total_set' => $total_question); 
        return response()->json($response);
    }

    /**
     * Import page method.
     *
     */
    public function import(Request $req) 
    {
        if($req->test_id){
            /*****************post method********************/
            if($req->file('fileUpload')){
                $subjects = $this->testSubjectModel->where('test_id', base64_decode($req->test_id))->select('subject_id')->groupBy('subject_id')->get();
                $subs = [];
                if($subjects){
                    foreach($subjects as $sub){
                        array_push($subs, $sub->subject_id);
                    }
                }
                $cahpters = $this->packageChapterModel->whereIn('subject_id', $subs)->orderBy('subject_id')->get();
                $chaps = [];
                if($cahpters){
                    foreach($cahpters as $chapter){
                        array_push($chaps, $chapter->id);
                    }
                }
                $topics = $this->packageTopicModel->whereIn('chapter_id', $chaps)->orderBy('chapter_id')->get();

                //$coachingFaculties = $this->coachingFacultyModel->get();
                /***********subject wise faculty***********************/
                $coachingFaculties = $this->testFacultyModel
                                            ->join('coaching_faculties', 'test_faculties.faculty_id', '=', 'coaching_faculties.id')
                                            ->where('test_id', base64_decode($req->test_id))
                                            ->groupBy('faculty_id')->get();  
                /***********subject wise faculty***********************/

                $req->validate([
                    'fileUpload' => 'required'
                ]);
                $path = $req->file('fileUpload')->getRealPath();
                $data = \Excel::load($path)->get();
                $err = 0;
                //echo '<pre>';print_r($data->toArray());die;
                $actual_colums = ['sr._no.','subject_name','chapter_name','topic_name','faculty_name','question_type','correct_answer','right_marks','negative_marks','difficulty_level','range_from','range_to','question','question_hindi','option1','option2','option3','option4','option5','option6','option7','option8','option9','option10','option11','option12','option13','option14','option15','option16','solution','solution_url','option_hindi1','option_hindi2','option_hindi3','option_hindi4','option_hindi5','option_hindi6','option_hindi7','option_hindi8','option_hindi9','option_hindi10','option_hindi11','option_hindi12','option_hindi13','option_hindi14','option_hindi15','option_hindi16','solution_hindi','solution_url_hindi','direction'];
                $html = '<table class="table card-table table-vcenter outline-border">';
                $invalid = 0;
                $failed = $data->count() - 100;
                if($data->count()){
                    $html .= '<thead>
                            <tr class="bg-light">';
                    foreach ($data->first()->keys() as $key => $head) {
                        $html .= '<th>'.ucfirst(str_replace('_', ' ', $head)).'</th>';
                        if(!in_array($head, $actual_colums)){
                            //echo '<pre>';echo $head;die; 
                            $invalid = 1;
                            break;
                        }
                    }
                    if($invalid == 0){
                        $html .= '</tr>
                          </thead>
                          <tbody>';
                          // dd($data);
                        foreach ($data as $key => $value) {
                            $items = $value->toArray();
                            // dd($items);
                            if($key < 100){
                                if(isset($items['question']) || isset($items['question_hindi'])){
                                    $html .= '<tr>';                        
                                    //echo '<pre>'; print_r($items);die;
                                    if($items){
                                        foreach ($items as $item_key => $item) {
                                            $err = 1;
                                            if($item_key !== 0){

                                                switch ($item_key) {
                                                    case "question":
                                                        $html .= '<td><textarea class="form-control form_field_import " name="question[]" >'.$item.'</textarea></td>';
                                                        break;
                                                    case "question_hindi":
                                                        $html .= '<td><textarea class="form-control form_field_import" name="question_hindi[]"  >'.$item.'</textarea></td>';
                                                        break;
                                                    case "subject_name":
                                                    
                                                        $html .= '<td>
                                                                <select name="subject[]" class="form-control form_select_import import_fields" data-type="subject">
                                                                <option value="">Select Subject</option>';
                                                        if($subjects){
                                                            foreach ($subjects as $key => $subject) {
                                                                $subject_name = (isset($subject->subjectByTestSubject) ? $subject->subjectByTestSubject->subject : '');
                                                                $html .= '<option value="'.$subject->subject_id.'" '.((strtolower($subject_name) == strtolower(trim($item))) ? 'selected' : '').'>'.$subject_name.'</option>';
                                                            }
                                                        }
                                                        $html .= '  </select>
                                                            </td>';                                        
                                                        break;
                                                    case "chapter_name":
                                                        $select_chapters = $this->testSubjectModel
                                                                        ->join('package_subjects','package_subjects.id','=','test_subjects.subject_id')
                                                                        ->join('package_chapters','package_subjects.id','=','package_chapters.subject_id')
                                                                        ->where('test_id', base64_decode($req->test_id))
                                                                        ->whereRaw('LOWER(subject) = "' . strtolower(trim($items['subject_name'])) . '"')->orderBy('subject')->select('package_chapters.*')->get();
                                                        //dd($select_chapters);
                                                        $html .= '<td>
                                                                <select name="chapter[]" class="form-control form_select_import import_fields" data-type="chapter" data-selected="'.strtolower(trim($item)).'">
                                                                <option value="">Select Chapter</option>';
                                                        if(count($select_chapters)>0){
                                                            foreach ($select_chapters as $key => $cahpter) {
                                                                $html .= '<option value="'.$cahpter->id.'" '.((strtolower($cahpter->chapter) == strtolower(trim($item))) ? 'selected' : '').'>'.$cahpter->chapter.'</option>';
                                                            }
                                                        }
                                                        $html .= '  </select>
                                                            </td>';                                        
                                                        break;
                                                    case "topic_name":
                                                        $select_topics = $this->testSubjectModel
                                                                        ->join('package_subjects','package_subjects.id','=','test_subjects.subject_id')
                                                                        ->join('package_chapters','package_subjects.id','=','package_chapters.subject_id')
                                                                        ->join('package_topics','package_chapters.id','=','package_topics.chapter_id')
                                                                        ->where('test_id', base64_decode($req->test_id))
                                                                        
                                                                        ->whereRaw('LOWER(subject) = "' . strtolower(trim($items['subject_name'])) . '"')
                                                                        ->whereRaw('LOWER(chapter) = "' . strtolower(trim($items['chapter_name'])) . '"')->orderBy('chapter')->select('package_topics.*')->get();
                                                        $html .= '<td>
                                                                <select name="topic[]" class="form-control form_select_import import_fields" data-type="topic" data-selected="'.(trim($item)).'">
                                                                <option value="">Select Topic</option>';
                                                        if($select_topics){
                                                            foreach ($select_topics as $key => $topic) {
                                                                $html .= '<option value="'.$topic->id.'" '.((strtolower($topic->topic) == strtolower(trim($item))) ? 'selected' : '').'>'.$topic->topic.'</option>';
                                                            }
                                                        }
                                                        $html .= '  </select>
                                                            </td>';                                        
                                                        break;
                                                    case "faculty_name":
                                                        $html .= '<td>
                                                                <select name="faculty[]" class="form-control form_select_import import_fields"  data-selected="'.(trim($item)).'">
                                                                <option value="">Faculty</option>';
                                                        if($coachingFaculties){
                                                            foreach ($coachingFaculties as $key => $coachingFaculty) {
                                                                $html .= '<option value="'.$coachingFaculty->id.'" '.((strtolower($coachingFaculty->faculty_name) == strtolower(trim($item))) ? 'selected' : '').'>'.$coachingFaculty->faculty_name.'</option>';
                                                            }
                                                        }
                                                        $html .= '  </select>
                                                            </td>';                                        
                                                        break;
                                                    case "question_type":
                                                        $html .= '<td>
                                                                <select name="question_type[]" class="form-control form_select_import question_types">
                                                                <option value="1" '.($item == 'Multiple Choice' ? 'selected' : '').'>Multiple Choice</option>
                                                                <option value="2" '.($item == 'Multiple Response' ? 'selected' : '').'>Multiple Response</option>
                                                                <option value="3" '.($item == 'True/False' ? 'selected' : '').'>True/False</option>
                                                                <option value="4" '.($item == 'Fill In The Blanks' ? 'selected' : '').'>Fill In The Blanks</option>
                                                                <option value="5" '.($item == 'Match The Following' ? 'selected' : '').'>Match The Following</option>
                                                                <option value="6" '.($item == 'Match Matrix' ? 'selected' : '').'>Match Matrix</option>
                                                                </select>
                                                            </td>';                                        
                                                        break;
                                                    case "difficulty_level":
                                                        $html .= '<td>
                                                                <select name="difficulty_level[]" class="form-control form_select_import">
                                                                <option value="1" '.(strtolower(trim($item)) == strtolower('Easy') ? 'selected' : '').'>Easy</option>
                                                                <option value="2" '.(strtolower(trim($item)) == strtolower('Medium') ? 'selected' : '').'>Medium</option>
                                                                <option value="3" '.(strtolower(trim($item)) == strtolower('Hard') ? 'selected' : '').'>Hard</option>
                                                                </select>
                                                            </td>';                                        
                                                        break;
                                                    case "sr._no.":  
                                                        $html .= '<td>'.$item.'</td>';
                                                        break;
                                                    case strstr($item_key,'option'):  
                                                        $html .= '<td><textarea class="form-control form_field_import '.$item_key.'" name="'.$item_key.'[]" >'.$item.'</textarea></td>';
                                                        break;
                                                    case "solution":  
                                                        $html .= '<td><input type="text" name="'.$item_key.'[]" class="form-control form_field_import" value="'.$item.'" style="width: 300px !important;"></td>';
                                                        break;
                                                    case "solution_video_url":  
                                                        $html .= '<td><input type="text" name="'.$item_key.'[]" class="form-control form_field_import" value="'.$item.'" style="width: 300px !important;"></td>';
                                                        break;
                                                    case "solution_hindi":  
                                                        $html .= '<td><input type="text" name="'.$item_key.'[]" class="form-control form_field_import" value="'.$item.'" style="width: 300px !important;"></td>';
                                                        break;
                                                    case "solution_video_url_hindi":  
                                                        $html .= '<td><input type="text" name="'.$item_key.'[]" class="form-control form_field_import" value="'.$item.'" style="width: 300px !important;"></td>';
                                                        break;
                                                    case "direction":
                                                        $html .= '<td><textarea class="form-control form_field_import '.$item_key.'" name="'.$item_key.'[]" >'.$item.'</textarea></td>';
                                                        break;
                                                    default:  
                                                        $html .= '<td><input type="text" name="'.$item_key.'[]" class="form-control form_field_import '.$item_key.'" value="'.$item.'" style="width: 300px !important;"></td>';
                                                        break;
                                                }                              
                                            }
                                        }
                                    }
                                    $html .= '</tr>';
                                }
                            }
                        }
                    }
                    
                }
                $html .= '</tbody>
                    </table>';

                if($err == 1 || $invalid == 0){
                    $response = array('status'=>200, 'message'=>'success', 'result'=>$html, 'failed'=>$failed); 
                } else {
                    $response = array('status'=>201, 'message'=>'Please choose proper file', 'result'=>$html); 
                }
                
                return response()->json($response);
            }
            /*****************post method********************/

            $id = base64_decode($req->test_id);
            $test_details = $this->testModel->find($id);
            if($test_details){
                $import_history = $this->savedQuestionModel->where('section_type', 1)->where('coaching_id', Auth::guard('coaching')->user()->coaching_id)->where('test_id', $id)->orderBy('created_at', 'DESC')->get();
                $update = $this->testPackageModel->where('id', $test_details->test_package_id)->update(['coaching_last_url'=>request()->path()]);
                $update = $this->testModel->where('id', $test_details->id)->update(['coaching_test_last_url'=>request()->path()]);
                return view('coaching.pages.test.question.import')
                            ->withImportHistory($import_history)
                            ->withTestDetails($test_details);
            } else {
                return redirect()->route('coaching.test_series_manager.test.list', base64_encode($test_details->test_package_id));
            }            
        } else {
            return redirect()->route('coaching.test_series_manager.test.list', base64_encode($test_details->test_package_id));
        } 
    }

    /**
     * Question single history delete method.
     *
     * @param $req
     *
     * @return json
     */
    public function delete_single_history(Request $req) 
    {
        $response = [];
        if($req->id){
            $history = $this->savedQuestionModel->find(base64_decode($req->id));
            if($history){
                $this->savedQuestionModel->where('id', base64_decode($req->id))->delete(); 
                $response = array('status'=>200, 'message'=>'success', 'result'=>[]); 
            } else {
                $response = array('status'=>201, 'message'=>'No history found..', 'result'=>[]); 
            }
            return response()->json($response);
        }
    }

    /**
     * Question import history delete method.
     *
     * @param $req
     *
     * @return json
     */
    public function import_history_delete(Request $req) 
    {
        $response = [];
        if($req->type){
            $history = $this->savedQuestionModel->where('section_type', $req->type)->get();
            if(count($history)>0){
                $this->savedQuestionModel->where('section_type', $req->type)->delete(); 
                $response = array('status'=>200, 'message'=>'success', 'result'=>[]); 
            } else {
                $response = array('status'=>201, 'message'=>'No history found..', 'result'=>[]); 
            }
            return response()->json($response);
        }
    }

    /**
     * Import save method.
     *
     */
    public function import_save(Request $req) 
    {
        $html = '';
        if($req->test_id){
            //dd($req->post());
            /*****************post method********************/
            if($req->post()){
                $total_data = count($req->subject);
                $total_data_inserted = 0;
                
                if(isset($req->question)){
                    foreach ($req->question as $key => $question) {
                        $unique_id = mt_rand(100000000,999999999);
                        if($question){

                            $testSubect = $this->testSubjectModel->where(['test_id' => base64_decode($req->test_id), 'subject_id' => $req->subject[$key]])->first();
                            $getExamType = $this->packageSubjectModel->where('id',$req->subject[$key])->first();

                            /******************QUESTION BANK SECTION************************/
                            $question_master_arr_question_bank = [
                                    'unique_id' => $unique_id,
                                    'coaching_id' => Auth::guard('coaching')->user()->coaching_id,
                                    'question' => $question,
                                    'exam_type_id' => $getExamType->exam_type_id,
                                    'subject_id' => $req->subject[$key],
                                    'chapter_id' => $req->chapter[$key],
                                    'topic_id' => isset($req->topic[$key]) ? $req->topic[$key] : 0,
                                    'coaching_faculty' => isset($req->faculty[$key]) ? $req->faculty[$key] : 0,
                                    'question_type' => $req->question_type[$key],
                                    'difficulty_level' => $req->difficulty_level[$key],
                                    'positive_mark' => $req->right_marks[$key],
                                    'negative_mark' => $req->negative_marks[$key],
                                    'correct_answer' => strtolower($req->correct_answer[$key]),
                                    'range_from' => $req->range_from[$key],
                                    'range_to' => $req->range_to[$key],
                                    'typist_name' => Auth::guard('coaching')->user()->manager_holder_name,
                                    'created_date'=>date('Y-m-d')
                            ];
                            $insert_master_question_bank = $this->bankQuestionModel->create($question_master_arr_question_bank);

                            $question_master_arr = [
                                    'bank_question_unique_id'=>$unique_id,
                                    'bank_question_id'=>$insert_master_question_bank->id,
                                    'test_id' => base64_decode($req->test_id),
                                    'test_subject_id' => isset($testSubect) ? $testSubect->id : 0,
                                    'positive_mark' => $req->right_marks[$key],
                                    'negative_mark' => $req->negative_marks[$key],
                                    'direction' => $req->direction[$key],
                            ];
                            $insert_master = $this->model->create($question_master_arr);

                            $assigned_arr = [
                                    'bank_question_id'=>$insert_master_question_bank->id,
                                    'section_id'=>base64_decode($req->test_id),
                                    'section_type'=>1,
                                    'manager_id'=>Auth::guard('coaching')->user()->id
                            ];
                            $insert_assigned = $this->questionAssignedModel->create($assigned_arr);
                            /******************QUESTION BANK SECTION************************/

                            if($insert_master->id){
                                $total_data_inserted = $total_data_inserted + 1;
                            }

                            /******************QUESTION BANK SECTION************************/
                            $question_details_eng_arr_question_bank = [
                                    'question_id' => $insert_master_question_bank->id,
                                    'question' => $question,
                                    'language_id' => 1,
                                    'solution' => $req->solution[$key],
                                    'solution_url' => $req->solution_url[$key],
                            ];
                            $insert_eng_question_bank = $this->bankQuestionLangModel->create($question_details_eng_arr_question_bank);
                            /******************QUESTION BANK SECTION************************/

                            for($eng = 1; $eng < 9; $eng ++){
                                //echo $eng.'='.$req->input('option'.$eng)[$key]; die;
                                /***********answer for english******************/
                                if($req->input('option'.$eng)[$key]){
                                    /******************QUESTION BANK SECTION************************/
                                    $answer_eng_arr_question_bank = [
                                            'question_id' => $insert_master_question_bank->id,
                                            'question_lang_id' => $insert_eng_question_bank->id,
                                            'language_id' => 1,
                                            'answer' => $req->input('option'.$eng)[$key],
                                            'options' => $req->input('option'.($eng+8))[$key],
                                    ];
                                    $insert_answer_eng_question_bank = $this->bankQuestionAnswerModel->create($answer_eng_arr_question_bank);
                                    /******************QUESTION BANK SECTION************************/
                                }
                            }

                            /***********for hindi******************/
                            if(isset($req->question_hindi[$key])){
                                /******************QUESTION BANK SECTION************************/
                                $question_details_hindi_arr_question_bank = [
                                        'question_id' => $insert_master_question_bank->id,
                                        'question' => $req->question_hindi[$key],
                                        'language_id' => 2,
                                        'solution' => $req->solution_hindi[$key],
                                        'solution_url' => $req->solution_url_hindi[$key],
                                ];
                                $insert_hindi_question_bank = $this->bankQuestionLangModel->create($question_details_hindi_arr_question_bank);
                                /******************QUESTION BANK SECTION************************/

                                for($hindi = 1; $hindi < 9; $hindi ++){
                                    /***********answer for hindi******************/
                                    if($req->input('option_hindi'.$hindi)[$key]){
                                        /******************QUESTION BANK SECTION************************/
                                        $answer_hindi_arr_question_bank = [
                                                'question_id' => $insert_master_question_bank->id,
                                                'question_lang_id' => $insert_hindi_question_bank->id,
                                                'language_id' => 2,
                                                'answer' => $req->input('option_hindi'.$hindi)[$key],
                                                'options' => $req->input('option_hindi'.($hindi+8))[$key],
                                        ];
                                        $insert_answer_hindi_question_bank = $this->bankQuestionAnswerModel->create($answer_hindi_arr_question_bank);
                                        /******************QUESTION BANK SECTION************************/
                                    }
                                }
                            }
                            
                        }
                    }
                } elseif(isset($req->question_hindi)){
                    foreach ($req->question_hindi as $key => $question) {
                        $unique_id = mt_rand(100000000,999999999);
                        if($question){

                            $testSubect = $this->testSubjectModel->where(['test_id' => base64_decode($req->test_id), 'subject_id' => $req->subject[$key]])->first();
                            $getExamType = $this->packageSubjectModel->where('id',$req->subject[$key])->first();
                            /******************QUESTION BANK SECTION************************/
                            $question_master_arr_question_bank = [
                                    'unique_id' => $unique_id,
                                    'coaching_id' => Auth::guard('coaching')->user()->coaching_id,
                                    'question' => $question,
                                    'exam_type_id' => $getExamType->exam_type_id,
                                    'subject_id' => $req->subject[$key],
                                    'chapter_id' => $req->chapter[$key],
                                    'topic_id' => isset($req->topic[$key]) ? $req->topic[$key] : 0,
                                    'coaching_faculty' => isset($req->faculty[$key]) ? $req->faculty[$key] : 0,
                                    'question_type' => $req->question_type[$key],
                                    'difficulty_level' => $req->difficulty_level[$key],
                                    'positive_mark' => $req->right_marks[$key],
                                    'negative_mark' => $req->negative_marks[$key],
                                    'correct_answer' => strtolower($req->correct_answer[$key]),
                                    'range_from' => $req->range_from[$key],
                                    'range_to' => $req->range_to[$key],
                                    'typist_name' => Auth::guard('coaching')->user()->manager_holder_name,
                                    'created_date'=>date('Y-m-d')
                            ];
                            $insert_master_question_bank = $this->bankQuestionModel->create($question_master_arr_question_bank);

                            $question_master_arr = [    
                                    'bank_question_unique_id'=>$unique_id,
                                    'bank_question_id'=>$insert_master_question_bank->id,
                                    'test_id' => base64_decode($req->test_id),
                                    'test_subject_id' => isset($testSubect) ? $testSubect->id : 0,
                                    'positive_mark' => $req->right_marks[$key],
                                    'negative_mark' => $req->negative_marks[$key],
                                    'direction' => $req->direction[$key],
                            ];
                            $insert_master = $this->model->create($question_master_arr);

                            $assigned_arr = [
                                    'bank_question_id'=>$insert_master_question_bank->id,
                                    'section_id'=>base64_decode($req->test_id),
                                    'section_type'=>1,
                                    'manager_id'=>Auth::guard('coaching')->user()->id
                            ];
                            $insert_assigned = $this->questionAssignedModel->create($assigned_arr);
                            /******************QUESTION BANK SECTION************************/

                            if($insert_master->id){
                                $total_data_inserted = $total_data_inserted + 1;
                            }

                            /******************QUESTION BANK SECTION************************/
                            $question_details_hindi_arr_question_bank = [
                                    'question_id' => $insert_master_question_bank->id,
                                    'question' => $req->question_hindi[$key],
                                    'language_id' => 2,
                                    'solution' => $req->solution_hindi[$key],
                                    'solution_url' => $req->solution_url_hindi[$key],
                            ];
                            $insert_hindi_question_bank = $this->bankQuestionLangModel->create($question_details_hindi_arr_question_bank);
                            /******************QUESTION BANK SECTION************************/

                            for($hindi = 1; $hindi < 9; $hindi ++){
                                /***********answer for hindi******************/
                                if($req->input('option_hindi'.$hindi)[$key]){
                                    /******************QUESTION BANK SECTION************************/ 
                                    $answer_hindi_arr_question_bank = [
                                            'question_id' => $insert_master_question_bank->id,
                                            'question_lang_id' => $insert_hindi_question_bank->id,
                                            'language_id' => 2,
                                            'answer' => $req->input('option_hindi'.$hindi)[$key],
                                            'options' => $req->input('option_hindi'.($hindi+8))[$key],
                                    ];
                                    $insert_answer_hindi_question_bank = $this->bankQuestionAnswerModel->create($answer_hindi_arr_question_bank);
                                    /******************QUESTION BANK SECTION************************/ 
                                }
                            }
                        }
                    }
                }
                /*********inset in save question table****************/
                $imported_filename = time().'.xlsx';
                if(isset($req->filename_import)){
                   $filename = explode('.', $req->filename_import);
                    if(count($filename)>0){
                        $imported_filename = $filename[0].rand(0, 10).'.'.$filename[1];
                    } 
                }
                
                $saved_question_arr = [
                        'filename' => $imported_filename,
                        'import_by' => Auth::guard('coaching')->user()->manager_holder_name,
                        'section_type' => 1,
                        'test_id' => base64_decode($req->test_id),
                        'coaching_id' => Auth::guard('coaching')->user()->coaching_id,
                        // 'ip_address' => $_SERVER['HTTP_X_FORWARDED_FOR'],
                        'ip_address' => (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']),
                        'details' => $total_data_inserted.' inserted, '.(($total_data - $total_data_inserted)+$req->failed_count).' failed',
                ];
                $history_id = $this->savedQuestionModel->create($saved_question_arr);
                $update = $this->testModel->where('id', base64_decode($req->test_id))->update(['completed_step'=>2]);
            }

            $html = '<div class="table-responsive">
                              <table class="table card-table table-vcenter text-nowrap outline-border tbl-gr-acrdn">
                                <thead>
                                  <tr>
                                    <th>Upload File</th>
                                    <th>Uploaded By</th>
                                    <th>Ip Address</th> 
                                    <th>Date & Time</th>                                     
                                    <th>Result</th>                                   
                                  </tr>
                                </thead>
                                <tbody>  
                                  <tr>
                                        <th>'.$imported_filename.'</th>
                                        <th>'.Auth::guard('coaching')->user()->manager_holder_name.'</th>
                                        <th>'.(isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']).'</th> 
                                        <th>'.date('d-m-Y H:i:s').'</th>                                         
                                        <th>'.$total_data_inserted.' inserted, '.(($total_data - $total_data_inserted)+$req->failed_count).' failed'.'</th>                                 
                                    </tr>                         
                                </tbody>
                              </table>
                            </div>';
        }
        $response = array('status'=>200, 'message'=>'success', 'result'=>$html); 
        return response()->json($response);
    }

    /**
     * Vault list page method.
     *
     */
    public function vault(Request $req) 
    {
        if($req->test_id){
            $subjects = $this->testSubjectModel->where('test_id', base64_decode($req->test_id))->select('subject_id')->groupBy('subject_id')->get();
            $sub_ids = [];
            $langArray = [];
            if($subjects){
                foreach ($subjects as $key => $subject) {
                    $subject_name = (isset($subject->subjectByTestSubject) ? $subject->subjectByTestSubject->subject : '');
                    array_push($sub_ids, $subject->subject_id);
                }
            }
            $languages = $this->testLanguageModel->where('test_id', base64_decode($req->test_id))->orderBy('language_id', 'ASC')->select('language_id')->get();
            if(isset($languages)){
                foreach ($languages as $langkey => $lang) {
                    array_push($langArray, $lang['language_id']);
                }
            }
            /*****************post method********************/
            if($req->post()){
                $internal_coaching = $this->coachingMasterModel->find(Auth::guard('coaching')->user()->coaching_id);                   
                $draw = $req->draw;
                $row = $req->start;
                $rowperpage = $req->length; // Rows display per page
                $columnIndex = $req->order[0]['column']; // Column index
                $columnName = $req->columns[$columnIndex]['data'] ? $req->columns[$columnIndex]['data'] : 'id'; // Column name
                $columnSortOrder = $req->order[0]['dir']; // asc or desc
                
                if($columnName == 'question_check' || $columnName == 'serial_no'){
                    $columnName = 'bank_questions.id';
                }
                if($columnName == 'question'){
                    $columnName = 'bank_questions.question';
                }
                ## Total number of records without filtering
                $questiontotalRecord = $this->bankQuestionModel
                                        ->select(DB::raw('*, bank_questions.id, GROUP_CONCAT(language_id) language_ids, (CASE WHEN section_id > 0 THEN "Assigned" ELSE "Not Assigned" END) assign_status, bank_questions.created_at'))
                                        ->leftJoin('package_subjects', 'package_subjects.id', '=', 'bank_questions.subject_id')
                                        ->leftJoin('package_chapters', 'package_chapters.id', '=', 'bank_questions.chapter_id')
                                        ->leftJoin('question_assigneds', 'question_assigneds.bank_question_id', '=', 'bank_questions.id')
                                        ->leftJoin('bank_question_langs', 'bank_question_langs.question_id', '=', 'bank_questions.id')
                                        ->groupBy('bank_questions.id');

                ## Total number of record with filtering
                $questiontotalRecordwithFilter = $this->bankQuestionModel
                                                    ->select(DB::raw('*, bank_questions.id, GROUP_CONCAT(language_id) language_ids, (CASE WHEN section_id > 0 THEN "Assigned" ELSE "Not Assigned" END) assign_status, bank_questions.created_at'))
                                                    ->leftJoin('package_subjects', 'package_subjects.id', '=', 'bank_questions.subject_id')
                                                    ->leftJoin('package_chapters', 'package_chapters.id', '=', 'bank_questions.chapter_id')
                                                    ->leftJoin('question_assigneds', 'question_assigneds.bank_question_id', '=', 'bank_questions.id')
                                                    ->leftJoin('bank_question_langs', 'bank_question_langs.question_id', '=', 'bank_questions.id')                           
                                                    ->groupBy('bank_questions.id');

                ## Fetch records
                $questions = $this->bankQuestionModel
                                ->select(DB::raw('*, bank_questions.id, GROUP_CONCAT(language_id) language_ids, (CASE WHEN section_id > 0 THEN "Assigned" ELSE "Not Assigned" END) assign_status, bank_questions.created_at created'))
                                ->leftJoin('package_subjects', 'package_subjects.id', '=', 'bank_questions.subject_id')
                                ->leftJoin('package_chapters', 'package_chapters.id', '=', 'bank_questions.chapter_id')
                                ->leftJoin('question_assigneds', 'question_assigneds.bank_question_id', '=', 'bank_questions.id')
                                ->leftJoin('bank_question_langs', 'bank_question_langs.question_id', '=', 'bank_questions.id')
                                ->groupBy('bank_questions.id')
                                ->orderBy($columnName, $columnSortOrder)
                                ->skip($row)
                                ->take($rowperpage);
                if(count($sub_ids)>0){
                    $questiontotalRecord = $questiontotalRecord->whereIn('bank_questions.subject_id', $sub_ids);
                    $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->whereIn('bank_questions.subject_id', $sub_ids);
                    $questions = $questions->whereIn('bank_questions.subject_id', $sub_ids);
                }
                if(count($langArray)>0){
                    $questiontotalRecord = $questiontotalRecord->whereIn('bank_question_langs.language_id', $langArray);
                    $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->whereIn('bank_question_langs.language_id', $langArray);
                    $questions = $questions->whereIn('bank_question_langs.language_id', $langArray);
                }
                if($internal_coaching->is_internal == 1){
                    $questiontotalRecord = $questiontotalRecord->where(['bank_questions.coaching_id'=> Auth::guard('coaching')->user()->coaching_id]);
                    $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where(['bank_questions.coaching_id'=> Auth::guard('coaching')->user()->coaching_id]);
                    $questions = $questions->where(['bank_questions.coaching_id'=> Auth::guard('coaching')->user()->coaching_id]);
                }else{
                    $questiontotalRecord = $questiontotalRecord->where(['bank_questions.coaching_id'=> Auth::guard('coaching')->user()->coaching_id]);
                    $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where(['bank_questions.coaching_id'=> Auth::guard('coaching')->user()->coaching_id]);
                    $questions = $questions->where(['bank_questions.coaching_id'=> Auth::guard('coaching')->user()->coaching_id]);
                } 
                $questiontotalRecord = $questiontotalRecord->get()->count();

                if($req->id_filter){
                    $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('unique_id','LIKE', '%' . $req->id_filter . '%');
                    $questions = $questions->where('unique_id','LIKE', '%' . $req->id_filter . '%');
                }
                if($req->language_filter){
                    if($req->language_filter < 3){
                        $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->havingRaw("language_ids LIKE '%".$req->language_filter."%'");
                        $questions = $questions->havingRaw("language_ids LIKE '%".$req->language_filter."%'");
                    } else {
                        $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->havingRaw("language_ids LIKE '%1,2%'");
                        $questions = $questions->havingRaw("language_ids LIKE '%1,2%'");
                    }
                    
                }
                if($req->examtype_filter){
                    $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('bank_questions.exam_type_id', $req->examtype_filter);
                    $questions = $questions->where('bank_questions.exam_type_id', $req->examtype_filter);
                }
                if($req->subject_filter){
                    $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('bank_questions.subject_id', $req->subject_filter);
                    $questions = $questions->where('bank_questions.subject_id', $req->subject_filter);
                }
                if($req->chapter_filter){
                    $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('chapter_id', $req->chapter_filter);
                    $questions = $questions->where('chapter_id', $req->chapter_filter);
                }
                if($req->topic_filter){
                    $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('topic_id', $req->topic_filter);
                    $questions = $questions->where('topic_id', $req->topic_filter);
                }
                if($req->question_type_filter){
                    $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('question_type', $req->question_type_filter);
                    $questions = $questions->where('question_type', $req->question_type_filter);
                }
                if($req->difficulty_level_filter){
                    $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('difficulty_level', $req->difficulty_level_filter);
                    $questions = $questions->where('difficulty_level', $req->difficulty_level_filter);
                }
                if($req->faculty_filter){
                    $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('coaching_faculty', $req->faculty_filter);
                    $questions = $questions->where('coaching_faculty', $req->faculty_filter);
                }
                if($req->typist_filter){
                    $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->where('typist_name', $req->typist_filter);
                    $questions = $questions->where('typist_name', $req->typist_filter);
                }

                $questiontotalRecordwithFilter = $questiontotalRecordwithFilter->get()->count();
                $questions = $questions->get(); 
                //echo $questions->toSql(); die;
                //echo '<pre>';print_r($quizes);die;
                $data = array();
                $status_btn = '';
                if($questions){
                    foreach($questions as $key => $question){
                        $question_type = '';
                        if($question->question_type == 1){
                            $question_type = 'Multiple Choice';
                        } elseif($question->question_type == 2){
                            $question_type = 'Multiple Response';
                        } elseif($question->question_type == 3){
                            $question_type = 'True/False';
                        } elseif($question->question_type == 4){
                            $question_type = 'Fill In The Blanks';
                        } elseif($question->question_type == 5){
                            $question_type = 'Match The Following';
                        } elseif($question->question_type == 6){
                            $question_type = 'Match Matrix';
                        } elseif($question->question_type == 7){
                            $question_type = 'Essay';
                        } elseif($question->question_type == 8){
                            $question_type = 'Single Digit';
                        } else{
                            $question_type = 'Subjective';
                        }

                        $difficulty_level = '';
                        if($question->difficulty_level == 1){
                            $difficulty_level = 'Easy';
                        } elseif($question->difficulty_level == 2){
                            $difficulty_level = 'Medium';
                        } else{
                            $difficulty_level = 'Hard';
                        } 
                        $assigned_to_this_test = $this->questionAssignedModel->where(['section_id'=> base64_decode($req->test_id), 'bank_question_id'=>$question->id, 'section_type'=>1])->first();
                        $data[] = array( 
                            "question_check"=>'<label class="custom-control custom-checkbox">
                                    <input type="checkbox" class="custom-control-input '.(($assigned_to_this_test) ? '':'single_chk').'" name="chk[]" value="'.base64_encode($question->id).'" '.(($assigned_to_this_test) ? 'disabled':'').'/>
                                    <span class="custom-control-label"></span>
                                  </label>',
                            "serial_no"=>($key + $row + 1),
                            "unique_id"=>$question->unique_id,
                            "question"=>\Illuminate\Support\Str::words($question->question, 15, $end=' ...'),
                            "subject"=>$question->subject,
                            "chapter"=>$question->chapter,
                            "question_type"=>$question_type,
                            "difficulty_level"=>$difficulty_level,
                            "created"=>date('d/m/Y', strtotime($question->created)),
                            "assign_status"=>($question->assign_status=='Assigned') ? '<a href="javascript:void(0)" class="assigned text-warning text-underline" data-id="'.base64_encode($question->id).'" >'.$question->assign_status.'</a>' : $question->assign_status,

                        );
                    }
                }
                

                $response = array(
                    "draw" => intval($draw),
                    "iTotalRecords" => $questiontotalRecord,
                    "iTotalDisplayRecords" => $questiontotalRecordwithFilter,
                    "aaData" => $data
                );

                echo json_encode($response);die;
            }
            $examTypes = $this->examTypeModel->join('tests','tests.exam_type_id','=','exam_types.id')->where('tests.id', base64_decode($req->test_id))->orderBy('exam_type')->get();
            $id = base64_decode($req->test_id);
            $test_details = $this->testModel->find($id);
            $update = $this->testPackageModel->where('id', $test_details->test_package_id)->update(['coaching_last_url'=>request()->path()]);
            $update = $this->testModel->where('id', $test_details->id)->update(['coaching_test_last_url'=>request()->path()]);
            if($test_details){
                return view('coaching.pages.test.question.vault')
                            ->withLanguages($languages)
                            ->withExamTypes($examTypes)
                            ->withSubjects($subjects)
                            ->withTestDetails($test_details);
            } else {
                return redirect()->route('coaching.test_series_manager.test.list', base64_encode($test_details->test_package_id));
            }            
        } else {
            return redirect()->route('coaching.test_series_manager.test.list', base64_encode($test_details->test_package_id));
        } 
    }

    /**
     * Question save from vault save method.
     *
     */
    public function question_save_from_vault(Request $req) 
    {
        if($req->test_id){
            //dd($req->post());
            /*****************post method********************/
            $total_data_inserted = 0;
            if($req->post()){
                if(isset($req->question_ids)){
                    $question_ids = explode(',',trim($req->question_ids,','));
                    //dd($question_ids);
                    foreach ($question_ids as $key => $question_id) {
                        $question_id = base64_decode($question_id);
                        if($question_id){
                            $bank_questions_details = $this->bankQuestionModel->where('id', $question_id)->first();
                            $testSubect = $this->testSubjectModel->where(['test_id' => base64_decode($req->test_id), 'subject_id' => $bank_questions_details->subject_id])->first();
                            if($bank_questions_details){
                                $question_master_arr = [
                                        'bank_question_unique_id'=>$bank_questions_details->unique_id,
                                        'bank_question_id'=>$bank_questions_details->id,
                                        'test_id' => base64_decode($req->test_id),
                                        'test_subject_id' => isset($testSubect) ? $testSubect->id : 0,
                                        'positive_mark' => $bank_questions_details->positive_mark,
                                        'negative_mark' => $bank_questions_details->negative_mark
                                ];
                                $insert_master = $this->model->create($question_master_arr);
                                $assigned_arr = [
                                        'bank_question_id'=>$question_id,
                                        'section_id'=>base64_decode($req->test_id),
                                        'section_type'=>1,
                                        'manager_id'=>Auth::guard('coaching')->user()->id
                                ];
                                $insert_assigned = $this->questionAssignedModel->create($assigned_arr);

                                if($insert_master->id){
                                    $total_data_inserted = $total_data_inserted + 1;
                                }
                            }
                        }
                    }
                    $update = $this->testModel->where('id', base64_decode($req->test_id))->update(['completed_step'=>2]);
                }
            }
        }
        if($total_data_inserted > 0){
            $response = array('status'=>200, 'message'=>'You Have Successfully Imported '.$total_data_inserted.' Questions From Question Bank'); 
        } else {
            $response = array('status'=>201, 'message'=>'Some error occurred'); 
        }
        return response()->json($response);
    }

    /**Set settings method.
     *
     * @param $req
     *
     * @return json
     */
    public function set_settings(Request $req) 
    {
        if($req->test_id){
            //dd($req->post());
            /*****************post method********************/
            if($req->post()){
                $total_data = count($req->question);
                $total_data_inserted = 0;
                if($req->question){
                    foreach ($req->question as $key => $question) {
                        if($question){

                            $testSubect = $this->testSubjectModel->where(['test_id' => base64_decode($req->test_id), 'subject_id' => $req->subject[$key]])->first();
                            $question_master_arr = [
                                    'test_id' => base64_decode($req->test_id),
                                    'question' => $question,
                                    'test_subject_id' => isset($testSubect) ? $testSubect->id : 0,
                                    'subject_id' => $req->subject[$key],
                                    'chapter_id' => $req->chapter[$key],
                                    'topic_id' => $req->topic[$key],
                                    'coaching_faculty' => $req->faculty[$key],
                                    'question_type' => $req->question_type[$key],
                                    'difficulty_level' => $req->difficulty_level[$key],
                                    'positive_mark' => $req->right_marks[$key],
                                    'negative_mark' => $req->negative_marks[$key],
                                    'correct_answer' => strtolower($req->correct_answer[$key]),
                                    'range_from' => $req->range_from[$key],
                                    'range_to' => $req->range_to[$key],
                                    'typist_name' => Auth::guard('coaching')->user()->manager_holder_name,
                                    'created_date'=>date('Y-m-d')
                            ];
                            $insert_master = $this->model->create($question_master_arr);
                            if($insert_master->id){
                                $total_data_inserted = $total_data_inserted + 1;
                            }

                            /***********for english******************/
                            $question_details_eng_arr = [
                                    'question_id' => $insert_master->id,
                                    'question' => $question,
                                    'language_id' => 1,
                                    'solution' => $req->solution[$key],
                                    'solution_url' => $req->solution_url[$key],
                            ];
                            $insert_eng = $this->testQuestionLangModel->create($question_details_eng_arr);

                            for($eng = 1; $eng < 9; $eng ++){
                                //echo $eng.'='.$req->input('option'.$eng)[$key]; die;
                                /***********answer for english******************/
                                if($req->input('option'.$eng)[$key]){
                                    $answer_eng_arr = [
                                            'question_id' => $insert_master->id,
                                            'question_lang_id' => $insert_eng->id,
                                            'language_id' => 1,
                                            'answer' => $req->input('option'.$eng)[$key],
                                            'options' => $req->input('option'.($eng+8))[$key],
                                    ];
                                    $insert_answer_eng = $this->testQuestionAnswerModel->create($answer_eng_arr);
                                }
                            }

                            /***********for hindi******************/
                            $question_details_hindi_arr = [
                                    'question_id' => $insert_master->id,
                                    'question' => $req->question_hindi[$key],
                                    'language_id' => 2,
                                    'solution' => $req->solution_hindi[$key],
                                    'solution_url' => $req->solution_url_hindi[$key],
                            ];
                            $insert_hindi = $this->testQuestionLangModel->create($question_details_hindi_arr);
                            for($hindi = 1; $hindi < 9; $hindi ++){
                                /***********answer for hindi******************/
                                if($req->input('option_hindi'.$hindi)[$key]){
                                    $answer_hindi_arr = [
                                            'question_id' => $insert_master->id,
                                            'question_lang_id' => $insert_hindi->id,
                                            'language_id' => 2,
                                            'answer' => $req->input('option_hindi'.$hindi)[$key],
                                            'options' => $req->input('option_hindi'.($hindi+8))[$key],
                                    ];
                                    $insert_answer_hindi = $this->testQuestionAnswerModel->create($answer_hindi_arr);
                                }
                            }
                        }
                    }
                }
                /*********inset in save question table****************/
                $imported_filename = time().'.xlsx';
                $saved_question_arr = [
                        'filename' => $imported_filename,
                        'import_by' => Auth::guard('coaching')->user()->manager_holder_name,
                        'section_type' => 1,
                        'test_id' => base64_decode($req->test_id),
                        'coaching_id' => Auth::guard('coaching')->user()->manager_holder_name,
                        'ip_address' => $_SERVER['HTTP_X_FORWARDED_FOR'],
                        'details' => $total_data_inserted.' inserted, '.($total_data - $total_data_inserted).' failed',
                ];
                $insert_answer_hindi = $this->savedQuestionModel->create($saved_question_arr);
            }
        }

        $html = '<div class="table-responsive">
                              <table class="table card-table table-vcenter text-nowrap outline-border tbl-gr-acrdn">
                                <thead>
                                  <tr>
                                    <th>Upload File</th>
                                    <th>Uploaded By</th>
                                    <th>Ip Address</th>                                    
                                    <th>Result</th>                                    
                                  </tr>
                                </thead>
                                <tbody>  
                                  <tr>
                                        <th>'.$imported_filename.'</th>
                                        <th>'.Auth::guard('coaching')->user()->manager_holder_name.'</th>
                                        <th>'.$_SERVER['HTTP_X_FORWARDED_FOR'].'</th>                                    
                                        <th>'.$total_data_inserted.' inserted, '.($total_data - $total_data_inserted).' failed'.'</th>                                    
                                    </tr>                         
                                </tbody>
                              </table>
                            </div>';
        $response = array('status'=>200, 'message'=>'success', 'result'=>$html); 
        return response()->json($response);
    }
   

}
