<?php

namespace App\Http\Controllers\Admin;


use Carbon\Carbon;
use App\Models\User;
use App\Models\Skill;
use App\Models\JobRole;
use App\Models\Candidate;
use App\Models\Webinars;
use App\Models\Education;
use App\Models\InterestedCandidatesWebinar;
use App\Models\Experience;
use App\Models\Profession;
// use App\Models\ContactInfo;
use App\Models\UniversitySuggest;
use App\Models\Universities;
use App\Models\Course;
use App\Models\Intake;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Models\SkillTranslation;
use App\Models\CandidateLanguage;
use Illuminate\Support\Facades\DB;
use Modules\Location\Entities\City;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Modules\Location\Entities\State;
use Modules\Location\Entities\Country;
use App\Http\Requests\CandidateRequest;
use Modules\Language\Entities\Language;
use App\Models\Setting;
use App\Notifications\CandidateCreateApprovalPendingNotification;
use Illuminate\Support\Facades\Notification;
use App\Notifications\CandidateCreateNotification;
use App\Notifications\UpdateCompanyPassNotification;
use App\Models\Documents;
use App\Models\DocumentSubcategory;
use Illuminate\Support\Facades\Storage;
use App\Models\DocumentCategory;
use App\Models\IndianUniversity;
use App\Models\Countries;
use App\Models\CandidateEducation;
use App\Models\CandidateDestination;
use App\Models\Followup;
use App\Models\CandidateExam;
use App\Models\Exam;
use App\Models\Admin;
use App\Models\CandidateApplication;
use PhpOffice\PhpSpreadsheet\Worksheet\Row;
use Spatie\Permission\Models\Role;
use App\Models\Source;
use App\Models\University;
use Illuminate\Validation\Rule;
use App\Models\UserTimeline;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use App\Models\Diploma_course;
use Illuminate\Support\Facades\Redirect;
use App\Notifications\AssignToChangeNotification;
use App\Exports\CustomerReportExport;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\StreamedResponse;
use App\Models\WhatsappTemplate;
use App\Models\Partner;
use App\Models\WorkExperience;
use App\Models\Service;
use DateTime;

class LeadManagementCandidateController extends Controller
{
    public function candidateEdit(Request $request, $id)
    {
        $candidate = Candidate::where('id',$id)->first();
        $formattedTime = Carbon::now()->format('Y-m-d H:i:s');
        $candidateDisplay = 0;
        $roleNames = Auth()->user()->getRoleNames()->toArray();
        // if (Auth::check() && !in_array('superadmin', $roleNames)) {
        if (Auth::check()) {
            if ($candidate) {
                $formattedTime = Carbon::now(); 
        
                if ($candidate->open_auth_id && $formattedTime <= $candidate->open_date_time && $candidate->open_auth_id != Auth::user()->id) {
                    $candidateDisplay = 1;
                    // flashWarning("This Custome is already opened by another user (" . ucwords(adminIdToNameGet($candidate->open_auth_id)) . ").");
                    // return back();
                }
        
                if (!$candidate->open_auth_id || $formattedTime > $candidate->open_date_time) {
                    if(!in_array('superadmin', $roleNames)){
                        $candidate->update([
                            'open_auth_id' => Auth::user()->id,
                            'open_date_time' => $formattedTime->addMinutes(30),
                        ]);
                    }
               
                }
            } else {
                flashError("Candidate not found.");
                return back();
            }
        }
   
        $roleEnvNames = explode(',', env('AVAILABLE_LEAD_ROLES', 'Lead Manager,Operation Manager'));
        $admin_list = Admin::where('id', '!=', 1)
            ->whereHas('roles', function ($query) use ($roleEnvNames) {
                $query->whereIn('name', $roleEnvNames);
            })
            ->get()
            ->toArray();

        // $admin_list = Admin::where('id', '!=', 1)
        // ->whereHas('roles', function ($query) {
        //     $query->whereIn('name', ['Lead Manager','Operation Manager']);
        // })
        // ->get()->toArray();
        // $contactInfo = ContactInfo::where('user_id', $user->id)->first();
        // $job_roles = JobRole::all();
        // $professions = Profession::all();
        // $experiences = Experience::all();
        // $educations = Education::all();
        // $skills = Skill::all();
        // $candidate_languages = CandidateLanguage::all(['id', 'name']);
        // $candidate->load('skills', 'languages:id,name', 'educations', 'destination', 'candidate_exam');
        // $candidate->load( 'languages:id,name', 'educations', 'destination', 'candidate_exam');
        $sourcesData = Source::distinct('name')->with("source")->where("parent_id",null)->get();
        // $candidate_exams = CandidateExam::all();

        $user = User::findOrFail($candidate->user_id);
        $countries = Countries::all('id', 'name');

        $preferred_countries = [];
        $other_countries = [];
        $jsonString = str_replace(['"', '[', ']'], '', @$candidate->destination[0]->preferred_country);
        $preferred_country_ids = explode(",", $jsonString);
        foreach ($preferred_country_ids as $preferred_country_id) {
            $country = $countries->firstWhere('id', $preferred_country_id);
            if ($country) {
                $preferred_countries[] = [
                    'id' => $country->id,
                    'name' => $country->name,
                ];
            }
        }
        $other_countries = $countries->reject(function ($country) use ($preferred_country_ids) {
            return in_array($country->id, $preferred_country_ids);
        })->toArray(); // Convert the collection to an array
        $countries = array_merge($preferred_countries, $other_countries);

        $jsonString = str_replace(['"', '[', ']'], '',  @$candidate->destination[0]->preferred_country);
        $preferred_country_ids = explode(",", $jsonString);
        $preferred_countries = [];
        $other_countries = [];
        foreach ($countries as $country) {
            if (in_array($country['id'], $preferred_country_ids)) {
                $preferred_countries[] = [
                    'id' => $country['id'],
                    'name' => $country['name'],
                ];
            }  
        }

        // $states = State::all('id','name');
        // $citys = City::all('id','name');
        $webinards= Webinars::select('id', 'webinar_name','webinar_link','dateTime')->get();
      
        $ind_universities = IndianUniversity::all(['id', 'name']);
        $universities = Universities::where('status', 1)->get(['id', 'name']);
        // $diploma_courses = Diploma_course::where('status',1)->get();
        $cadidate_id_web = $candidate->id;
        $candidate_web_find = InterestedCandidatesWebinar:: where('candidate_id', $cadidate_id_web )->pluck('webinar_id');  
        $main_intake = Intake::whereIn('status', [1])->pluck('name')->toArray();
        $webinar_history = InterestedCandidatesWebinar::where('candidate_id',$candidate->id)->get();
        $partners = Partner::select('id', 'name')->get();
        // $main_intake = [];
        // dd($main_intake);

        $document = Documents::where('user_id',$candidate->user_id)->get();
        // $document_link = "https://gradding.s3.ap-south-1.amazonaws.com";
        $exam_list = Exam::get();
        $mytime = Carbon::now();
        $today = $mytime->toDateString();

        // $work_experience = WorkExperience::where('candidate_id',$candidate->id)->get();


        $profile_progress = $this->profile_complete($candidate->id);
        
        $services = Service::select('id', 'name')->get();
      
        // dd($countries);
        return view('admin.lead-management.customer-detail', compact(
            'countries',
            'candidate',
            'user',
            'preferred_country_ids',
            'preferred_countries',
            'admin_list',
            'ind_universities',
            'universities',
            'webinards',
            'candidate_web_find',
            'main_intake',
            'partners',
            // 'document_link',
            'exam_list',
            'today',
            'webinar_history',
            'profile_progress',
            'sourcesData',
            // 'experiences',
            // 'document',
             // 'work_experience',
            // 'educations',
            // 'candidateDisplay',
             // 'diploma_courses',
              // 'candidate_languages',
            'services',

        ));
        //return view('admin.candidate.studentCase.studentCase');

    }

    public function followup(Request $request){
        $candidate = Candidate::where('user_id', $request->user_id)->first();
        $followups = Followup::latest()->where('user_id', $candidate->user_id)->get();
    
        $followupList = [];
    
        foreach ($followups as $followup){ 
            $followupItem = '<div class="single-folloup-list">
                <div class="f-head">
                    <p class="f-col">Followup Date:<span class="f-value">' . dateMonthTimeFormat($followup->datetime) . '</span></p>
                    <div class="head-mid">
                        <p class="f-col">Type:<span class="f-value">' . $followup->type . '</span></p>
                        <p class="f-col">Priority:<span class="f-value">' . $followup->priority . '</span></p>
                        <p class="f-col">Status:<span class="f-value">';
            $followupItem .= ($followup->follow_up_status == 'Not Connected') ? '<span class="badge badge-danger float-right ml-2">Not Connected</span>' : '<span class="badge badge-success float-right ml-2">Connected</span>';
            $followupItem .= '</span></p>
                    </div>
                    <div class="reminder">
                        <img src="' . asset('backend') . '/lead-management/images/customer-detail/reminder.svg" alt="reminder" width="100%" height="100%">
                        <span class="rem-head">Set Reminder</span>
                        <p class="rem-list">
                            <span class="rem-item">5 Min.</span>
                            <span class="rem-item">10 Min.</span>
                            <span class="rem-item">15 Min.</span>
                            <span class="rem-item">60 Min.</span>
                        </p>
                    </div>
                </div>
                <div class="f-body">
                    <p class="f-col">Assign To:<span class="f-value">' . ucwords(adminIdToNameGet($followup->assign_to)) . '</span></p>
                    <p class="f-col">Followup:<span class="f-value">' . $followup->followup_up . '</span></p>
                    <p class="f-col">Comment:<span class="f-value">' . $followup->comment . '</span></p>
                    <p class="f-col">Created By:<span class="f-value">' . @$followup->admin->name . '</span></p>
                    <p class="f-col">Created Date:<span class="f-value">' . dateMonthTimeFormat($followup->created_at) . '</span></p>
                </div>
            </div>';
            array_push($followupList, $followupItem);
        }
        
        if($followupList == null){
            $followupItem = '<div >
              <center>  No Data Avaialable </center>
            </div> <br>';
            array_push($followupList, $followupItem);
        }
        return $followupList;
    }

    public function student_case(Request $request,$user_id){
        $request->user_id = $user_id;
        $candidate = Candidate::where('user_id', $request->user_id)->first();
        $user = User::findOrFail($candidate->user_id);
        if($candidate->country_id != null && $candidate->country_id != ""){
            $countries = Country::where('id',$candidate->country_id)->select('name','id')->first();
            $candidate->country_name = $countries->name;
        }else{
            $countries = null;
            $candidate->country_name = "";
        }
        
        
        $mytime = Carbon::now();
        
        $from = new DateTime($candidate->birth_date);
        $to = new DateTime();
        
        $user->age = $from->diff($to)->y;
        $candidate->destination[0] = CandidateDestination::where('candidate_id',$candidate->id)->first();
        
        $preferred_countries = [];
        $other_countries = [];
        
        $jsonString = str_replace(['"', '[', ']'], '', @$candidate->destination[0]->preferred_country);
        $preferred_country_ids = explode(",", $jsonString);
        $country = null;
        $country_name = "";
        foreach ($preferred_country_ids as $preferred_country_id) {
            
            if($preferred_country_id != null && $preferred_country_id != ""){
                if($countries != null && $countries != ""){
                    $country = $countries->Where('id', $preferred_country_id)->first();
                
                    if ($country) {
                        $country_name = $country_name." ".$country->name;
                    }
                }
            }

            
        }
        $candidate->preferred_country = $country_name;
        $education_data = CandidateEducation::where('candidate_id',$candidate->id)->get();
       
        $work_experience = WorkExperience::where('candidate_id',$candidate->id)->get();
        foreach($work_experience as $work_experience_use){
            
            $date1 = new DateTime(@$work_experience_use->start_date);
            $date2 = new DateTime(@$work_experience_use->end_date);
            $diff = $date1->diff($date2);
           
            $work_experience_use->experience = "";
            if($diff->y > 0){
                $work_experience_use->experience = $work_experience_use->experience."".$diff->y."Year ";
            }
            if($diff->m > 0){
                $work_experience_use->experience = $work_experience_use->experience."".$diff->m."Month ";
            }
            if($diff->d > 0){
                $work_experience_use->experience = $work_experience_use->experience."".$diff->d."Day ";
            }
            
            
            $work_experience_use->start_date = date('d-m-Y', strtotime($work_experience_use->start_date));
            $work_experience_use->end_date = date('d-m-Y', strtotime($work_experience_use->end_date));
            
        }
        $english_test = [
            'test_name' => '',
            'test_taken_date' => '',
            'test_result_date' => '',
            'test_scores' => '',
            'speaking_scores' => '',
            'reading_scores' => '',
            'listening_scores' => '',
            'writing_scores' => '',
        ];
        $abroad_test = [
            'test_name' => '',
            'test_taken_date' => '',
            'test_result_date' => '',
            'test_scores' => '',
        ];
        
        foreach ($candidate->candidate_exam as $index => $exam){

            
            if ($exam->test_type == 'Study Abroad Test'){
                
                $abroad_test = [
                    'test_name' => $exam->test_name,
                    'test_taken_date' => $exam->test_taken_date,
                    'test_result_date' => $exam->test_result_date,
                    'test_scores' => $exam->test_scores,
                   
                ];
            }
            else if($exam->test_type == 'English Proficiency'){
               
                $english_test = [
                    'test_name' => $exam->test_name,
                    'test_taken_date' => $exam->test_taken_date,
                    'test_result_date' => $exam->test_result_date,
                    'test_scores' => $exam->test_scores,
                    'speaking_scores' => $exam->speaking_scores,
                    'reading_scores' => $exam->reading_scores,
                    'listening_scores' => $exam->listening_scores,
                    'writing_scores' => $exam->writing_scores,
                ];
            }
            
        }
        
        return view('admin.candidate.studentCase.studentCase',compact('candidate','user','country','work_experience','education_data','english_test'));
    }


    public function update(Request $request){
         
        if($request->type == "personal_info_form"){

            if($request->operation_type == "cancel"){
                $user = User::findOrFail($request->user_id);
                $candidate = Candidate::where('user_id', $request->user_id)->first();
                $userData = $user->toArray();
                $candidateData = $candidate->toArray();
                $fetch_data = array_merge($userData, $candidateData);
                return response()->json(['status'=>4,'user'=>$user,'fetch_data'=>$fetch_data]);

            }else{

                
                $validator = Validator::make($request->all(), [
                    'name' => 'required|max:100',
                    'phone' => [
                        'required',
                        'max:20', 
                        Rule::when(!empty($request->phone), Rule::unique('users', 'phone')->where(function ($query) {
                            return $query->whereNull('deleted_at');
                        })->ignore($request->user_id)),
                        Rule::when(empty(@$request->email), ['numeric', Rule::unique('users', 'phone')->where(function ($query) {
                            return $query->whereNull('deleted_at');
                        })->ignore($request->user_id)])
                    ],
                    'email' => [
                        'required',
                        'email',
                        Rule::unique('users', 'email')->where(function ($query) use ($request) {
                            return $query->whereNull('deleted_at');
                        })->ignore($request->user_id),
                    ],
                    'birth_date' => 'required|date|max:20',
                    'alternate_phone' => 'nullable|max:20',
                    'alternate_email' => 'nullable|email | max:300',
                    'gender' => 'required|max:20',
                    'passport_number' => 'required|max:20',
                    'passport_expiry' => 'required|max:20',
                    'country' => 'required',
                    'state_id' => 'required',
                    'city_id' => 'required',
                    'visa_refusal' => 'required',
                    'marital_status' => 'required',
                ]);
                $validator->errors = $validator->errors();
                
                if ($request->visa_refusal == "1") {
                    $validatornew = Validator::make($request->all(), [
                        'date_of_visa_expiration' => 'required|date',
                    ]);
                            
                    $validator->errors = $validator->errors()->merge($validatornew->errors());
                
                }
            
                if ($validator->fails()) {
                    $errors = $validator->errors;
                    
                    return response()->json([
                        'error' => $errors,
                        'status' => 3
                    ]);
                }
                
                
                if (!empty($request->birth_date)) {
                    $dateTime = Carbon::parse($request->birth_date);
                    $birth_date = $request['birth_date'] = $dateTime->format('Y-m-d H:i:s');
                } else {
                    $birth_date = null;
                }

                if (!empty($request->passport_expiry)) {
                    $dateTime = Carbon::parse($request->passport_expiry);
                    $passport_expiry = $request['birth_date'] = $dateTime->format('Y-m-d H:i:s');
                } else {
                    $passport_expiry = null;
                }

                if( $request->visa_refusal  == "Yes"){
                    dd("jhhfdjhjh");
                }
        
                $request->prefferd_time =  date('H:i:s', strtotime($request->prefferd_time));
                $user = User::FindOrFail($request->user_id);
                $user_save_data = [
                    'name' => $request->name,
                    'phone' => $request->phone,
                    'alternate_phone' => $request->alternate_phone,
                    'secondary_email' => $request->secondary_email,
                    'email' => $request->email,
                    'last_name' => $request->last_name,
                    'country' => $request->country,
                    'prefferd_time' => $request->prefferd_time,
                    'source'  => $request->source,
                    'partner_id'=> $request->partner_id,
                    'whatsapp_marketing_status' => $request->whatsapp_marketing_status,
                ];
                
                $candidate_save_data = [
                    'birth_date' => $birth_date,
                    'passport_number' => $request->passport_number,
                    'passport_expiry' => $passport_expiry,
                    'gender' => $request->gender,
                    'country_id' => $request->country_id,
                    'state_id' => $request->state_id,
                    'city_id' => $request->city_id,
                    'visa_refusal' => $request->visa_refusal,
                    'visa_refusal_reason' => $request->visa_refusal_reason,
                    'date_of_visa_expiration' => $request->date_of_visa_expiration,
                    'visa_categories' => $request->visa_categories,
                    'marital_status' => $request->marital_status,
                    'spouse_comming' => $request->spouse_comming,
                    'spouse_qualification'  => $request->spouse_qualification,
                    'spouse_income' => $request->spouse_income,
                    'kids_count' => $request->kids_count,
                    'accompanying_applicant'  => $request->accompanying_applicant,
                    'comment' => $request->comment,
                    'spouse_employment_status'  => $request->spouse_employment_status,
                    "student_category" => $request->student_category,
                    "notes" => $request->notes,
                    "address" => $request->address,

                ];
                $user_status = User::where('id',$user->id)->update($user_save_data);
                $candidate_status = Candidate::where('user_id',$request->user_id)->update($candidate_save_data);
                
                $user = User::findOrFail($request->user_id);
                $candidate = Candidate::where('user_id', $request->user_id)->first();
                $userData = $user->toArray();
                
                $candidateData = $candidate->toArray();
                
                $fetch_data = array_merge($userData, $candidateData);
                
                if($user_status == 1 && $candidate_status == 1){
                    return response()->json(['status'=>1,'message' => "Information Successfully Updated",'fetch_data' =>$fetch_data]);
                }else{
                    return response()->json(['status'=>2,'message' => "Please Try Again Something Wrong Detail Not Save",'fetch_data' =>$fetch_data]); 
                }
            }
            
        }
        elseif($request->type == "education_detail"){

            
            if($request->doc_id == "null"){
                if ($request->education_board == "10th" || $request->education_board == "12th") {
                    $request->education_board = $request->education_board;
                    if($request->education_board == "other"){
                        $request->education_board = $request->board_other;
                    }
                }
                elseif ($request->education_board == "Bachelors" || $request->education_board == "Masters" || $request->education_board == "Diploma") {
                    $request->education_board = $request->uni_board;
                    if($request->uni_board == "other"){
                        $request->education_board = $request->uni_other;
                    }
                }
                
                $candidate = Candidate::where('user_id',$request->user_id)->first();
                
                $data = CandidateEducation::where('candidate_id',$candidate->id)->where('qualification',$request->qualification)->first();
                
                if($data == null){
                    $education_data = [
                        'qualification' => $request->qualification,
                        'education_board' => $request->education_board,
                        'year' => $request->admission_year,
                        'passing_year' => $request->passing_year,
                        'institute_name' => $request->institute_name,
                        'grade_percentage' => $request->grade_percentage,
                        'medium' => $request->medium,
                        'backlogs' => $request->backlog,
                        'gaps' => $request->gap,
                        'candidate_id' => $candidate->id,
                        'grade_type' => $request->grade_type,
                    ];
                    $data = CandidateEducation::insert($education_data);
                    
                    if($data == 1){
                        return response()->json(['status'=>1,'message' => "Education Detail Successfully Save"]);
                    }else{
                        return response()->json(['status'=>0,'message' => "Please Try Again Something Wrong Detail Not Save"]);  
                    }
                }else{
                    return response()->json(['status'=>2,'message' => "Already Document Exist Please Select another type Detail qualification / update Detail"]);  
                }
                
            }else{
                
                if ($request->qualification == "10th" || $request->qualification == "12th") {
                    $request->education_board = $request->education_board;
                    if($request->education_board == "other"){
                        $request->education_board = $request->board_other;
                    }
                }
                elseif ($request->qualification == "Bachelors" || $request->qualification == "Masters" || $request->qualification == "Diploma") {
                    $request->education_board = $request->uni_board;
                    if($request->uni_board == "other"){
                        $request->education_board = $request->uni_other;
                    }
                }
                
                $candidate = Candidate::where('user_id',$request->user_id)->first();
                $data = CandidateEducation::whereNotIn('id', [$request->doc_id])->where('candidate_id',$candidate->id)->where('qualification',$request->qualification)->first();
                if($data == null){
                    $education_data = [
                        'qualification' => $request->qualification,
                        'education_board' => $request->education_board,
                        'year' => $request->admission_year,
                        'passing_year' => $request->passing_year,
                        'institute_name' => $request->institute_name,
                        'grade_percentage' => $request->grade_percentage,
                        'medium' => $request->medium,
                        'backlogs' => $request->backlog,
                        'gaps' => $request->gap,
                        'candidate_id' => $candidate->id,
                        'grade_type' => $request->grade_type,
                        'remark' => $request->remark
        
                    ];
                    $data = CandidateEducation::where('id',$request->doc_id)->update($education_data);
                    if($data == 1){
                        return response()->json(['status'=>1,'message' => "Education Detail Successfully Updated"]);
                    }else{
                        return response()->json(['status'=>0,'message' => "Please Try Again Something Wrong Detail Not Update"]);  
                    }
                }else{
                    return response()->json(['status'=>2,'message' => "Already Detail Exist Please Select another type qualification / update detail"]);  
                }
            }
            
        }
        
        elseif($request->type == "study_abroad_form"){

            if($request->operation_type == "cancel"){
                $candidate = Candidate::where('user_id', $request->user_id)->first();
                $candidatedestination = CandidateDestination::where('candidate_id', $candidate->id)->first();
                if($candidatedestination == null){
                    $fetch_data = [
                        "preferred_country" => null,
                        "preferred_state" => null,
                        "preferred_city" => null,
                        "preferred_program" => null,
                        "preferred_course" => null,
                        "preffered_stream" => null,
                        "applied_university_name" => null,
                        "applied_university_status" => "No",
                        "consultant_status" => "No",
                        "consultant_name" => null,
                        "intake" => null,
                        "intake_sessions" => null,
                        "intake_months" => null,
                        "intake_years" => null,
                    ];

                }else{
                    $fetch_data = $candidatedestination->toArray();
                    
                    if($fetch_data['applied_university_name'] != Null && $fetch_data['applied_university_name'] != ""){
                        $fetch_data['applied_university'] = "Yes";
                    }else{
                        $fetch_data['applied_university'] = "No";
                    }

                    if($fetch_data['consultant_name'] != Null && $fetch_data['consultant_name'] != ""){
                        $fetch_data['consultant'] = "Yes";
                    }else{
                        $fetch_data['consultant'] = "No";
                    }
                  
                }
                return response()->json(['status'=>4,'fetch_data'=>$fetch_data]);

            }else{

                $candidate = Candidate::where('user_id',$request->user_id)->first();

                if($request->applied_university == "Yes"){
                    
                }else{
                    $request->applied_university_name = NULL;
                }

                if($request->consultant == "Yes"){
                    
                }else{
                    $request->consultant_name = NULL;
                }

            
                $_POST['intake_years'] = $request->intake_years[0];
                $_POST['intake_months'] = $request->intake_months[0];
                $_POST['preferred_country'] =  $request->preferred_country[0];
                
                $validator = Validator::make($_POST, [
                    'preferred_country' => 'required',
                    'intake_years' => 'required',
                    'intake_months' => 'required',
                    
                ]);
            
                
                if ($validator->fails()) {
                    $errors = $validator->errors();
                    return response()->json([
                        'error' => $errors,
                        'status' => 3
                    ]);
                }

                $candidate_save_data = [
                    "intake_years" => $request->intake_years[0],
                    "intake_months" => $request->intake_months[0],
                    "consultant_name" => $request->consultant_name,
                    "preferred_country" => $request->preferred_country[0],
                    "preferred_course" => $request->preferred_course,
                    "applied_university_name" => $request->applied_university_name,
                    "preferred_program" => $request->preferred_program,
                    'candidate_id' => $candidate->id,
                ];
                
                
                $candidate_status = CandidateDestination::where('candidate_id',$candidate->id)->update($candidate_save_data);
                
                $candidate = Candidate::where('user_id', $request->user_id)->first();
                $candidatedestination = CandidateDestination::where('candidate_id', $candidate->id)->first();
                if($candidatedestination == null){
                    $fetch_data = [
                        "preferred_country" => null,
                        "preferred_state" => null,
                        "preferred_city" => null,
                        "preferred_program" => null,
                        "preferred_course" => null,
                        "preffered_stream" => null,
                        "applied_university_name" => null,
                        "applied_university_status" => "No",
                        "consultant_status" => "No",
                        "consultant_name" => null,
                        "intake" => null,
                        "intake_sessions" => null,
                        "intake_months" => null,
                        "intake_years" => null,
                    ];

                }else{
                    $fetch_data = $candidatedestination->toArray();
                    
                    if($fetch_data['applied_university_name'] != Null && $fetch_data['applied_university_name'] != ""){
                        $fetch_data['applied_university'] = "Yes";
                    }else{
                        $fetch_data['applied_university'] = "No";
                    }

                    if($fetch_data['consultant_name'] != Null && $fetch_data['consultant_name'] != ""){
                        $fetch_data['consultant'] = "Yes";
                    }else{
                        $fetch_data['consultant'] = "No";
                    }
                  
                }
                
                if( $candidate_status > 0){
                    return response()->json(['status'=>1,'message' => "Information Successfully Updated",'fetch_data'=>$fetch_data]);
                }else{
                    $candidate_status = CandidateDestination::insert($candidate_save_data);
                    if( $candidate_status > 1){
                        return response()->json(['status'=>1,'message' => "Information Successfully Insert",'fetch_data'=>$fetch_data]);
                    }else{
                        return response()->json(['status'=>0,'message' => "Please Try Again Something Wrong Detail Not Save",'fetch_data'=>$fetch_data]); 
                    }
                }
            }
            
        }
        elseif($request->type == "budget_preference_form"){
            if($request->operation_type == "cancel"){
                $candidate = Candidate::where('user_id', $request->user_id)->first();
                
                $fetch_data = $candidate->ToArray();
                
                return response()->json(['status'=>4,'fetch_data'=>$fetch_data]);

            }else{
                $candidate_save_data = [
                    "budget" => $request->budget,
                    "fund_source" => $request->fund_source,
                    "loan_type" => $request->loan_type,
                ];

                $candidate_status = Candidate::where('user_id',$request->user_id)->update($candidate_save_data);
                $candidate = Candidate::where('user_id', $request->user_id)->first();
                
                $fetch_data = $candidate->ToArray();
                if( $candidate_status == 1){
                    return response()->json(['status'=>1,'message' => "Information Successfully Updated"]);
                }else{
                    return response()->json(['status'=>1,'message' => "Please Try Again Something Wrong Detail Not Save"]); 
                }
            }
            
        }
        elseif($request->type == "test_status_form"){
            
            if($request->operation_type == "cancel"){
                $candidate = Candidate::where('user_id', $request->user_id)->first();
                $candidate_exam_study_abroad= CandidateExam::where('candidate_id',$candidate->id)->where('test_type',"Study Abroad Test")->first();
                $candidate_exam_english= CandidateExam::where('candidate_id',$candidate->id)->where('test_type',"English Proficiency")->first();
                $examList = Exam::get();
                $englishFlag = false;
                $abroadFlag = false;

                foreach ($examList as $exam) {
                    if ($candidate_exam_study_abroad && $exam->type === "Study Abroad" && $exam->name === $candidate_exam_study_abroad->test_name) {
                        $abroadFlag = true;
                    }
                    if ($candidate_exam_english && $exam->type === "English Proficiency" && $exam->name === $candidate_exam_english->test_name) {
                        $englishFlag = true;
                    }
                }

                if ($englishFlag == false) {
                    
                    $candidate_exam_english->english_other = $candidate_exam_english->test_name;
                    $candidate_exam_english->test_name = "other";
                }
               
               
                if ($abroadFlag == false) {
                    
                    $candidate_exam_study_abroad->aptitude_other = $candidate_exam_study_abroad->test_name;
                    $candidate_exam_study_abroad->test_name = "other";
                }

                $englishTestData = ($candidate_exam_english) ? [
                    'english_test' => $candidate_exam_english->test_name,
                    'english_other' => $candidate_exam_english->english_other,
                    'english_test_scores' => $candidate_exam_english->test_scores,
                    'english_test_taken_date' => date('Y-m-d', strtotime($candidate_exam_english->test_taken_date)),
                    'english_test_result_date' => date('Y-m-d', strtotime($candidate_exam_english->test_result_date)),
                    'english_speaking_scores' => $candidate_exam_english->speaking_scores,
                    'english_reading_scores' => $candidate_exam_english->reading_scores,
                    'english_listening_scores' => $candidate_exam_english->listening_scores,
                    'english_writing_scores' => $candidate_exam_english->writing_scores,
                ] : [
                    'english_test' => "",
                    'english_test_scores' => "",
                    'english_test_taken_date' => "",
                    'english_test_result_date' => "",
                    'english_speaking_scores' => "",
                    'english_reading_scores' => "",
                    'english_listening_scores' => "",
                    'english_writing_scores' => "",
                ];

                $abroadTestData = ($candidate_exam_study_abroad) ? [
                    'aptitude_other' => $candidate_exam_study_abroad->aptitude_other,
                    'aptitude_test' => $candidate_exam_study_abroad->test_name,
                    'aptitude_test_scores' => $candidate_exam_study_abroad->test_scores,
                    'aptitude_test_taken_date' => date('Y-m-d', strtotime($candidate_exam_study_abroad->test_taken_date)),
                    'aptitude_test_result_date' => date('Y-m-d', strtotime($candidate_exam_study_abroad->test_result_date)),
                ] : [
                    'aptitude_test' => "",
                    'aptitude_test_scores' => "",
                    'aptitude_test_taken_date' => "",
                    'aptitude_test_result_date' => "",
                ];

                $fetch_data = array_merge($abroadTestData, $englishTestData);

                return response()->json(['status'=>4,'fetch_data'=>$fetch_data]);

            }else{
                $validator = Validator::make($request->all(), [
                    'english_test_taken_date' => 'required | date| max:20',
                    'english_test_result_date' => 'required | date| max:20',
                    'english_test_scores' => 'required | max:20',
                    'english_speaking_scores' => 'required | max:20',
                    'english_reading_scores' => 'required | max:20',
                    'english_listening_scores' => 'required | max:20',
                    'english_writing_scores' => 'required | max:20',
                    'aptitude_test_taken_date' => 'required | date|  max:20',
                    'aptitude_test_result_date' => 'required | date |  max:20',
                    'aptitude_test_scores' => 'required |  max:20 ' ,
                    'english_test' => 'required |  max:20',
                    'aptitude_test' => 'required |  max:20',
                ]);
                if ($validator->fails()) {
                    $errors = $validator->errors();
                    return response()->json([
                        'error' => $errors,
                        'status' => 3
                    ]);
                }
                if($request->english_test == "other"){
                    $validator = Validator::make($request->all(), [
                        'english_other' => 'required | Max:50',
                    ]);
                }
    
                if($request->aptitude_test == "other"){
                    $validator = Validator::make($request->all(), [
                        'aptitude_other' => 'required | Max:50',
                    ]);
                }
                
                if ($validator->fails()) {
                    $errors = $validator->errors();
                    return response()->json([
                        'error' => $errors,
                        'status' => 3
                    ]);
                } 
                
                $candidate = Candidate::where('user_id',$request->user_id)->first();
                if($request->english_test == "other" ){
                    $request->english_test = $request->english_other;
                }
                $english_test_data = [
                    'candidate_id' =>$candidate->id,
                    'test_type' => "English Proficiency",
                    'test_name' => $request->english_test,
                    
                    'test_scores' => $request->english_test_scores,
                    'test_taken_date' => $request->english_test_taken_date,
                    'test_result_date' => $request->english_test_result_date,
                    'speaking_scores' => $request->english_speaking_scores,
                    'reading_scores' => $request->english_reading_scores,
                    'listening_scores' => $request->english_listening_scores,
                    'writing_scores' => $request->english_writing_scores,
                ];

                
                if(CandidateExam::where('candidate_id',$candidate->id)->where('test_type',"English Proficiency")->exists()){ 
                    $english_status = CandidateExam::where('candidate_id',$candidate->id)->where('test_type',"English Proficiency")->update($english_test_data);
                }else{
                    $english_status = CandidateExam::insert($english_test_data);
                }
            
                if($request->aptitude_test == "other"){
                    $request->aptitude_test = $request->aptitude_other;
                }
                $abroad_test_data = [
                    'candidate_id' =>$candidate->id,
                    'test_type' => "Study Abroad Test",
                    'test_name' => $request->aptitude_test,
                    'test_scores' => $request->aptitude_test_scores,
                    'test_taken_date' => $request->aptitude_test_taken_date,
                    'test_result_date' => $request->aptitude_test_result_date,
                ];
    
                if(CandidateExam::where('candidate_id',$candidate->id)->where('test_type',"Study Abroad Test")->exists()){ 
                    $abroad_status = CandidateExam::where('candidate_id',$candidate->id)->where('test_type',"Study Abroad Test")->update($abroad_test_data);
                }else{
                    $abroad_status =  CandidateExam::insert($abroad_test_data);
                }
                $candidate = Candidate::where('user_id', $request->user_id)->first();
                $candidate_exam_study_abroad= CandidateExam::where('candidate_id',$candidate->id)->where('test_type',"Study Abroad Test")->first();
                $candidate_exam_english= CandidateExam::where('candidate_id',$candidate->id)->where('test_type',"English Proficiency")->first();
                $examList = Exam::get();
                $englishFlag = false;
                $abroadFlag = false;

                foreach ($examList as $exam) {
                    if ($candidate_exam_study_abroad && $exam->type === "Study Abroad" && $exam->name === $candidate_exam_study_abroad->test_name) {
                        $abroadFlag = true;
                    }
                    if ($candidate_exam_english && $exam->type === "English Proficiency" && $exam->name === $candidate_exam_english->test_name) {
                        $englishFlag = true;
                    }
                }

                if ($candidate_exam_english && !$englishFlag) {
                    $candidate_exam_english->test_name = "other";
                    $candidate_exam_english->english_other = $candidate_exam_english->test_name;
                }

                if ($candidate_exam_study_abroad && !$abroadFlag) {
                    $candidate_exam_study_abroad->test_name = "other";
                    $candidate_exam_study_abroad->aptitude_other = $candidate_exam_study_abroad->test_name;
                }

                $englishTestData = ($candidate_exam_english) ? [
                    'english_test' => $candidate_exam_english->test_name,
                    'english_other' => $candidate_exam_english->english_other,
                    'english_test_scores' => $candidate_exam_english->test_scores,
                    'english_test_taken_date' => date('Y-m-d', strtotime($candidate_exam_english->test_taken_date)),
                    'english_test_result_date' => date('Y-m-d', strtotime($candidate_exam_english->test_result_date)),
                    'english_speaking_scores' => $candidate_exam_english->speaking_scores,
                    'english_reading_scores' => $candidate_exam_english->reading_scores,
                    'english_listening_scores' => $candidate_exam_english->listening_scores,
                    'english_writing_scores' => $candidate_exam_english->writing_scores,
                ] : [
                    'english_test' => "",
                    'english_test_scores' => "",
                    'english_test_taken_date' => "",
                    'english_test_result_date' => "",
                    'english_speaking_scores' => "",
                    'english_reading_scores' => "",
                    'english_listening_scores' => "",
                    'english_writing_scores' => "",
                ];

                $abroadTestData = ($candidate_exam_study_abroad) ? [
                    'aptitude_other' => $candidate_exam_study_abroad->aptitude_other,
                    'aptitude_test' => $candidate_exam_study_abroad->test_name,
                    'aptitude_test_scores' => $candidate_exam_study_abroad->test_scores,
                    'aptitude_test_taken_date' => date('Y-m-d', strtotime($candidate_exam_study_abroad->test_taken_date)),
                    'aptitude_test_result_date' => date('Y-m-d', strtotime($candidate_exam_study_abroad->test_result_date)),
                ] : [
                    'aptitude_test' => "",
                    'aptitude_test_scores' => "",
                    'aptitude_test_taken_date' => "",
                    'aptitude_test_result_date' => "",
                ];

                $fetch_data = array_merge($abroadTestData, $englishTestData);

                if( $english_status > 0 && $abroad_status > 0){
                    return response()->json(['status'=>1,'message' => "Information Successfully Updated",'fetch_data' => $fetch_data]);
                }else{
                    return response()->json(['status'=>0,'message' => "Please Try Again Something Wrong Detail Not Save",'fetch_data' => $fetch_data]); 
                }
            }
            
        }
        elseif($request->type == "webinar_form"){
            if($request->webinar_id == null){
                return response()->json(['status'=>0,'message' => "Webinar Is null Please Select Valid Webinar"]); 
            }
            $candidate = Candidate::where('user_id',$request->user_id)->first();
            
            $webinar = [
                'candidate_id' =>$candidate->id,
                'webinar_id' => $request->webinar_id,
                
            ];
            if(InterestedCandidatesWebinar::where('candidate_id',$candidate->id)->where('webinar_id',$request->webinar_id)->exists()){
                return response()->json(['status'=>1,'message' => "You Are Already Join This Webinar"]); 
            }
            else{
                $webinar_status = InterestedCandidatesWebinar::insert($webinar);
                if( $webinar_status > 0){
                    $mytime = Carbon::now();
                    $today = $mytime->toDateString();
                    $cadidate_id_web = $candidate->id;
                    $webinar_history = InterestedCandidatesWebinar::where('candidate_id',$candidate->id)->get();
                    $webinards= Webinars::select('id', 'webinar_name','webinar_link','dateTime')->get();
                    $candidate_web_find = InterestedCandidatesWebinar:: where('candidate_id', $cadidate_id_web )->pluck('webinar_id'); 
                    return response()->json(['status'=>1,'message' => "Webinar Successfully Added",'today'=>$today,'webinar_history'=>$webinar_history,'webinards'=>$webinards,'candidate_web_find'=>$candidate_web_find]);
                }else{
                    return response()->json(['status'=>0,'message' => "Please Try Again Something Wrong Detail Not Save"]); 
                }
            }
        }
        elseif($request->type == "lead_type"){
           
            $data = [
              
                'lead_type' => $request->lead_type,
            ];
          
            $stage_data = User::where('id',$request->user_id)->update($data);
            
            if( $stage_data > 0){
                return response()->json(['status'=>1,'message' => "Stage Changed Successfully","stage" => $request->stage]);
            }else{
                $stage_data = User::where('id',$request->user_id)->first();
                return response()->json(['status'=>0,'message' => "Please Try Again Something Wrong Detail Not Save","stage" => $stage_data->stages]); 
            }
        }

        elseif($request->type == "stage_change"){
           
            $data = [
              
                'stages' => $request->stage,
            ];
          
            $stage_data = User::where('id',$request->user_id)->update($data);
           
            if( $stage_data > 0){
                $stage_name = getStageGroup($request->stage);
                return response()->json(['status'=>1,'message' => "Stage Changed Successfully","stage" => $request->stage, "stage_name" => $stage_name]);
            }else{
                
                $stage_data = User::where('id',$request->user_id)->first();
                $stage_name = getStageGroup($stage_data->stages);
                return response()->json(['status'=>0,'message' => "Please Try Again Something Wrong Detail Not Save","stage" => $stage_data->stages, "stage_name" => $stage_name]); 
            }
        }
        elseif($request->type == "stage_save"){
            if($request->dropped_reason == "other"){
                $request->dropped_reason = $request->dropped_reason1;
            }

            $data = [
              
                'stages' => $request->stage,
                'dropped_reason' => $request->dropped_reason
                
            ];
          
            $stage_data = User::where('id',$request->user_id)->update($data);
            
            if( $stage_data > 0){
                $stage_name = getStageGroup($request->stage);
                return response()->json(['status'=>1,'message' => "Stage Changed Successfully","stage" => $request->stage, "stage_name" => $stage_name]);
            }else{
                $stage_data = User::where('id',$request->user_id)->first();
                $stage_name = getStageGroup($stage_data->stages);
                return response()->json(['status'=>0,'message' => "Please Try Again Something Wrong Detail Not Save","stage" => $stage_data->stages ,"stage_name" => $stage_name]); 
            }
        }
        elseif($request->type == "work_experience"){
            $validator = Validator::make($request->all(), [
                'organization_name' => 'required| max: 250',
                'organization_type' => 'required| max: 250',
                'organization_address' => 'required| max: 250',
                'position' => 'required| max: 250',
                'start_date' => 'required| max: 250',
                'end_date' => 'required| max: 250',
                'experience_letter' => 'required| max: 250',
                'mode_of_salery' => 'required| max: 250',
            ]);
        
            if ($validator->fails()) {
                $errors = $validator->errors();
                return response()->json([
                    'error' => $errors,
                    'status' => 3
                ]);
            } 
            
            if($request->id != null){
                
                $data = [
                    "organization_name" => $request->organization_name,
                    "organization_type" => $request->organization_type,
                    "organization_address" => $request->organization_address,
                    "position" => $request->position,
                    "start_date" => $request->start_date,
                    "end_date" => $request->end_date,
                    "name" => $request->name,
                    "department_name" => $request->department_name,
                    "mobile_number" => $request->mobile_number,
                    "experience_letter" => $request->experience_letter,
                    "mode_of_salery" => $request->mode_of_salery,
                ];
                
                $stage_data = WorkExperience::where('id',$request->id)->update($data);
            }else{
                $candidate = Candidate::where('user_id',$request->user_id)->first();
                $data = [
                    "organization_name" => $request->organization_name,
                    "organization_type" => $request->organization_type,
                    "organization_address" => $request->organization_address,
                    "position" => $request->position,
                    "start_date" => $request->start_date,
                    "end_date" => $request->end_date,
                    "name" => $request->name,
                    "department_name" => $request->department_name,
                    "mobile_number" => $request->mobile_number,
                    "candidate_id" => $candidate->id,
                ];
                $stage_data = WorkExperience::insert($data);
            }
            
            
            if( $stage_data > 0){
                return response()->json(['status'=>1,'message' => "Data Successfully Saved"]);
            }else{
                $stage_data = User::where('id',$request->user_id)->first();
                return response()->json(['status'=>0,'message' => "Please Try Again Something Wrong Detail Not Save"]); 
            }
        }
        

        dd($request);
    }
    public function education_detail_delete(Request $request){
       
        if($request->doc_type == "education"){
            $data = CandidateEducation::where('id', $request->doc_delete_id)->delete();
            if($data == 1){
                return response()->json(['status'=>1,'message' => "Education Detail Successfully Deleted","type" =>$request->doc_type]);
            }else{
                return response()->json(['status'=>0,'message' => "Please Try Again Something Wrong Detail Not Delete","type" =>$request->doc_type]);  
            }
        }else if($request->doc_type == "document"){
            
            $data = Documents::where('id', $request->doc_delete_id)->delete();
            if($data == 1){
                return response()->json(['status'=>1,'message' => "Document Successfully Deleted","type" =>$request->doc_type]);
            }else{
                return response()->json(['status'=>0,'message' => "Please Try Again Something Wrong Document Not Delete","type" =>$request->doc_type]);  
            }
        
        }else if($request->doc_type == "work_experience"){
                
            $data = WorkExperience::where('id', $request->doc_delete_id)->delete();
            if($data == 1){
                return response()->json(['status'=>1,'message' => "Work Experience Detail Successfully Deleted","type" =>$request->doc_type]);
            }else{
                return response()->json(['status'=>0,'message' => "Please Try Again Something Wrong Work Experience Detail Not Delete","type" =>$request->doc_type]);  
            }
        }
       
    }

    public function check_qualification_year(Request $request){
        $down_to_up = ['10th','12th','Diploma','Bachelors','Masters'];
        $up_to_down = ['Masters','Bachelors','Diploma','12th','10th'];
        $candidate = Candidate::where('user_id',$request->user_id)->first();
        $max[0] = 2024;
        $min[0] = 1980;

        $data = CandidateEducation::where('candidate_id',$candidate->id)->get();
        $year = 0;
        $flag = 0;
        $i = 0;
        
        foreach($down_to_up as $down_to_up_use){
            $year++;
            if($down_to_up_use == $request->qualification){
                $flag = 1;
            }else{
                if($flag == 1){
                    foreach($data as $data_use){
                        if($data_use->qualification == $down_to_up_use){
                            $max[$i] = $data_use->passing_year - 1;
                            
                            $i++;
                            break;
                        }
                    }
                }
            }
            
            
        }
       
        $flag = 0;
        $i = 0;
        
        foreach($up_to_down as $up_to_down_use){
            $year++;
            
            if($up_to_down_use == $request->qualification){
                $flag = 1;
               
            }else{
                if($flag == 1){
                    foreach($data as $data_use){
                        if($data_use->qualification == $up_to_down_use){
                            $min[$i] = $data_use->passing_year+1;
                            $i++;
                            break;
                        }
                    }
                }
            }
        }

        if($request->doc_id == "null"){
            $candidate = Candidate::where('user_id',$request->user_id)->first();
            $education_data = CandidateEducation::where('candidate_id',$candidate->id)->get();
            
        }else{
            $education_data = CandidateEducation::where('id',$request->doc_id)->first();
           
        }
        // if($min <= 1980){
        //     $min = 1980;
        // }
        // if($max <= 2024){
        //     $min = 2024;
        // }
        $data = 1;
        if($data == 1){
            return response()->json(['status'=>1,'message' => "Education Detail Successfully Fetch",'max'=>$max[0] , 'min' => $min[0],'education_detail' => $education_data ]);
        }else{
            return response()->json(['status'=>0,'message' => "Please Try Again Something Wrong Detail Not Delete",'max'=>$max[0] , 'min' => $min[0]]);  
        }
    }
    

    public function education_detail_get(Request $request){
        if($request->doc_id == "null"){
            $candidate = Candidate::where('user_id',$request->user_id)->first();
            $education_data = CandidateEducation::where('candidate_id',$candidate->id)->get();
            
        }else{
            $education_data = CandidateEducation::where('id',$request->doc_id)->first();
            
        }
        
        
        return $education_data;
    }

    public function form_work_experience_get(Request $request){
        if($request->id == "null"){
            $candidate = Candidate::where('user_id',$request->user_id)->first();
            $education_data = WorkExperience::where('candidate_id',$candidate->id)->get();
            foreach($education_data as $education_data_use){
                $education_data_use->start_date = date('d-m-Y', strtotime($education_data_use->start_date));
                $education_data_use->end_date = date('d-m-Y', strtotime($education_data_use->end_date));
            }
        }else{
            $education_data = WorkExperience::where('id',$request->id)->first();
            $education_data->start_date = date('d-m-Y', strtotime($education_data->start_date));
                $education_data->end_date = date('d-m-Y', strtotime($education_data->end_date));
        }
        return $education_data;
    }
    public function delete_documents(Request $request)
    {
        // $user_id=Auth::user()->id;
        // $subcategory_id=$request->subcategory_id;
        // $document=Documents::where('user_id',$user_id)
        // ->where('document_subcategory_id',$subcategory_id);
        $document_id = $request->document_id;
        $document = Documents::where('id', $document_id)->first();
        if (isset($document)) {
            $document_path = $document->get()->toArray()[0]["document_location"];
            $path = Storage::disk('s3')->delete($document_path);
            if ($path) {
                $document->delete();
                return response()->json(['status' => 1]);
            }
        }

        return response()->json(['status' => 0]);
    }

    public function documents_upload(Request $request)
    {       
       
        
            $validator = Validator::make($request->all(), [
                'file' => 'required|mimes:pdf,doc,xlsx,csv,docx,jpeg,jpg,png|max:16000000'
            ]);
        
            if ($validator->fails()) {
                $errors = $validator->errors();
                return response()->json([
                    'error' => $errors,
                    'status' => 3
                ]);
            } 
    
            if ($request->hasFile('file')) {

                // $user_id=Auth::user()->id;
                $user_id = $request->user_id;
                // $subcategory=DocumentSubcategory::find($request->document_subcategory_id)->toArray()['document_subcategory_name'];
                // $subcategory=str_replace("'"," ",$subcategory);
                // $subcategory=explode(' ', $subcategory);
                // $subcategory=implode('_', $subcategory);
    
                $subcategory = $request->subcategory_name;
    
                $file = $request->file('file');
                $target_dir = "https://gradding.s3.ap-south-1.amazonaws.com/";
                $file_type = strtolower($file->getClientOriginalExtension());
    
                $filename = $subcategory . "_" . time() . "." . $file_type;
                $user_dir = "candidate/documents/" . $user_id . "/";
    
                $document_name = $request->document_name;
    
                $file_path = $user_dir . $filename;
                $path = Storage::disk('s3')->put($file_path,  fopen($file, 'r+')); //stores file
    
    
                if ($path) {
                    $document = new Documents;
                    $document->user_id = $user_id;
                    ($request->document_subcategory_id != null || $request->document_subcategory_id != "") ?
                        ($document->document_subcategory_id = $request->document_subcategory_id) : ($document->document_name = $document_name);
                    $document->document_location = $user_dir . $filename;
                    $document->document_size = $file->getSize();
                    $document->save();
                    return response()->json(['document_subcategory_id' => $request->document_subcategory_id, 'status' => 1, "massage" => "document successfully Uploaded"]);
                }
                else{
                    return response()->json(['document_subcategory_id' => $request->document_subcategory_id, 'status' => 0, "massage" => "Something Wrong Please Try Again"]);
                }
            }else{
                return response()->json(['document_subcategory_id' => $request->document_subcategory_id, 'status' => 2, "massage" => "Attach Document File"]);
            }
            
    
    }

    public function get_documents(Request $request)
    {   
        $doc_category = DocumentCategory::get();
        $doc_sub_category = DocumentSubcategory::get();
        $document = Documents::where('user_id',$request->user_id)->get();
        $document_link = Storage::disk('s3')->url('/');
        $document_link = substr($document_link, 0, -1);

       
        $data = compact(['document', 'document_link','doc_category','doc_sub_category']);
        return response()->json(['data' => $data]);
    }


    public function profile_complete($candidate_id){

        $candidate = Candidate::where('id',$candidate_id)->first();
        $user = User::findOrFail($candidate->user_id);
       
        
        $null_fields = 0;
        $Available_fields = 0;
        $Available_mandatary = 0;
        $null_mandatary = 0;
        $fields = [
            'name' => $user->name,
            'phone' => $user->phone,
            'email' => $user->email,
            'birth_date' => $candidate->birth_date,
            'country_id' => $candidate->country_id,
            'state_id' => $candidate->state_id,
            'city_id' => $candidate->city_id,
            'address' => $candidate->address,
            'budget' => $candidate->budget,
            'fund_source' => $candidate->fund_source,
            'preferred_country' => @$candidate->destination[0]->preferred_country,
            'preferred_program' => @$candidate->destination[0]->preferred_program,
            'preffered_stream' => @$candidate->destination[0]->preffered_stream,
        ];

        if($candidate->visa_refusal == 1){
            $fields['visa_refusal'] = $candidate->visa_refusal;
            $fields['visa_refusal_reason'] = $candidate->visa_refusal_reason;
        }

        if($candidate->passport_status == 1){
            $fields['passport_expiry'] = $candidate->passport_expiry;
            $fields['passport_number'] = $candidate->passport_number;
        }

        if($candidate->marital_status == 1){
            $fields['marital_status'] = $candidate->marital_status;
            if($candidate->spouse_comming == 1){
                $fields['spouse_comming'] = $candidate->spouse_comming;
                $fields['spouse_qualification'] = $candidate->spouse_qualification;
                $fields['spouse_employment_status'] = $candidate->spouse_employment_status;
                $fields['spouse_income'] = $candidate->spouse_income;
                $fields['kids_count'] = $candidate->kids_count;
                $fields['accompanying_applicant'] = $candidate->accompanying_applicant;
                $fields['comment'] = $candidate->comment;
            }
        }
	 
        // dd($fields);

        $mandatoryFields = ['name', 'phone', 'email', 'birth_date', 'gender', 'passport_number', 'passport_expiry', 'country_id', 'state_id', 'city_id', 'visa_refusal', 'marital_status', ];
        
        foreach ($fields as $field => $value) {
            if ($value != "" && $value != null) {
                $Available_fields++;
                if (in_array($field, $mandatoryFields)) {
                    $Available_mandatary++;
                }
            } else {
                $null_fields++;
                if (in_array($field, $mandatoryFields)) {
                    $null_mandatary++;
                }
            }
        }

        $personal_info = $Available_fields+$null_fields;
        $personal_info_available = $Available_fields;
        if($null_mandatary > 0){
            $personal_info_mandatary = 1;
        }else{
            $personal_info_mandatary = 0;
        }
        $personal_info_available_percentage = ($Available_fields/$personal_info)*100;


        $null_fields = 0;
        $Available_fields = 0;
        $Available_mandatary = 0;
        $null_mandatary = 0;
        
        if(isset($candidate->destination[0])){
            if($candidate->destination[0]['preferred_country'] != "" && $candidate->destination[0]['preferred_country'] !=null){
                $Available_fields++;
                $Available_mandatary++;
            }else{
                $null_fields++;
                $null_mandatary++;
            }
            if($candidate->destination[0]['intake_years'] != "" && $candidate->destination[0]['intake_years'] !=null){
                $Available_fields++;
                $Available_mandatary++;
            }else{
                $null_fields++;
                $null_mandatary++;
            }
            if($candidate->destination[0]->intake_months != "" && $candidate->destination[0]->intake_months !=null){
                $Available_fields++;
                $Available_mandatary++;
            }else{
                $null_fields++;
                $null_mandatary++;
            }
            if($candidate->destination[0]->preferred_program != "" && $candidate->destination[0]->preferred_program !=null){
                $Available_fields++;
                
            }else{
                $null_fields++;
               
            }
            if($candidate->destination[0]->preffered_stream != "" && $candidate->destination[0]->preffered_stream !=null){
                $Available_fields++;
                
            }else{
                $null_fields++;
               
            }
        }else{
            $Available_fields = 0;
            $null_fields = 4;
            $null_mandatary = 4;
            $Available_mandatary = 0;
        }
        
        
        $study_abroad_info = $Available_fields+$null_fields;
        $study_abroad_info_available = $Available_fields;
        if($null_mandatary > 0){
            $study_abroad_info_mandatary = 1;
        }else{
            $study_abroad_info_mandatary = 0;
        }
        $study_abroad_info_available_percentage = ($Available_fields/$study_abroad_info)*100;
        

        $null_fields = 0;
        $Available_fields = 0;
        $Available_mandatary = 0;
        $null_mandatary = 0;
        
        
        if($candidate->budget != "" && $candidate->budget !=null){
            $Available_fields++;
          
        }else{
            $null_fields++;
            
        }
        if($candidate->fund_source != "" && $candidate->fund_source !=null){
            $Available_fields++;
            
        }else{
            $null_fields++;
            
        }
        if($candidate->loan_type != "" && $candidate->loan_type !=null){
            $Available_fields++;
           
        }else{
            $null_fields++;
            
        }
        
        $budget_info = $Available_fields+$null_fields;
        $budget_info_available = $Available_fields;
        if($null_mandatary > 0){
            $budget_info_mandatary = 1;
        }else{
            $budget_info_mandatary = 0;
        }
        $budget_info_available_percentage = ($Available_fields/$budget_info)*100;




        $null_fields = 0;
        $Available_fields = 0;
        $Available_mandatary = 0;
        $null_mandatary = 0;
        $english_test = [
            'test_name' => '',
            'test_taken_date' => '',
            'test_result_date' => '',
            'test_scores' => '',
        ];
        $abroad_test = [
            'test_name' => '',
            'test_taken_date' => '',
            'test_result_date' => '',
            'test_scores' => '',
        ];
        
        foreach ($candidate->candidate_exam as $index => $exam){

            
            if ($exam->test_type == 'Study Abroad Test'){
                
                $abroad_test = [
                    'test_name' => $exam->test_name,
                    'test_taken_date' => $exam->test_taken_date,
                    'test_result_date' => $exam->test_result_date,
                    'test_scores' => $exam->test_scores,
                ];
            }
            else if($exam->test_type == 'English Proficiency'){
               
                $english_test = [
                    'test_name' => $exam->test_name,
                    'test_taken_date' => $exam->test_taken_date,
                    'test_result_date' => $exam->test_result_date,
                    'test_scores' => $exam->test_scores,
                ];
            }
            
        }
    
        if($english_test['test_name'] != "" && $english_test['test_name'] !=null){
            $Available_fields++;
            $Available_mandatary++;
          
        }else{
            $null_fields++;
            $null_mandatary++;
            
        }
        if($english_test['test_taken_date'] != "" && $english_test['test_taken_date'] !=null){
            $Available_fields++;
            $Available_mandatary++;
            
        }else{
            $null_fields++;
            $null_mandatary++;
        }
        if(@$english_test['test_result_date'] != "" && @$english_test['test_result_date'] !=null){
            $Available_fields++;
            $Available_mandatary++;
           
        }else{
            $null_fields++;
            $null_mandatary++;
            
        }

        if($english_test['test_scores'] != "" && $english_test['test_scores'] !=null){
            $Available_fields++;
            $Available_mandatary++;
           
        }else{
            $null_fields++;
            $null_mandatary++;
            
        }


        if($abroad_test['test_name'] != "" && $abroad_test['test_name'] !=null){
            $Available_fields++;
            $Available_mandatary++;
           
        }else{
            $null_fields++;
            $null_mandatary++;
        }

        if($abroad_test['test_taken_date'] != "" && $abroad_test['test_taken_date'] !=null){
            $Available_fields++;
            $Available_mandatary++;
           
        }else{
            $null_fields++;
            $null_mandatary++;
            
        }
        if($abroad_test['test_result_date'] != "" && $abroad_test['test_result_date'] !=null){
            $Available_fields++;
            $Available_mandatary++;
           
        }else{
            $null_fields++;
            $null_mandatary++;
            
        }

        if($abroad_test['test_scores'] != "" && $abroad_test['test_scores'] !=null){
            $Available_fields++;
            $Available_mandatary++;
           
        }else{
            $null_fields++;
            $null_mandatary++;
            
        }
        
        
        
        $test_score_info = $Available_fields+$null_fields;
        $test_score_info_available = $Available_fields;
        if($null_mandatary > 0){
            $test_score_info_mandatary = 1;
        }else{
            $test_score_info_mandatary = 0;
        }
        $test_score_info_available_percentage = ($Available_fields/$test_score_info)*100;


        $null_fields = 0;
        $Available_fields = 0;
        $Available_mandatary = 0;
        $null_mandatary = 0;
        

        // $doc_category = DocumentCategory::get();
        // $doc_sub_category = DocumentSubcategory::get();
        
        // $document_link = Storage::disk('s3')->url('/');
        // $document_link = substr($document_link, 0, -1);

        // $massage = "";
        // foreach($doc_sub_category as $doc_sub_category_use){
        //     $flag = 0;
        //     foreach($document as $document_use){
        //         if($document_use->document_subcategory_id ==  $doc_sub_category_use->document_category_id){
        //             $Available_fields++;
        //             $flag = 1;
                    
        //         }
        //     }

        //     if($flag == 0 ){
        //         if($doc_sub_category_use->document_category_id == 21 || $doc_sub_category_use->document_category_id == 37 || $doc_sub_category_use->document_category_id == 12 || $doc_sub_category_use->document_category_id == 8 || $doc_sub_category_use->document_category_id == 10 || $doc_sub_category_use->document_category_id == 11 || $doc_sub_category_use->document_category_id == 24 || $doc_sub_category_use->document_category_id == 33 || $doc_sub_category_use->document_category_id == 1 ){
        //             $null_mandatary++;
        //             $massage = $massage. " Please Upload " .$doc_sub_category_use->document_subcategory_name.",";
        //         }
        //         $null_fields++;
        //     }
        // }
        

        // $document_info = $Available_fields+$null_fields;
        // $document_info_available = $Available_fields;
        // if($null_mandatary > 0){
        //     $document_info_mandatary = 1;
        // }else{
        //     $document_info_mandatary = 0;
        // }
        // $document_info_available_percentage = ($Available_fields/$budget_info)*100;


        // $total_fields = $study_abroad_info+$personal_info+$test_score_info+$document_info;
        // $total_available_fields = $study_abroad_info_available+$test_score_info_available+$personal_info_available+$document_info_available;

        $total_fields = $study_abroad_info+$personal_info+$test_score_info;
        $total_available_fields = $study_abroad_info_available+$test_score_info_available+$personal_info_available;
        
        $available_percentage = ($total_available_fields/$total_fields)*100;
        $profile_progress = [];
        $profile_progress['available_percentage'] = round($available_percentage);
        $profile_progress['personal_info_mandatary'] = $personal_info_mandatary;
        $profile_progress['study_abroad_info_mandatary'] = $study_abroad_info_mandatary;
        $profile_progress['budget_info_mandatary'] = $budget_info_mandatary;
        $profile_progress['test_score_info_mandatary'] = $test_score_info_mandatary;
        
        $profile_lock = $candidate->lock_profile;

        $data = [
            'profile_complete' => $profile_progress['available_percentage'],
        ];

        if($profile_progress['available_percentage'] == 100.0){
            if($profile_lock == null){
                $current_date = date('Y-m-d');
                $after_seven_days = date('Y-m-d', strtotime($current_date . ' + 7 days'));
                $data['lock_profile'] = $after_seven_days;          
            }
        }

        Candidate::where('id',$candidate_id)->update($data);
        return $profile_progress;
    }

    
}
