<?php

namespace App\Http\Controllers\Coaching;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use App\Repository\AdminRepository;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Models\CoachingUser;
use App\Models\CoachingMaster;
use App\Models\CoachingExamType;
use App\Models\Organisation;
use App\Models\Sale;
use App\Models\State;
use App\Models\City;
use App\Models\SiteSetting;
use App\Models\AccountDeactivateReason;
use App\Models\User;
use App\Models\ExamType;
use App\Models\TestPackage;
use App\Models\PracticeSets;
use App\Models\PracticeSetSubject;
use App\Models\PracticeSetChapter;
use App\Models\PracticeSetQuestion;
use App\Models\Quiz,App\Models\QuizQuestion;
use App\Models\Test,App\Models\TestQuestion;
use App\Models\CoachingUserDoc;
use App\Models\TestSubject;
use App\Models\PackageSubject;
use App\Models\TestResult;
use App\Models\TestFaculty;
use App\Models\CoachingFaculty;
use App\Models\PackageTestType;
use App\Models\CoachingEngagement;
use App\Mail\SendMailOtp;
use App\Mail\DeactivateAccount;
use Auth;
use Image;
use File;
use DB;

class CoachingDashboardController extends Controller 
{
    
    protected $examTypeModel;
    protected $testPackageModel;
    protected $practiceSetSubjectModel;
    protected $practiceSetChapterModel;
    protected $practiceSetQuestionModel;
    protected $practiceSetModel;
    protected $quizModel;
    protected $saleModel;
    protected $organisationModel;
    protected $accountDeactivateReasonModel;
    protected $coachingMasterModel;
    protected $coachingUserDocModel;
    protected $coachingUserModel;
    protected $testModel;
    protected $quizQuestionModel;
    protected $coachingEngagementModel;
    public function __construct()
    {
        $this->examTypeModel = new ExamType;
        $this->testPackageModel = new TestPackage;
        $this->practiceSetSubjectModel = new PracticeSetSubject;
        $this->practiceSetChapterModel = new PracticeSetChapter;
        $this->practiceSetQuestionModel = new PracticeSetQuestion;
        $this->practiceSetModel = new PracticeSets;
        $this->quizModel = new Quiz;
        $this->saleModel = new Sale;
        $this->coachingMasterModel = new CoachingMaster;
        $this->coachingExamTypeModel = new CoachingExamType;
        $this->coachingUserDocModel = new CoachingUserDoc;
        $this->coachingUserModel = new CoachingUser;
        $this->organisationModel = new Organisation;
        $this->testModel = new Test;
        $this->quizQuestionModel = new QuizQuestion;
        $this->coachingEngagementModel = new CoachingEngagement;
        $this->accountDeactivateReasonModel = new AccountDeactivateReason;
    }
	
    public function index() 
    {   
        $coaching_id=Auth::guard('coaching')->user()->coaching_id;
        $users = User::where('user_type', 2)->count();//total users
        $coaching_users = CoachingUser::count();//total users
        $examType = $this->examTypeModel->orderBy('exam_type')->get();   
        $test_series_sale = $this->saleModel->whereRaw('coaching_id ='.Auth::guard('coaching')->user()->coaching_id.' AND test_series_id > 0 AND is_refund < 2')->whereDate('created_at', date('Y-m-d'))->count();
        $pass_sale = $this->saleModel->whereRaw('coaching_id ='.Auth::guard('coaching')->user()->coaching_id.' AND pass_id > 0 AND is_refund < 2')->whereDate('created_at', date('Y-m-d'))->count();
        $total_sale = $test_series_sale + $pass_sale;
        $total_test_sers = $this->testPackageModel->whereRaw('coaching_id ='.Auth::guard('coaching')->user()->coaching_id)->whereDate('created_at', date('Y-m-d'))->count();
        $total_practice_set = $this->practiceSetModel->whereRaw('coaching_id ='.Auth::guard('coaching')->user()->coaching_id)->whereDate('created_at', date('Y-m-d'))->count();
        $total_quiz = $this->quizModel->whereRaw('coaching_id ='.Auth::guard('coaching')->user()->coaching_id)->whereDate('created_at', date('Y-m-d'))->count();
        $total_test = $this->testModel->join('test_packages','test_packages.id','=','tests.test_package_id')->whereRaw('coaching_id ='.Auth::guard('coaching')->user()->coaching_id)->whereDate('tests.created_at', date('Y-m-d'))->count();
        $total_chapter = $this->practiceSetChapterModel->join('practice_sets','practice_sets.id','=','practice_set_chapters.practice_set_id')->whereRaw('coaching_id ='.Auth::guard('coaching')->user()->coaching_id)->whereDate('practice_set_chapters.created_at', date('Y-m-d'))->count();
        $total_quiz_question = $this->quizQuestionModel->join('quizzes','quizzes.id','=','quiz_questions.quiz_id')->whereRaw('coaching_id ='.Auth::guard('coaching')->user()->coaching_id)->whereDate('quiz_questions.created_at', date('Y-m-d'))->count();
        $total_test_enroll = $this->coachingEngagementModel->whereRaw('coaching_id ='.Auth::guard('coaching')->user()->coaching_id.' AND package_type = 1')->whereDate('created_at', date('Y-m-d'))->count();
        $total_practice_enroll = $this->coachingEngagementModel->whereRaw('coaching_id ='.Auth::guard('coaching')->user()->coaching_id.' AND package_type = 2')->whereDate('created_at', date('Y-m-d'))->count();
        $total_quiz_enroll = $this->coachingEngagementModel->whereRaw('coaching_id ='.Auth::guard('coaching')->user()->coaching_id.' AND package_type = 3')->whereDate('created_at', date('Y-m-d'))->count();
        $coachingDetails = $this->coachingMasterModel->find(Auth::guard('coaching')->user()->coaching_id);
        $deactive_message = '';
        if($coachingDetails->is_deleted == 1){
            $deactive_message = 'Welcome to Admisure again .. ';
            $coachingDetails = $this->coachingMasterModel->where('id',Auth::guard('coaching')->user()->coaching_id)->update(['is_deleted'=>0]);
        }
        /*****sale count************/
        return view('coaching.pages.dashboard.index',compact('users','coaching_users','examType','total_test_sers','total_practice_set','total_quiz','total_test','total_chapter','total_quiz_question','total_test_enroll','total_practice_enroll','total_quiz_enroll','total_sale','test_series_sale','pass_sale', 'deactive_message'));
    }

    public function dashboard_result(Request $req) 
    {
        if($req->post()){
            //echo Auth::guard('coaching')->user()->coaching_id;die;
            //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
            
            if($columnName == 'status') {
                $columnName = 'tests.status';
            }

            ## Total number of records without filtering
            $testtotalRecord = $this->testModel
                                    ->select(DB::raw('tests.id'))
                                    ->rightJoin('test_packages','test_packages.id','=','tests.test_package_id')
                                    ->rightJoin('test_results','test_results.test_id','=','tests.id')
                                    ->where('test_packages.coaching_id',Auth::guard('coaching')->user()->coaching_id)
                                    ->groupBy('test_results.test_id')
                                    ->limit(5)
                                    ->get()
                                    ->count();

            ## Total number of record with filtering
            $testtotalRecordwithFilter = $this->testModel
                                    ->select(DB::raw('tests.id'))
                                    ->rightJoin('test_packages','test_packages.id','=','tests.test_package_id')
                                    ->rightJoin('test_results','test_results.test_id','=','tests.id')
                                    ->where('test_packages.coaching_id',Auth::guard('coaching')->user()->coaching_id)
                                    ->groupBy('test_results.test_id')
                                    ->orderBy('test_results.created_at', 'DESC')
                                    ->limit(5);

            ## Fetch records
            $tests = $this->testModel
                                    ->select(DB::raw("tests.id, tests.test_name,tests.marks,tests.duration,tests.package_test_type_id,tests.candidate_setting_subsequent,tests.candidate_setting_subsequent_date,tests.result_published, package_name"))
                                    ->rightJoin('test_packages','test_packages.id','=','tests.test_package_id')
                                    ->rightJoin('test_results','test_results.test_id','=','tests.id')
                                    ->where('test_packages.coaching_id',Auth::guard('coaching')->user()->coaching_id)
                                    ->groupBy('test_results.test_id')
                                    ->orderBy('test_results.created_at', 'DESC')
                                    ->limit(5);
            //echo '<pre>';print_r($tests);die;

            if($req->exam_type_id){
                $testtotalRecordwithFilter = $testtotalRecordwithFilter->where('tests.exam_type_id', $req->exam_type_id);
                $tests = $tests->where('tests.exam_type_id', $req->exam_type_id);
            }

            if($req->package_id){
                $testtotalRecordwithFilter = $testtotalRecordwithFilter->where('tests.test_package_id', $req->package_id);
                $tests = $tests->where('tests.test_package_id', $req->package_id);
            }

            if($req->test_type_id){
                $testtotalRecordwithFilter = $testtotalRecordwithFilter->where('tests.package_test_type_id', $req->test_type_id);
                $tests = $tests->where('tests.package_test_type_id', $req->test_type_id);
            }

            if($req->test_id){
                $testtotalRecordwithFilter = $testtotalRecordwithFilter->where('tests.id', $req->test_id);
                $tests = $tests->where('tests.id', $req->test_id);
            }

            if($req->search_key){
                $search_key=$req->search_key;
                $search_test_ids=Test::select('tests.id')
                ->leftjoin('test_packages','test_packages.id','=','tests.test_package_id')
                ->where('tests.test_name','like','%'.$search_key.'%')
                ->orWhere('test_packages.package_name','like','%'.$search_key.'%')
                ->pluck('id');
                $testtotalRecordwithFilter = $testtotalRecordwithFilter->whereIn('tests.id', $search_test_ids);
                $tests = $tests->whereIn('tests.id', $search_test_ids);
            }

            if($req->published_filter){
                $testtotalRecordwithFilter = $testtotalRecordwithFilter->where('tests.candidate_setting_subsequent', $req->published_filter);
                $tests = $tests->where('tests.candidate_setting_subsequent', $req->published_filter);
            }

            if($req->orderby_filter){
                $testtotalRecordwithFilter = $testtotalRecordwithFilter->orderBy('test_results.attempted_on',$req->orderby_filter);
                $tests = $tests->orderBy('test_results.attempted_on',$req->orderby_filter);
            }
            
            if($req->custom_date){
                $custom_date=$req->custom_date;
                $today=date('Y-m-d');
                if($custom_date==1){
                   $custom_from_date=$today;
                   $custom_to_date=$today;
                }
                if($custom_date==2){
                   $custom_from_date=date('Y-m-d', strtotime($today.'-7 days'));
                   $custom_to_date=$today;
                }
                if($custom_date==3){
                   $custom_from_date=date('Y-m-01', strtotime($today));
                   $custom_to_date=date('Y-m-t', strtotime($today));
                }
                if($custom_date==4){
                   $current_year_last_month_date=date('Y').'-12-01';
                   $custom_from_date=date('Y').'-01-01';
                   $custom_to_date=date('Y-m-t', strtotime($current_year_last_month_date));
                }
                if($custom_date==5){
                   $last_year_last_month_date=(date('Y')-1).'-12-01';
                   $custom_from_date=(date('Y')-1).'-01-01';
                   $custom_to_date=date('Y-m-t', strtotime($last_year_last_month_date));
                }
                if($custom_date!=6){
                   $testtotalRecordwithFilter = $testtotalRecordwithFilter->whereDate('test_results.attempted_on','>=',$custom_from_date)->whereDate('test_results.attempted_on','<=',$custom_to_date);
                   $tests = $tests->whereDate('test_results.attempted_on','>=',$custom_from_date)->whereDate('test_results.attempted_on','<=',$custom_to_date);
                }
            }

            if($req->from_date){
                $from_date=date('Y-m-d', strtotime($req->from_date));
                $testtotalRecordwithFilter = $testtotalRecordwithFilter->whereDate('test_results.attempted_on','>=',$from_date);
                $tests = $tests->whereDate('test_results.attempted_on','>=',$from_date);
            }

            if($req->to_date){
                $to_date=date('Y-m-d', strtotime($req->to_date));
                $testtotalRecordwithFilter = $testtotalRecordwithFilter->whereDate('test_results.attempted_on','<=',$to_date);
                $tests = $tests->whereDate('test_results.attempted_on','<=',$to_date);
            }

            $testtotalRecordwithFilter = $testtotalRecordwithFilter->get()->count();
            $tests = $tests->get(); 
            //echo $tests->toSql(); die;
            // echo '<pre>';print_r($tests);die;
            $data = array();
            $status_btn = '';
            if($tests){
                foreach($tests as $test){
                    $schedule_time_text = '';
                    if($test->candidate_setting_subsequent==1){
                        $button = '<a href="'.route('coaching.result.view', base64_encode($test->id)).'"><button type="button" class="btn btn-outline-primary btn-pill">View Result</button></a>'; 
                    }else if($test->candidate_setting_subsequent==2){
                        if($test->result_published==1){
                           $button = '<a href="'.route('coaching.result.view', base64_encode($test->id)).'"><button type="button" class="btn btn-outline-primary btn-pill">View Result</button></a>';
                        }else{
                           $button = '<button type="button" class="btn btn-outline-primary btn-pill publishbtn" data-toggle="modal" data-target="#publishResultModal" data-testid="'.$test->id.'">Publish Now</button>'; 
                        }
                    }else if($test->candidate_setting_subsequent==3){
                       if($test->candidate_setting_subsequent_date!='' && $test->candidate_setting_subsequent_date!=NULL && strtotime($test->candidate_setting_subsequent_date)<=strtotime(date('Y-m-d h:i:s'))){
                         $button = '<a href="'.route('coaching.result.view', base64_encode($test->id)).'"><button type="button" class="btn btn-outline-primary btn-pill">View Result</button></a>';   
                       }else{
                        if($test->candidate_setting_subsequent_date!='' && $test->candidate_setting_subsequent_date!=NULL){
                          $schedule_time_text='<span class="schedule-time" id="schedule_time_'.$test->id.'" style="display:inline-block;font-size:10px; color:#858d97; min-width:160px; padding-bottom:10px;">Scheduled on: '.date('d F @ h:i a',strtotime($test->candidate_setting_subsequent_date)).'</span></br>';
                          $schedule_text='Reschedule';
                        }else{
                          $schedule_time_text='';
                          $schedule_text='Schedule';
                        }
                        $button = '<button type="button" class="btn btn-outline-primary btn-pill schedulebtn"  data-toggle="modal" data-target="#scheduleResultModal" data-testid="'.$test->id.'">'.$schedule_text.'</button>';
                       }
                    }else{
                        $button = ''; 
                    }
                    
                    $test_type_name='';
                    $package_test_types=PackageTestType::select('test_type_name')->where('id',$test->package_test_type_id)->first();
                    if($package_test_types!=''){
                        $test_type_name=$package_test_types->test_type_name;
                    }

                    $all_test_subject_name='';
                    $test_subject_data='';
                    $test_subject_ids=TestSubject::select('subject_id')->where('test_id',$test->id)->pluck('subject_id')->toArray();
                    if(count($test_subject_ids)){
                        $test_subject_data=PackageSubject::select('subject')->whereIn('id',$test_subject_ids)->pluck('subject')->toArray();
                        if(count($test_subject_data)>0){
                            if(count($test_subject_data)>1){
                                $test_subject_count=0;
                                foreach ($test_subject_data as $key=>$test_subject_row) {
                                    if($key!=0){
                                      $test_subject_count++;
                                      $all_test_subject_name .= '<p>'.$test_subject_row.'</p>';
                                    }
                                }
                                $test_subject_data ='<a href="javascript:void(0)" class="more_subject" data-title="'.$all_test_subject_name.'">'.$test_subject_data[0].'<span class="badge badge-primary badge-pill fs-10 ml-5">+'.($test_subject_count).'</span><div id="tooltip"></div></a>';
                            }else{
                                $test_subject_data =$test_subject_data[0];
                            }
                        }
                    }

                    $tot_ques_count=TestQuestion::where('test_id',$test->id)->count();
                    $tot_student_count=TestResult::where('test_id',$test->id)->count();
                    $test_faculty_name='';
                    $test_faculty_ids=TestFaculty::select('faculty_id')->where('test_id',$test->id)->pluck('faculty_id')->toArray();
                    if(count($test_faculty_ids)){
                        $test_faculty_data=CoachingFaculty::select('faculty_name')->whereIn('id',$test_faculty_ids)->pluck('faculty_name')->toArray();
                        if($test_faculty_data!=''){
                            $test_faculty_name=implode(' & ',$test_faculty_data);
                        }
                    }
                    $data[] = array( 
                        "package_name"=>$test->package_name,
                        "test_name"=>$test->test_name,
                        "test_type"=>$test_type_name,
                        "subject"=>$test_subject_data,
                        "tot_ques"=>$tot_ques_count,
                        "marks"=>$test->marks,
                        "duration"=>$test->duration,
                        "faculty"=>$test_faculty_name,
                        "attempted_by"=>$tot_student_count,
                        "schedule_on"=>$schedule_time_text,
                        "action"=>$button
                    );
                }
            }
            $response = array(
                "draw" => intval($draw),
                "iTotalRecords" => $testtotalRecord,
                "iTotalDisplayRecords" => $testtotalRecordwithFilter,
                "aaData" => $data
            );
            echo json_encode($response);die;
        }
    }
         
    public function get_dashboard_data(Request $req) 
    {  
        $data_type=$req->input('data_type');  
        $users = User::where('user_type', 2)->count();//total users
        $examType = $this->examTypeModel->orderBy('exam_type')->get();
        return view('coaching.pages.dashboard.data', compact('data_type','users','examType'));
    }

    public function get_dashboard_review_data(Request $req) 
    {  
        $data_type=$req->input('data_type');  
        $users = User::where('user_type', 2)->count();//total users
        $examType = $this->examTypeModel->orderBy('exam_type')->get();
        return view('coaching.pages.dashboard.review_data', compact('data_type','users','examType'));
    }

    public function get_package_data(Request $req) 
    {
        $coaching_id=Auth::guard('coaching')->user()->coaching_id;
        if($req->post()){
            //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
            
            if($columnName == 'status') {
                $columnName = 'test_packages.status';
            }
            if($columnName == 'status') {
                $columnName = 'test_packages.created_at';
            }
            ## Total number of records without filtering
            $testpackagetotalRecord = $this->testPackageModel
                                    ->select(DB::raw("test_packages.id, package_name, no_of_test, validity, on_sale_status, expire_date, validity_type, product_price, discount_price, sale_type, test_packages.status, test_packages.id, GROUP_CONCAT(DISTINCT(test_type_name) SEPARATOR ' & ') as test_type_name , GROUP_CONCAT(DISTINCT(exam_type) SEPARATOR ' , ') as exam_type"))
                                    
                                    ->leftJoin('test_package_exam_types','test_packages.id','=','test_package_exam_types.test_package_id')
                                    ->leftJoin('exam_types','exam_types.id','=','test_package_exam_types.exam_type_id')
                                    
                                    ->leftJoin('tests','tests.test_package_id','=','test_packages.id')
                                    ->leftJoin('package_test_types','tests.package_test_type_id','=','package_test_types.id')
                                    ->where('test_packages.coaching_id','=',$coaching_id)
                                    ->groupBy('test_packages.id')
                                    ->limit(5)
                                    ->get()
                                    ->count();
            ## Total number of record with filtering
            $testpackagetotalRecordwithFilter = $this->testPackageModel
                                    ->select(DB::raw("test_packages.id, package_name, no_of_test, validity, on_sale_status, expire_date, validity_type, product_price, discount_price, sale_type, test_packages.status, test_packages.id, GROUP_CONCAT(DISTINCT(test_type_name) SEPARATOR ' & ') as test_type_name , GROUP_CONCAT(DISTINCT(exam_type) SEPARATOR ' , ') as exam_type"))
                                    ->leftJoin('test_package_exam_types','test_packages.id','=','test_package_exam_types.test_package_id')
                                    ->leftJoin('exam_types','exam_types.id','=','test_package_exam_types.exam_type_id')
                                    ->leftJoin('tests','tests.test_package_id','=','test_packages.id')
                                    ->leftJoin('package_test_types','tests.package_test_type_id','=','package_test_types.id')
                                    ->where('test_packages.coaching_id','=',$coaching_id)
                                    ->groupBy('test_packages.id')
                                    ->orderBy('test_packages.created_at', 'DESC')
                                    ->limit(5);
            ## Fetch records
            $testspackage = $this->testPackageModel
                            ->select(DB::raw("test_packages.id, package_name, no_of_test, validity, on_sale_status, expire_date, validity_type, product_price, discount_price, sale_type, test_packages.status, test_packages.id, GROUP_CONCAT(DISTINCT(test_type_name) SEPARATOR ' & ') as test_type_name , GROUP_CONCAT(DISTINCT(exam_type) SEPARATOR ' , ') as exam_type"))
                            ->leftJoin('test_package_exam_types','test_packages.id','=','test_package_exam_types.test_package_id')
                            ->leftJoin('exam_types','exam_types.id','=','test_package_exam_types.exam_type_id')
                            ->leftJoin('tests','tests.test_package_id','=','test_packages.id')
                            ->leftJoin('package_test_types','tests.package_test_type_id','=','package_test_types.id')
                            ->where('test_packages.coaching_id','=',$coaching_id)
                            ->groupBy('test_packages.id')
                            ->orderBy('test_packages.created_at', 'DESC')
                            ->limit(5);

            if($req->status_filter){
                $testpackagetotalRecordwithFilter = $testpackagetotalRecordwithFilter->where('test_packages.status', $req->status_filter);
                $testspackage = $testspackage->where('test_packages.status', $req->status_filter);
            }

            if($req->examtype_filter){
                $testpackagetotalRecordwithFilter = $testpackagetotalRecordwithFilter->where('test_package_exam_types.exam_type_id', $req->examtype_filter);
                $testspackage = $testspackage->where('test_package_exam_types.exam_type_id', $req->examtype_filter);
            }

            $testpackagetotalRecordwithFilter = $testpackagetotalRecordwithFilter->get()->count();
            $testspackage = $testspackage->get(); 
            $data = array();
            $status_btn = '';
            if($testspackage){
                foreach($testspackage as $testpackage){
                    $created_date = date('Y-m-d', strtotime($testpackage->created_at));
                    $current_date = date('Y-m-d');
                    $target_date = date('Y-m-d', strtotime($testpackage->expire_date. ' - 60 days'));
                    $more_exam_type = explode(' , ', $testpackage->exam_type);

                    if(count($more_exam_type) > 1){
                        $result_exam_type = '';
                        foreach ($more_exam_type as $key => $value) {
                            if($key>0){
                                $result_exam_type .= '<p>'.$value.'</p>';
                            }
                        }
                        $testpackage->exam_type = '<a href="javascript:void(0)" class="more_subject" data-title="'.$result_exam_type.'">'.$more_exam_type[0].'<span class="badge badge-primary badge-pill fs-10 ml-5">+'.(count($more_exam_type)-1).'</span><div id="tooltip"></div></a>';
                    } else {
                        $testpackage->exam_type = $testpackage->exam_type;
                    }
                
                    $more_test_type_name = explode(' & ', $testpackage->test_type_name);
                    if(count($more_test_type_name) > 1){
                        $result_test_type_name = '';
                        foreach ($more_test_type_name as $key => $value) {
                            if($key>0){
                                $result_test_type_name .= '<p>'.$value.'</p>';
                            }
                        }
                        $testpackage->test_type_name = '<a href="javascript:void(0)" class="more_subject" data-title="'.$result_test_type_name.'">'.$more_test_type_name[0].'<span class="badge badge-primary badge-pill fs-10 ml-5">+'.(count($more_test_type_name)-1).'</span><div id="tooltip"></div></a>';
                    } else {
                        $testpackage->test_type_name = $testpackage->test_type_name;
                    }

                    if($testpackage->status == 1) {
                        $status = 'Under Process'; 
                        $button = '<a href="'.route('coaching.test_series_manager.test.list', base64_encode($testpackage->id)).'"><button type="button" class="btn btn-outline-primary btn-pill">Continue Adding </button></a>'; 
                    } elseif($testpackage->status == 2) {
                        $status = 'Completed'; 
                        $button = '<a href="'.route('coaching.test_series_manager.view', base64_encode($testpackage->id)).'"><button type="button" class="btn btn-primary btn-pill">Publish Now </button></a>'; 
                    } elseif($testpackage->status == 3) {
                        $status = 'In Review'; 
                        $button = '<a href="'.route('coaching.test_series_manager.view', base64_encode($testpackage->id)).'"><button type="button" class="btn btn-outline-primary btn-pill">Check Details </button></a>'; 
                    } elseif($testpackage->status == 4) {
                        $status = 'Rejected'; 
                        // $button = '<a href="javascript:void()" class="check_reason" data-id="'.base64_encode($testpackage->id).'"><button type="button" class="btn btn-outline-primary btn-pill">Check Reason </button></a>';
                        $button = '<a href="'.route('coaching.test_series_manager.view', base64_encode($testpackage->id)).'"><button type="button" class="btn btn-outline-primary btn-pill">Check Reason </button></a>'; 
                    } elseif($testpackage->status == 5) {
                        if($testpackage->on_sale_status == 1)
                        {
                            $status = 'Pause Sale';
                        }
                        else
                        {
                            $status = 'On Sale';
                        }
                        $button = '<a href="'.route('coaching.test_series_manager.test.list', base64_encode($testpackage->id)).'"><button type="button" class="btn btn-outline-primary btn-pill">View Report </button></a>'; 
                    }else{
                        $status = 'Expired'; 
                        $button = '<a href="'.route('coaching.test_series_manager.view', base64_encode($testpackage->id)).'"><button type="button" class="btn btn-outline-primary btn-pill">View Details </button></a>'; 
                    }

                    if($testpackage->sale_type == 1 || $testpackage->sale_type == 2)
                    {
                        if($testpackage->product_price == $testpackage->price )
                        {
                           $price = $testpackage->product_price;
                        }
                        else
                        {
                            $price = $testpackage->price." <strike>".$testpackage->product_price."</strike>";
                        }
                    }
                    elseif($testpackage->sale_type == 4)
                    {
                        $price = $testpackage->price." <strike>".$testpackage->product_price."</strike>";
                    }
                    else
                    {
                        $price = $testpackage->product_price;
                    }

                    $data[] = array( 
                        "package_name"=>$testpackage->package_name,
                        "exam_type"=>$testpackage->exam_type,
                        "test_type"=>(($testpackage->test_type_name != NULL) ? $testpackage->test_type_name : 'N/A'),
                        "no_of_test"=>$testpackage->no_of_test,
                        "validity"=>(($testpackage->validity_type == 0) ? $testpackage->validity. ' Days' : date('d-m-Y', strtotime($testpackage->expire_date))),
                        "price"=>'<i class="fa fa-rupee lh-0 op-6"></i> '.$price,
                        "status"=>$status,
                        "action"=>$button.'<div class="item-action dropdown">
                                <a href="javascript:void(0)" data-toggle="dropdown" class="icon"><i class="fe fe-more-vertical fs-20 text-primary"></i></a>
                                <div class="dropdown-menu dropdown-menu-right">
                                <a href="'.route('coaching.test_series_manager.test.list', base64_encode($testpackage->id)).'" class="dropdown-item">Go To Test</a>
                                <a href="'.route('coaching.test_series_manager.normal.view', base64_encode($testpackage->id)).'" class="dropdown-item">View</a>'.
                                (($testpackage->status != 3 && $testpackage->status < 5) ? '<a href="'.route('coaching.test_series_manager.edit', base64_encode($testpackage->id)).'" class="dropdown-item">Edit</a>
                                <a href="javascript:void(0)" class=" dropdown-item test_pack_delete" data-id="'.base64_encode($testpackage->id).'">Delete</a>' : '').
                                (($testpackage->status == 5) ? (($testpackage->on_sale_status == 1) ? '<a href="javascript:void(0)" class="dropdown-item resume" data-id="'.base64_encode($testpackage->id).'">Resume Sale</a>' : '<a href="javascript:void(0)" class="dropdown-item pause" data-id="'.base64_encode($testpackage->id).'">Pause Sale</a>') .'<a href="javascript:void(0)" class="dropdown-item end" data-id="'.base64_encode($testpackage->id).'">End Sale</a>' : '').
                                (($testpackage->status == 4) ? '<a href="'.route('coaching.test_series_manager.resubmit_view', base64_encode($testpackage->id)).'" class="dropdown-item">Resubmit</a> ' : '').
                                (($testpackage->status == 5 && $current_date == $target_date && $current_date != $created_date) ? '<a href="javascript:void(0)" class="dropdown-item extend_validity" data-id="'.base64_encode($testpackage->id).'">Extend Validity</a>' : '')                                
                                .'</div>
                              </div>',

                    );
                }
            }
            $response = array(
                "draw" => intval($draw),
                "iTotalRecords" => $testpackagetotalRecord,
                "iTotalDisplayRecords" => $testpackagetotalRecordwithFilter,
                "aaData" => $data
            );
            echo json_encode($response);die;
        }       
    }

    public function get_practiceset_data(Request $req) 
    {
        $coaching_id=Auth::guard('coaching')->user()->coaching_id;
        if($req->post()){
            $test_series_id = base64_decode($req->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
            
            if($columnName == 'status') {
                $columnName = 'practice_set.status';
            }

            ## Total number of records without filtering
            $testtotalRecord = $this->practiceSetModel
                                    ->select(DB::raw("set_name, practice_sets.id,practice_sets.status,practice_sets.id, exam_type"))
                                    ->leftJoin('exam_types','exam_types.id','=','practice_sets.exam_type_id')
                                    ->where('practice_sets.coaching_id','=',$coaching_id)
                                    ->limit(5)
                                    ->get()
                                    ->count();

            ## Total number of record with filtering
            $testtotalRecordwithFilter = $this->practiceSetModel
                                    ->select(DB::raw("set_name, practice_sets.id,practice_sets.status,practice_sets.id, exam_type"))
                                    ->leftJoin('exam_types','exam_types.id','=','practice_sets.exam_type_id')
                                    ->where('practice_sets.coaching_id','=',$coaching_id)
                                    ->orderBy('practice_sets.created_at', 'DESC')
                                    ->limit(5);

            ## Fetch records
            $tests = $this->practiceSetModel
                            ->select(DB::raw("set_name, practice_sets.id,practice_sets.status,practice_sets.id, exam_type"))
                            ->leftJoin('exam_types','exam_types.id','=','practice_sets.exam_type_id')
                            ->where('practice_sets.coaching_id','=',$coaching_id)
                            ->orderBy('practice_sets.created_at', 'DESC')
                            ->limit(5);

            if($req->status_filter){
                $testtotalRecordwithFilter = $testtotalRecordwithFilter->where('practice_sets.status', $req->status_filter);
                $tests = $tests->where('practice_sets.status', $req->status_filter);
            }
            if($req->examtype_filter){
                $testtotalRecordwithFilter = $testtotalRecordwithFilter->where('practice_sets.exam_type_id', $req->examtype_filter);
                $tests = $tests->where('practice_sets.exam_type_id', $req->examtype_filter);
            }
            if($req->diff_filter){
                $testtotalRecordwithFilter = $testtotalRecordwithFilter->where('practice_sets.difficulty_level', $req->diff_filter);
                $tests = $tests->where('practice_sets.difficulty_level', $req->diff_filter);
            }

            $testtotalRecordwithFilter = $testtotalRecordwithFilter->get()->count();
            $tests = $tests->get(); 
            //echo $quizes->toSql(); die;
            //echo '<pre>';print_r($quizes);die;
            $data = array();
            $status_btn = '';
            if($tests){
                foreach($tests as $test){

                    $test->total_subject = $this->practiceSetSubjectModel->where('practice_set_id', $test->id)->count();
                    $test->total_chapter = $this->practiceSetChapterModel->where('practice_set_id', $test->id)->count();
                    $test->total_question = $this->practiceSetQuestionModel->where('practice_set_id', $test->id)->count();

                    $ext_btn = '';
                    if($test->status == 1) {
                        $status = 'Under Process'; 
                        $button = '<a href="'.route('coaching.practice_set.chapter.list', base64_encode($test->id)).'"><button type="button" class="btn btn-outline-primary btn-pill">Continue Adding </button></a>'; 
                    } elseif($test->status == 2) {
                        $status = 'Completed'; 
                        $button = '<a href="'.route('coaching.practice_set.view', base64_encode($test->id)).'"><button type="button" class="btn btn-primary btn-pill">Publish Now </button></a>'; 
                    } elseif($test->status == 3) {
                        $status = 'In Review'; 
                        $button = '<a href="'.route('coaching.practice_set.view', base64_encode($test->id)).'"><button type="button" class="btn btn-outline-primary btn-pill">Check Details </button></a>'; 
                    } elseif($test->status == 4) {
                        $status = 'Declined'; 
                        $button = '<a href="javascript:void(0);" class="check_reason"  data-id="'.base64_encode($test->id).'"><button type="button" class="btn btn-outline-primary btn-pill">Check Reason </button></a>'; 
                        $ext_btn = '<a href="javascript:void(0)" class="dropdown-item resubmit" data-id="'.base64_encode($test->id).'">Resubmit</a>'; 
                    } elseif($test->status == 5) {
                        $status = 'Live'; 
                        $button = '<a href="javascript:void(0);" class="view_analytics"  data-id="'.base64_encode($test->id).'"><button type="button" class="btn btn-outline-primary btn-pill">View Analytics </button></a>'; 
                        $ext_btn = '<a href="javascript:void(0)" class="dropdown-item unpublish" data-id="'.base64_encode($test->id).'">Unpublish</a>
                                    <a href="javascript:void(0)" class="dropdown-item set_expiry" data-id="'.base64_encode($test->id).'">Set Expiry</a>';
                    } else {
                        $status = 'Expired'; 
                        $button = '<a href="'.route('coaching.practice_set.view', base64_encode($test->id)).'"><button type="button" class="btn btn-outline-primary btn-pill">View Details </button></a>'; 
                    }

                    $data[] = array( 
                        "set_name"=>$test->set_name,
                        "exam_type"=>$test->exam_type,
                        "total_subject"=>$test->total_subject,
                        "total_chapter"=>$test->total_chapter,
                        "total_question"=>$test->total_question,
                        "status"=>$status,
                        "action"=>$button
                    );
                }
            }            

            $response = array(
                "draw" => intval($draw),
                "iTotalRecords" => $testtotalRecord,
                "iTotalDisplayRecords" => $testtotalRecordwithFilter,
                "aaData" => $data
            );

            echo json_encode($response);die;
        }
            
    }

    public function get_quiz_data(Request $req) 
    {
        $coaching_id=Auth::guard('coaching')->user()->coaching_id;
        if($req->post()){
            //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
            
            if($columnName == 'status') {
                $columnName = 'quizzes.status';
            }

            ## Total number of records without filtering
            $quiztotalRecord = $this->quizModel
                                    ->select(DB::raw('quizzes.id, quiz_name, exam_type, quizzes.status,count(quiz_questions.id) question_count, duration'))
                                    ->leftJoin('exam_types','exam_types.id','=','quizzes.exam_type_id')
                                    ->leftJoin('quiz_questions','quiz_questions.quiz_id','=','quizzes.id')
                                    ->leftJoin('quiz_subjects','quiz_subjects.quiz_id','=','quizzes.id')
                                    ->where('quizzes.coaching_id','=',$coaching_id)
                                    ->groupBy('quizzes.id')
                                    ->limit(5)
                                    ->get()
                                    ->count();

            ## Total number of record with filtering
            $quiztotalRecordwithFilter = $this->quizModel
                                    ->select(DB::raw('quizzes.id, quiz_name, exam_type, quizzes.status,count(quiz_questions.id) question_count, duration'))
                                    ->leftJoin('exam_types','exam_types.id','=','quizzes.exam_type_id')
                                    ->leftJoin('quiz_questions','quiz_questions.quiz_id','=','quizzes.id')
                                    ->leftJoin('quiz_subjects','quiz_subjects.quiz_id','=','quizzes.id')
                                    ->where('quizzes.coaching_id','=',$coaching_id)
                                    ->groupBy('quizzes.id')
                                    ->orderBy('quizzes.created_at', 'DESC')
                                    ->limit(5);

            ## Fetch records
            $quizes = $this->quizModel
                            ->select(DB::raw('quizzes.id, quiz_name, exam_type, quizzes.status,count(quiz_questions.id) question_count, duration'))
                            ->leftJoin('exam_types','exam_types.id','=','quizzes.exam_type_id')
                            ->leftJoin('quiz_questions','quiz_questions.quiz_id','=','quizzes.id')
                            ->leftJoin('quiz_subjects','quiz_subjects.quiz_id','=','quizzes.id')
                            ->where('quizzes.coaching_id','=',$coaching_id)
                            ->groupBy('quizzes.id')
                            ->orderBy('quizzes.created_at', 'DESC')
                            ->limit(5);

            if($req->status_filter){
                $quiztotalRecordwithFilter = $quiztotalRecordwithFilter->where('quizzes.status', $req->status_filter);
                $quizes = $quizes->where('quizzes.status', $req->status_filter);
            }
            if($req->examtype_filter){
                $quiztotalRecordwithFilter = $quiztotalRecordwithFilter->where('exam_type_id', $req->examtype_filter);
                $quizes = $quizes->where('exam_type_id', $req->examtype_filter);
            }
            if($req->diff_filter){
                $quiztotalRecordwithFilter = $quiztotalRecordwithFilter->where('quizzes.difficulty_level', $req->diff_filter);
                $quizes = $quizes->where('quizzes.difficulty_level', $req->diff_filter);
            }
            if($req->subject_filter){
                $quiztotalRecordwithFilter = $quiztotalRecordwithFilter->where('quiz_subjects.subject_id', $req->subject_filter);
                $quizes = $quizes->where('quiz_subjects.subject_id', $req->subject_filter);
            }

            $quiztotalRecordwithFilter = $quiztotalRecordwithFilter->get()->count();
            $quizes = $quizes->get(); 
            //echo $quizes->toSql(); die;
            //echo '<pre>';print_r($quizes);die;
            $data = array();
            $status_btn = '';
            if($quizes){
                foreach($quizes as $quiz){
                    if($quiz->status == 1) {
                        $status = 'Under Process'; 
                        $button = '<a href="'.route('coaching.quiz.question.list', base64_encode($quiz->id)).'"><button type="button" class="btn btn-outline-primary btn-pill">Continue Adding </button></a>'; 
                    } elseif($quiz->status == 2) {
                        $status = 'Completed'; 
                        $button = '<a href="'.route('coaching.quiz.view', base64_encode($quiz->id)).'"><button type="button" class="btn btn-outline-primary btn-pill">Publish Now </button></a>'; 
                    } elseif($quiz->status == 3) {
                        $status = 'In Review'; 
                        $button = '<a href="'.route('coaching.quiz.view', base64_encode($quiz->id)).'"><button type="button" class="btn btn-outline-primary btn-pill">Check Details </button></a>'; 
                    } elseif($quiz->status == 4) {
                        $status = 'Declined'; 
                        $button = '<a href="javascript:void(0);" class="check_reason"  data-id="'.base64_encode($quiz->id).'"><button type="button" class="btn btn-outline-primary btn-pill">Check Reason </button></a>'; 
                        $status_btn = '<a href="javascript:void(0)" class="dropdown-item resubmit" data-id="'.base64_encode($quiz->id).'">Resubmit</a>';
                    }elseif($quiz->status == 5) {
                        $status = 'Live'; 
                        $button = '<a href="javascript:void(0);" class="view_analytics"  data-id="'.base64_encode($quiz->id).'"><button type="button" class="btn btn-outline-primary btn-pill">View Analytics </button></a>';
                        $status_btn = '<a href="javascript:void(0)" class="dropdown-item unpublish" data-id="'.base64_encode($quiz->id).'">Unpublish</a>
                                    <a href="javascript:void(0)" class="dropdown-item set_expiry" data-id="'.base64_encode($quiz->id).'">Set Expiry</a>'; 
                    } else {
                        $status = 'Expired'; 
                        $button = '<a href="'.route('coaching.quiz.view', base64_encode($quiz->id)).'"><button type="button" class="btn btn-outline-primary btn-pill">View Details </button></a>'; 
                    }
                    $data[] = array( 
                        "quiz_name"=>$quiz->quiz_name,
                        "exam_type"=>$quiz->exam_type,
                        "question_count"=>$quiz->question_count,
                        "duration"=>$quiz->duration,
                        "status"=>$status,
                        "action"=>$button
                    );
                }
            }
            $response = array(
                "draw" => intval($draw),
                "iTotalRecords" => $quiztotalRecord,
                "iTotalDisplayRecords" => $quiztotalRecordwithFilter,
                "aaData" => $data
            );
            echo json_encode($response);die;
        }       
    }

    public function profile(Request $req)
    {
        $id = Auth::guard('coaching')->user()->id;
        $coaching_id = Auth::guard('coaching')->user()->coaching_id;
        $coachingDetails = $this->coachingMasterModel->find(Auth::guard('coaching')->user()->coaching_id);
        $testSeriesCount = $this->testPackageModel->where('coaching_id', $coaching_id)->count();
        // dd($testSeriesCount);
        $quizCount = $this->quizModel->where('coaching_id', $coaching_id)->count();
        $chapterCount = $this->practiceSetChapterModel
                             ->select(DB::raw("practice_set_chapters.*"))      
                             ->leftJoin('practice_sets','practice_sets.id','=','practice_set_chapters.practice_set_id')
                             ->where('practice_sets.coaching_id', $coaching_id)
                             ->count();
        $reasons = $this->accountDeactivateReasonModel->get();
        $organisationDocsId = [];
        $organisationDocsId = $this->coachingUserDocModel->where('coaching_user_id',$id)->get();
        $state = State::where('country_id', 105)->get(); 
        $city = City::where('state_id', Auth::guard('coaching')->user()->state_id)->orderBy('city')->get();
        // dd(Auth::guard('coaching')->user()->state_id); 

    	return view('coaching.pages.dashboard.profile')
                ->withState($state)
                ->withQuizCount($quizCount)
                ->withTestSeriesCount($testSeriesCount)
                ->withChapterCount($chapterCount)
                ->withReasons($reasons)
                ->withCoachingDocsId($organisationDocsId)
                ->withCoachingDetails($coachingDetails)
                ->withCity($city);
    }

    public function get_city(Request $request)
    {
        $state_id = $request->input('id');;
        $city = City::where('state_id', $state_id)->orderBy('city')->get();
        if(!empty($city))
        {
            $output = '<option value="">--Select--</option>';
            foreach ($city as $value) 
            {
                 $output .= '<option value="'.$value->id.'" data-badge="">'.$value->city.'</option>';
                 
            }
            echo $output;
        } 
        else
        {
            $output = '<option value="">--Select--</option>';

            echo $output;
        }        
    }


    public function profile_update(Request $request) 
    {
        $id = Auth::guard('coaching')->user()->id;
        // dd($id);
        $user = CoachingUser::find($id);
        $request->validate([
            'username'        => 'required',
            'pnumber'        => 'required',
            //'snumber'        => 'required',
            'country'        => 'required',
            'state'        => 'required',
            'city'        => 'required',

        ]);

        if($request->profile_pic != 'undefined')
        {
            //Delete Old Images
            
            // if(File::exists('admin/images/coaching/avaters/'.$user->picture))
            // {
            //     File::delete('admin/images/coaching/avaters/'.$user->picture);
            // }

            if(File::exists(public_path('storage/manager/picture/'.Auth::guard('coaching')->user()->picture)))
            {
                @unlink(public_path('storage/manager/picture/'.Auth::guard('coaching')->user()->picture));//unlik uploaded file
            }

            //Insert New Image
            /*$image = $request->file('profile_pic');
            //Create Image Name
            $img = 'profile.'.$image->getClientOriginalExtension(); 
            $location = public_path('storage/manager/picture/'.$img);
            Image::make($image)->save($location);*/

            $update_arr = [
                    'manager_holder_name' => $request->username,
                    'primary_no' => $request->pnumber,
                    'secondary_no' => $request->snumber ? $request->snumber : '',
                    'country_id' => $request->country,
                    'state_id' => $request->state,
                    'city_id' => $request->city,
                    'zipcode' => $request->zipcode,
                    'address' => $request->address,
                    //'picture' => $img
                ];
            $return = CoachingUser::where('id', $id)->update($update_arr);
        }
        else
        {
            $update_arr = [
                    'manager_holder_name' => $request->username,
                    'primary_no' => $request->pnumber,
                    'secondary_no' => $request->snumber ? $request->snumber : '',
                    'country_id' => $request->country,
                    'state_id' => $request->state,
                    'city_id' => $request->city,
                    'zipcode' => $request->zipcode,
                    'address' => $request->address
                ];
            $return = CoachingUser::where('id', $id)->update($update_arr);
        }
        
        if($return)
        {
            echo 1;
            exit;
        }
        else
        {
            echo 2;
            exit;
        }
    }


    public function documentUpload(Request $request)
    {
        // dd($request->post());
        $id = Auth::guard('coaching')->user()->id;
        $user = CoachingUser::find($id);
        // $docs = CoachingUserDoc::where('coaching_user_id',$id)->count();

        $request->validate([
            'id_proof'        => 'required',
            'id_card_no'        => 'required'
        ]);

        if($request->profile_pic != 'undefined')
        {
            //Delete Old Images
            
            // if(File::exists('admin/images/coaching/avaters/'.$user->picture))
            // {
            //     File::delete('admin/images/coaching/avaters/'.$user->picture);
            // }

            if(File::exists(public_path('storage/manager/picture/'.Auth::guard('coaching')->user()->picture)))
            {
                @unlink(public_path('storage/manager/picture/'.Auth::guard('coaching')->user()->picture));//unlik uploaded file
            }

            //Insert New Image
            $image = $request->file('profile_pic');
            //Create Image Name
            $img = 'profile.'.$image->getClientOriginalExtension(); 
            $location = public_path('storage/manager/picture/'.$img);
            Image::make($image)->save($location);

            if($request->id_card_no != '')
            {
                $update_arr = [
                    'id_proof' => $request->id_proof,
                    // 'id_card_no' => $request->id_card_no,
                    'picture' => $img
                ];

                if (!strrchr($req->id_card_no, "XXXX")) {
                  $update_arr['id_card_no'] = $req->id_card_no;
                }
            }
            else
            {
                $update_arr = [
                    'picture' => $img
                ];
            }
            if(count($request->file('id_proofs')) > 0)
            {
                $id_proofs_arr = [];
                if($request->file('id_proofs')){
                    $files = $request->file('id_proofs');
                    foreach ($files as $key => $file) {
                        if($file->isValid()){  
                            if($file->getClientOriginalExtension() == 'jpeg' || $file->getClientOriginalExtension() == 'jpg' || $file->getClientOriginalExtension() == 'png' || $file->getClientOriginalExtension() == 'pdf' || $file->getClientOriginalExtension() == 'doc' || $file->getClientOriginalExtension() == 'docx'){
                                $bannername = time().str_random(5).'.'.$file->getClientOriginalExtension();
                                $path = 'id_proofs';
                                $destination = public_path('storage/coaching/id_proofs');
                                $upload_location = $path.'/'.$bannername;
                                $file->move($destination, $bannername);
                                $id_proofs_arr[] = $bannername;
                            }
                        }
                    }
                    
                    if($id_proofs_arr){
                        foreach ($id_proofs_arr as $key => $filenames) {
                            $insert_arr_banner = [
                                'coaching_user_id' => $id,
                                'filename' => $filenames,
                            ]; 
                            $this->coachingUserDocModel->insert($insert_arr_banner);  
                        }
                    } 
                }
            }
            
            
            $return = CoachingUser::where('id', $id)->update($update_arr);
        }
        else
        {
            if('id_card_no' != '')
            {
                $update_arr = [
                    'id_proof' => $request->id_proof,
                    'id_card_no' => $request->id_card_no
                ];
                $return = CoachingUser::where('id', $id)->update($update_arr);
            }
            else
            {
                $return = false;
            }
            
            if(count($request->file('id_proofs')) > 0)
            {
                $id_proofs_arr = [];
                if($request->file('id_proofs')){
                    $files = $request->file('id_proofs');
                    foreach ($files as $key => $file) {
                        if($file->isValid()){  
                            if($file->getClientOriginalExtension() == 'jpeg' || $file->getClientOriginalExtension() == 'jpg' || $file->getClientOriginalExtension() == 'png' || $file->getClientOriginalExtension() == 'pdf' || $file->getClientOriginalExtension() == 'doc' || $file->getClientOriginalExtension() == 'docx'){
                                $bannername = time().str_random(5).'.'.$file->getClientOriginalExtension();
                                $path = 'id_proofs';
                                $destination = public_path('storage/coaching/id_proofs');
                                $upload_location = $path.'/'.$bannername;
                                $file->move($destination, $bannername);
                                $id_proofs_arr[] = $bannername;
                            }
                        }
                    }
                    
                    if($id_proofs_arr){
                        foreach ($id_proofs_arr as $key => $filenames) {
                            $insert_arr_banner = [
                                'coaching_user_id' => $id,
                                'filename' => $filenames,
                            ]; 
                            $this->coachingUserDocModel->insert($insert_arr_banner);  
                        }
                    } 
                }
            }
            
            
           
        }
        
        if($return)
        {
            echo 1;
            exit;
        }
        else
        {
            echo 2;
            exit;
        }
    }

    public function deleteDoc(Request $req) 
    {
        $response = [];
        if($req->id){
            $id = base64_decode($req->id);
            $doc_details = $this->coachingUserDocModel->find($id);
            if (File::exists(public_path('storage/coaching/id_proofs/'.$doc_details->filename))) {
                @unlink(public_path('storage/coaching/id_proofs/'.$doc_details->filename));//unlik uploaded file
            }
            $this->coachingUserDocModel->where('id', $id)->delete(); 
            
            $response = array('status'=>200, 'message'=>'success', 'result'=>[]); 
            return response()->json($response);
        }
    }


    public function deleteAccount(Request $req)
    {
        $id = Auth::guard('coaching')->user()->id;
        // dd($id);
        $real_password = Auth::guard('coaching')->user()->password;
        // dd($req->post());
        $req->validate([
            'user'        => 'required',
            'password'    => 'required',
            'reason'      => 'required',
            'comments'    => 'required'
        ]);

        $update = [
                    'reason_id' => $req->reason,
                    'comments' => $req->comments,
                    'status' => 1
                ];

        if($req->reason == 0)
        {
            $update['reason'] = $req->others;
            $reason = $req->others;
        }
        else
        {
            $rson = $this->accountDeactivateReasonModel->where('id', $req->reason)->first();
            $reason = $rson->reason;
        }
        // dd($update);
        if(Hash::check($req->password, $real_password))
        {
            $user = $this->coachingUserModel->where('id', $id)->where('email', $req->user)->count();

            if($user > 0)
            {
                $update = $this->coachingUserModel->where('id', $id)->update($update);
                $up = $this->coachingMasterModel->where('id', Auth::guard('coaching')->user()->coaching_id)->update(['is_deleted'=>1]);
                if($update && $up)
                {
                    // Auth::guard('coaching')->logout();
                    // return redirect('/coaching-master/login');
                    $deactivateAccount = [];
                    $deactivateAccount['name'] = Auth::guard('coaching')->user()->manager_holder_name;
                    $deactivateAccount['email'] = $req->user;
                    $deactivateAccount['comment'] = $comments;
                    $deactivateAccount['reason'] = $reason;
                    Mail::to($email)->send(new DeactivateAccount($deactivateAccount));
                    echo 2;
                    exit;
                }
                else
                {
                    // session()->flash('errors', 'Account Deleted Not Successfully');
                    // return redirect()->route('coaching.coaching_profile');
                    echo 3;
                    exit;
                }
            }
            else
            {
                // session()->flash('errors', 'Something Is Wrong');
                // return redirect()->route('coaching.coaching_profile');
                echo 4;
                exit;
            }
        }
        else
        {
            echo 1;
            exit;
        }   
    }

    public function change_password(Request $req)
    {
        return view('coaching.pages.dashboard.password');
    }

    public function password_check(Request $req)
    {
        $id = Auth::guard('coaching')->user()->id;
        $old_password = $req->old_password;
        $admin = CoachingUser::find($id);
        if(Hash::check($old_password, $admin->password))
        {
            echo "success";
        }
        else
        {
            echo 1;
        }
    }


    public function update_password(Request $request)
    {
        $id = Auth::guard('coaching')->user()->id;
        $user = CoachingUser::find($id);
        $request->validate([
            'new_password'        => 'required'
        ]);

        if(!empty($request->profile_pic))
        {
            //Delete Old Images
            
            // if(File::exists('admin/images/coaching/avaters/'.$user->picture))
            // {
            //     File::delete('admin/images/coaching/avaters/'.$user->picture);
            // }

            if(File::exists(public_path('storage/manager/picture/'.Auth::guard('coaching')->user()->picture)))
            {
                @unlink(public_path('storage/manager/picture/'.Auth::guard('coaching')->user()->picture));//unlik uploaded file
            }

            //Insert New Image
            $image = $request->file('profile_pic');
            //Create Image Name
            $img = 'profile.'.$image->getClientOriginalExtension(); 
            $location = public_path('storage/manager/picture/'.$img);
            Image::make($image)->save($location);

            $data = array('picture' => $img, 'password' => Hash::make($request->new_password));
            $return = CoachingUser::where('id', $id)->update($data);
        }
        else
        {
            $data = array('password' => Hash::make($request->new_password));
            $return = CoachingUser::where('id', $id)->update($data);
        }
        
        if($return)
        {
            session()->flash('success', 'Coaching Admin Password Updated Successfully');
            return redirect()->route('coaching.coaching_changepassword');
        }
        else
        {
            session()->flash('errors', 'Coaching Admin Password Not Successfully Update');
            return redirect()->route('coaching.coaching_changepassword');
        }
    }


    public function number_verify(Request $request)
    {
        $site_setting = SiteSetting::where('site_key_slug', 'sms_gateway_api_key')->first();
        $api_key = $site_setting->site_value;
        $primary_number = $request->primary_number;
        $secondary_number = $request->secondary_number;
        $id = Auth::guard('coaching')->user()->id;
        if($api_key && $primary_number || $api_key && $secondary_number)
        {
            if($secondary_number != '')
            {
                $url = "https://2factor.in/API/V1/".$api_key."/SMS/+91".$secondary_number."/AUTOGEN/OTP Verification Admisure";
                //$url = "https://2factor.in/API/V1/".$api_key."/SMS/+91".$secondary_number."/AUTOGEN";
                $curl = curl_init($url);
                curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
                $result = curl_exec($curl); 

                $output = explode(',', $result);
                $details = explode('"', $output[1]);
                $data = array('otp_session_id' => $details[3], 'secondary_no' => $secondary_number, 'secondary_number_verify' => 0);
                $return = CoachingUser::where('id', $id)->update($data);

                echo 1;
            }
            else
            {
                $url = "https://2factor.in/API/V1/".$api_key."/SMS/+91".$primary_number."/AUTOGEN/OTP Verification Admisure";
                //$url = "https://2factor.in/API/V1/".$api_key."/SMS/+91".$primary_number."/AUTOGEN";
                $curl = curl_init($url);
                curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
                $result = curl_exec($curl); 

                $output = explode(',', $result);
                $details = explode('"', $output[1]);
                $data = array('otp_session_id' => $details[3], 'primary_no' => $primary_number, 'primary_number_verify' => 0);
                $return = CoachingUser::where('id', $id)->update($data);

                echo 1;
            }
            
            

        }
        
    }

    public function otp_verify(Request $request)
    {
        $site_setting = SiteSetting::where('site_key_slug', 'sms_gateway_api_key')->first();
        $api_key = $site_setting->site_value;
        $primary_otp = $request->primary_otp;
        $secondary_otp = $request->secondary_otp;
        $id = Auth::guard('coaching')->user()->id;
        $user_otp_session_id = Auth::guard('coaching')->user()->otp_session_id;
        // echo $primary_otp;
        // die;

        if($user_otp_session_id)
        {
            if($primary_otp != '')
            {
                $url = "https://2factor.in/API/V1/".$api_key."/SMS/VERIFY/".$user_otp_session_id."/".$primary_otp; 
                $curl = curl_init($url);
                curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
                $result = curl_exec($curl); 
                // print_r($result);
                $output = explode(',', $result);
                // print_r($result);
                $details = explode('"', $output[1]);
                // print_r($result);
                
                if($details[3] == "OTP Matched")
                {
                    // echo "success";
                    // exit;
                    $data = array('otp_session_id' => '',  'primary_number_verify' => 1);
                    $return = CoachingUser::where('id', $id)->update($data);
                    echo 1;
                }
                else
                {
                    // echo "failed";
                    // exit;
                    echo 2;
                }

            }
            else
            {
                $url = "https://2factor.in/API/V1/".$api_key."/SMS/VERIFY/".$user_otp_session_id."/".$secondary_otp;
                $curl = curl_init($url);
                curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
                $result = curl_exec($curl); 
                $output = explode(',', $result);
                $details = explode('"', $output[1]);
                
                if($details[3] == "OTP Matched")
                {
                    $data = array('otp_session_id' => '',  'secondary_number_verify' => 1);
                    $return = CoachingUser::where('id', $id)->update($data);
                    echo 1;
                }
                else
                {
                    echo 2;
                }
            }
        }
    }

    public function details(Request $request)
    {
        $exam_types = $this->examTypeModel->orderBy('display_order')->get();
        $coaching_exam_types = $this->coachingExamTypeModel
                            ->select(DB::raw("*"))
                            ->where('coaching_exam_types.coaching_id', Auth::guard('coaching')->user()->coaching_id)
                            ->get();
         
        $coachingName = $this->coachingMasterModel->find(Auth::guard('coaching')->user()->coaching_id);
        // dd($coachingName->state_id);
        $state = State::where('country_id', 105)->get(); 
        $city = City::where('state_id', $coachingName->state_id)->orderBy('city')->get();

        $org = $this->organisationModel->where('coaching_id', Auth::guard('coaching')->user()->coaching_id)->first();

        $edit_exam_types = [];
        if($coaching_exam_types){
            foreach ($coaching_exam_types as $key => $xm) {
                array_push($edit_exam_types, $xm->exam_type_id);
            }
        }
        // dd($coachingName);
        return view('coaching.pages.dashboard.details')
                ->withCoachingName($coachingName)
                ->withEditExamTypes($edit_exam_types)
                ->withExamTypes($exam_types)
                ->withState($state)
                ->withOrg($org)
                ->withCity($city);
    }

    public function coaching_number_verify(Request $request)
    {
        $site_setting = SiteSetting::where('site_key_slug', 'sms_gateway_api_key')->first();
        $api_key = $site_setting->site_value;
        $primary_number = $request->primary_number;
        $id = Auth::guard('coaching')->user()->coaching_id;
        $exist_number = CoachingMaster::where('help_no', $primary_number)->where('id', '!=', $id)->count();
        if($exist_number == 0)
        {
            if($api_key && $primary_number)
            {
                $url = "https://2factor.in/API/V1/".$api_key."/SMS/+91".$primary_number."/AUTOGEN/OTP Verification Admisure";
                //$url = "https://2factor.in/API/V1/".$api_key."/SMS/+91".$primary_number."/AUTOGEN";
                $curl = curl_init($url);
                curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
                $result = curl_exec($curl); 

                $output = explode(',', $result);
                $details = explode('"', $output[1]);
                $data = array('otp_session_id' => $details[3], 'help_no' => $primary_number, 'no_verify' => 0);
                $return = CoachingMaster::where('id', $id)->update($data);

                $response = array('status'=>200, 'message'=>'', 'result'=>[]);

            }
        }
        else
        {
            $response = array('status'=>201, 'message'=>'helpline number already registered in some other account', 'result'=>[]);
        }
        
        return response()->json($response);
    }

    public function coaching_otp_verify(Request $request)
    {
        $site_setting = SiteSetting::where('site_key_slug', 'sms_gateway_api_key')->first();
        $api_key = $site_setting->site_value;
        $primary_otp = $request->primary_otp;
        $id = Auth::guard('coaching')->user()->coaching_id;
        $coaching_master = CoachingMaster::find($id);
        $user_otp_session_id = $coaching_master['otp_session_id'];
        // echo $primary_otp;
        // echo $user_otp_session_id;
        // die;

        if($user_otp_session_id)
        {
            if($primary_otp != '')
            {
                $url = "https://2factor.in/API/V1/".$api_key."/SMS/VERIFY/".$user_otp_session_id."/".$primary_otp; 
                $curl = curl_init($url);
                curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
                $result = curl_exec($curl); 
                // print_r($result);
                $output = explode(',', $result);
                // print_r($result);
                $details = explode('"', $output[1]);
                // print_r($result);
                
                if($details[3] == "OTP Matched")
                {
                    $data = array('otp_session_id' => '',  'no_verify' => 1);
                    $return = CoachingMaster::where('id', $id)->update($data);
                    echo 1;
                    die;
                }
                else
                {
                    echo 2;
                    die;
                }

            }
        }
    }


    public function coaching_details_update(Request $req)
    {
        if($req->post())
        {
            $coaching_id = Auth::guard('coaching')->user()->coaching_id;
            $coaching_exam_type = $this->coachingExamTypeModel->where('coaching_id', $coaching_id)->get();
            $org_details = $this->organisationModel->where('coaching_id', $coaching_id)->count();
            $edit_exam_types = [];
            if($coaching_exam_type){
                foreach ($coaching_exam_type as $key => $xm) {
                    array_push($edit_exam_types, $xm->exam_type_id);
                }
            }

            $req->validate([
                    'coachingname' => 'required|max:255',
                    'examType' => 'required',
                    // 'ben_name' => 'required',
                    'email' => 'required',
                    'state' => 'required',
                    'city' => 'required',
                    'address' => 'required'

                ]);

            $update_arr = [
                    'coaching_name' => $req->coachingname,
                    'benificiary_name' => $req->ben_name,
                    'coaching_type' => $req->coachingType,
                    'email' => $req->email,
                    'country_id' => $req->country,
                    'state_id' => $req->state,
                    'city_id' => $req->city,
                    'zipcode' => $req->zipcode,
                    'address' => $req->address
                ];
            if($org_details > 0)
            {
                $this->organisationModel->where('coaching_id', $coaching_id)->update(['beneficiary_organization_name'=>$req->ben_name]);
            }
            else
            {
                $update_array = [
                    'coaching_id' => $coaching_id,
                    'beneficiary_organization_name' => $req->ben_name,
                    'country_id' => $req->country,
                    'state_id' => $req->state,
                    'city_id' => $req->city,
                    'zipcode' => $req->zipcode,
                    'address' => $req->address
                ];
                // dd($update_array);

                $this->organisationModel->create($update_array);
            }
            
            $update = $this->coachingMasterModel->where('id', $coaching_id)->update($update_arr);
            if($update)
            {
                session()->flash('success', 'Coaching details update successfully');
                $insert_arr_type = [];

                //Test Package Exam Type Update With Checking
                $type_new = array_diff($req->examType, $edit_exam_types);
                $type_exist_but_not_selected = array_diff($edit_exam_types, $req->examType);
                if($type_new)
                {
                    foreach($type_new as $type)
                    {
                        $insert_arr_type[] = [
                            'coaching_id' => $coaching_id,
                            'exam_type_id' => $type
                        ];
                    }
                    $insert_type = $this->coachingExamTypeModel->insert($insert_arr_type);
                }
                
                if($type_exist_but_not_selected)
                {
                    foreach($type_exist_but_not_selected as $type_old)
                    {
                        $exist_type = $this->testPackageModel
                                    ->select(DB::raw("*"))
                                    ->leftJoin('test_package_exam_types','test_packages.id','=','test_package_exam_types.test_package_id')
                                    ->where('test_packages.coaching_id', $coaching_id)
                                    ->where('test_package_exam_types.exam_type_id', $type_old)
                                    ->count();
                        // dd($exist_type);

                        if($exist_type == 0)
                        {
                            $this->coachingExamTypeModel->where(['exam_type_id'=> $type_old, 'coaching_id' => $coaching_id])->delete();
                            session()->flash('success', 'Coaching details update successfully');

                        } else {
                            session()->flash('error', 'Test Series associated with this Exam Type, so those have to be selected');
                        }
                    }
                }   
            }else{
                session()->flash('errors', 'Something is wrong, please try again');
            }
            return redirect()->route('coaching.coaching_details');
        }
    }


    public function sendOtpEmail(Request $req)
    {
        $email = $req->email;
        $id = Auth::guard('coaching')->user()->coaching_id;
        $otp = mt_rand(100000,999999);
        if($email)
        {
            $user = CoachingMaster::where('id', $id)->first();

            if(count($user) > 0)
            {
                $update_arr = [
                            'email_otp'   => $otp,
                    ];
                $update = CoachingMaster::where('id', $id)->update($update_arr);
                if($update)
                {
                    $sendOtp = [];
                    $sendOtp['name'] = $user->coaching_name;
                    $sendOtp['email'] = $email;
                    $sendOtp['otp'] = $otp;
                    Mail::to($email)->send(new SendMailOtp($sendOtp));
                    echo 3;
                    exit;
                }
                else
                {
                    echo 2;
                    exit;
                }
            }
            else
            {
                echo 1;
                exit;
            }
        }
    }


    public function emailOtpVerify(Request $request)
    {
        $email_otp = $request->email_otp;
        $new_email = $request->newemail;
        
        $id = Auth::guard('coaching')->user()->coaching_id;
        $coaching_master = CoachingMaster::where('id', $id)->count();
        
        if($coaching_master > 0 && $email_otp != '')
        {
                $check = CoachingMaster::where('id', $id)->where('email_otp', $email_otp)->count();

                if($check > 0)
                {
                    $data = array('email_otp' => 0,  'email' => $new_email);
                    $return = CoachingMaster::where('id', $id)->update($data);
                    echo 1;
                    die;
                }
                else{
                    echo 2;
                    die;
                }
           
        }
    }

    public function image_upload(Request $request) 
    {
        $id = Auth::guard('coaching')->user()->id;
        // dd($id);
        $user = CoachingUser::find($id);
        if($request->profile_pic != 'undefined')
        {
            if(File::exists(public_path('storage/manager/picture/'.Auth::guard('coaching')->user()->picture)))
            {
                @unlink(public_path('storage/manager/picture/'.Auth::guard('coaching')->user()->picture));//unlik uploaded file
            }
            //Insert New Image
            $image = $request->file('profile_pic');
            //Create Image Name
            $img = 'profile-'.time().'.'.$image->getClientOriginalExtension(); 
            $location = public_path('storage/manager/picture/'.$img);
            $file = Image::make($image->getRealPath());
            $file->fit(150, 150, function ($constraint) {
                $constraint->aspectRatio();
            })->save($location);

            $update_arr = [
                    'picture' => $img
                ];
            $return = CoachingUser::where('id', $id)->update($update_arr);
            $response = array('status'=>200, 'message'=>'success', 'result'=>[]);
        } else {
            $response = array('status'=>201, 'message'=>'image not uploaded', 'result'=>[]);
        }
        return response()->json($response);
    }

    public function verify_username(Request $request)
    {
        $username = $request->username;
        if($username) {
            $exist = CoachingUser::where('coaching_username', $username)->first();
            if($exist) {
                $response = array('status'=>201, 'message'=>'Username not available', 'result'=>[]);
            } else {
                $response = array('status'=>200, 'message'=>'Username available', 'result'=>[]);
            }
        } else {
            $response = array('status'=>201, 'message'=>'Invalid username', 'result'=>[]);
        }
        return response()->json($response);
    }

    public function update_username(Request $request)
    {
        $username = $request->username;
        if($username) {
            if(!preg_match ('/^([a-zA-Z0-9]+)$/', $username)){
                $response = array('status'=>201, 'message'=>'Use only characters as username', 'result'=>[]);
            } else {
                $exist = CoachingUser::where('coaching_username', $username)->first();
                if($exist) {
                    $response = array('status'=>201, 'message'=>'Username not available', 'result'=>[]);
                } else {
                    CoachingUser::where('id', Auth::guard('coaching')->user()->id)->update(['coaching_username'=>$username]);
                    $response = array('status'=>200, 'message'=>'Username updated', 'result'=>[]);
                }
            }
        } else {
            $response = array('status'=>201, 'message'=>'Invalid username', 'result'=>[]);
        }
        return response()->json($response);
    }
}
