<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Candidate;
use App\Models\Course;
use App\Models\CandidateDestination;
use App\Models\Countries;
use App\Models\State;
use App\Models\City;
use App\Models\CandidateEducation;
use App\Models\CandidateExam;
use App\Models\OnboardCategory;
use App\Models\IndianUniversity;
use Auth;
use JWTAuth;
use Validator;
use Mail;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use App\Models\Documents;

class LoginController extends Controller
{

    public function login(Request $request)
    {
        $user = null;
        if (isset($request->email)) {
            $validator = Validator::make($request->all(), [
                'email' => ['required', 'email','exists:users,email'],
                'password' => ['required'],
            ]);
        } else {
            $validator = Validator::make($request->all(), [
                'country_code'=>['required'],
                'phone' => ['required','integer','exists:users,phone'],
                'password' => ['required'],

            ]);
        }
        if ($validator->fails()) {
            $response = [
                'message' => $validator->errors(),
                'status' => 0
            ];
            $response_code = 403;
        } else {
            try {
                // dd(JWTAuth::user());
                // if(!$token=auth('api')->attempt($validator->validated())){
                if (!$token = JWTAuth::attempt($validator->validated())) {
                    $response = [
                        'message' => "Invalid Username or Password",
                        'status' => 0
                    ];
                    $response_code = 401;
                } else {
                    if(isset($request->email)){
                        $data = $request->email;
                        $condition = 'email';
                    }else if(isset($request->phone)){
                        $data = $request->phone;
                        $condition = 'phone';
                    }
                    $credentials=$validator->validated();
                    @$user = User::where($condition, $data)->first();
                    $user_id = $user->id;
                    $credentials=base64_encode(serialize($credentials));//array to string 
                    $web_token=Crypt::encryptString($credentials);
                    $lastActivityUser = User::FindOrFail($user_id);
                    $lastActivityUser->update([  
                        'last_activity_date' =>  Carbon::now(),
                    ]);
                    $user_id = Crypt::encryptString($user_id);
                    $response = [
                        'token' => $token,
                        'expires_in' => JWTAuth::factory()->getTTL() * 60,
                        'message' => "Login Successful",
                        'web_token'=>$web_token,
                        'user' => $user_id,
                        'status' => 1,
                    ];
                    $response_code = 200;
                }
            } catch (JWTException $e) {
                // catch (\Exception $e) {
                $response = [
                    'message' => $e->getMessage(),
                    'status' => 0
                ];
                $response_code = 500;
            }
        }
        return response()->json($response, $response_code);
    }

    public function logout()
    {
        //Request is validated, do logout        
        try {
            $token = JWTAuth::getToken();
            JWTAuth::invalidate($token);
            $response = [
                'message' => "User has been logged out",
                'status' => 1,                
            ];
            $response_code = 200;
        } catch (JWTException $exception) {
            $response = [
                'message' => $e->getMessage(),
                'status' => 0
            ];
            $response_code = 404;
        }

        return response()->json($response, $response_code);
    }

    public function change_password(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'current_password' => 'required|string',
            'new_password' => 'required|min:8|string|different:current_password',
            'confirm_new_password' => 'required|min:8|same:new_password'
        ]);
        try {
            $saved_password = JWTAuth::user()->password;
        } catch (\Exception $e) {
            $response = [
                'message' => $e->getMessage(),
                'status' => 0
            ];
            $response_code = 500;
            return response()->json($response, $response_code);
        }

        if ($validator->fails()) {
            $response = [
                'message' => $validator->errors(),
                'status' => 0
            ];
            $response_code = 403;
        } elseif (!Hash::check($request->current_password, $saved_password)) {
            $response = [
                'message' => 'Provided current password is Incorrect.',
                'status' => 0
            ];
            $response_code = 403;
        } else {
            DB::beginTransaction();
            try {
                $user = JWTAuth::user();
                // $old=JWTAuth::user()->password;
                $user->password = Hash::make($request->new_password);
                // $new=JWTAuth::user()->password;
                $user->save();
                DB::commit();
                $response = [
                    // 'old'=>$old,
                    // 'new'=>$new,
                    'message' => "Password Successfully Changed",
                    'status' => 1
                ];
                $response_code = 200;
            } catch (\Exception $e) {
                DB::rollback();
                $response = [
                    'message' => $e->getMessage(),
                    'status' => 0
                ];
                $response_code = 500;
            }
        }
        return response()->json($response, $response_code);
    }

    public function get_states($country_id) {
        try {
            $states = State::where("country_id", $country_id)->orderBy('name', 'asc')->get(['id','name']);
            $response = [
                'message' => 'Success',
                'status' => 1,
                'states' => $states
            ];
            $response_code = 200;
        } catch (\Exception $e) {
            $response = [
                'message' => $e->getMessage(),
                'status' => 0
            ];
            $response_code = 500;
        }
        return response()->json($response, $response_code);
    }

    public function get_cities($state_id){
        try {
            $cities = City::where("state_id", $state_id)->orderBy('name', 'asc')->get(['id','name']);
            $response = [
                'message' => 'Success',
                'status' => 1,
                'cities' => $cities
            ];
            $response_code = 200;
        } catch (\Exception $e) {
            $response = [
                'message' => $e->getMessage(),
                'status' => 0
            ];
            $response_code = 500;
        }
        return response()->json($response, $response_code);
    }

    public function delete_education($education_id){
        DB::beginTransaction();
        try {
            $candidate_education = CandidateEducation::where('id', $education_id)->first();
            $candidate_id = $candidate_education->candidate_id;
            $candidate_education->delete();
            DB::commit();
            $educations=CandidateEducation::where('candidate_id',$candidate_id)->get(['id','qualification','year','passing_year','education_board','grade_percentage','grade_type','medium','stream','degree','institute_name']);
            $response = [
                'message' => 'Successfully Deleted',
                'status' => 1,
                'educations'=>$educations
            ];
            $response_code = 200;
        } catch (\Exception $e) {
            DB::rollback();
            $response = [
                'message' => $e->getMessage(),
                'status' => 0
            ];
            $response_code = 500;
        }
        return response()->json($response, $response_code);
    }
    
    //$education_boards=array("Indian Board of School Education", "Indian Board of Computer Education", "J&K State Board of School Education", "Jharkhand Academic Council", "Karnataka Board of the Pre-University Education", "Karnataka Secondary Education Examination Board", "Kerala Board of Public Examinations", "Maharashtra State Board of Secondary and Higher Secondary Education", "Andhra Pradesh Board of Intermediate Education", "Andhra Pradesh Board of Secondary Education", "Board of Higher Secondary Education, New Delhi", "Assam Board of Secondary Education", "Bihar School Examination Board", "Board of School Education, Haryana", "Board of Secondary Education, Madhya Pradesh", "Board of Secondary Education Madhya Bharat Gwalior", "Board of Secondary Education, Rajasthan", "Chhattisgarh Board of Secondary Education", "Central Board of Secondary Education", "Central Board Of Patna, Bihar", "Central Board Of Education Ajmer New Delhi", "Goa Board of Secondary & Higher Secondary Education", "Gujarat Secondary Education Board", "Himachal Pradesh Board of School Education", "Manipur Board of Secondary Education", "Manipur Council of Higher Secondary Education", "Meghalaya Board of School Education", "Mizoram Board of School Education", "Nagaland Board of School Education", "National Institute of Open Schooling", "Orissa Board of Secondary Education", "Orissa Council of Higher Secondary Education", "Punjab School Education Board", "Board of lntermediate Education, Andhra Pradesh,Vidya Bhawan, Nampally, Hyderabad-500001.", "Assam Higher Secondary Education Council, G.N.B. Board, Ambari, Guwahati-781014.", "Bihar Intermediate Education Council, Amrapali Bhawan, Barley Road, Patna-800005.", "Central Board of Secondary Education (Shiksha Kendra), 2, Community Centre, C.B.S.E. Preet Vihar, Delhi - 110092.", "Council for the India School Certificate Examination. Pragati House, 3'd Floor, 47-48 Nehru Place, I.C.S.E., New Delhi110019.", "Goa Board of Secondary and Higher Secondary Education, Alto Betim, Bardez, Goa- 403521.", "Gujrat Secondary Education Board, Sector- 10-6, Near Old Sachivalaya, Gandhinagar- 382010.", "Board of School Education, Bhiwani, Haryana.", "Himachal Pradesh Board of School Education, Dharmasala- 17621.6.", "The Jammu & Kaslunir State Board of School Education, Lal Mandi, Srinagar-190005 (Summer), Behari Colony,Jammu- 180005 (Winter).", "Board ofPre-University Education, Kamataka, Palace Road, Bangalore-550001.", "Maharastra State Board of Secondary and Higher Secondary Education, Shivaji Nagar, Pune- 411010.", "Madhyamik Shiksha Monda!, Madhya Pradesh, Bhopal.", "Board of Secondary Education, Manipur, Imphal-7950001.", "Council of Higher Secondary Education, Orissa, Kedar Gouri Road, Bhubaneswar-751002.", "Rajasthan Madhyamik Shiksha Board, Ajmer-305001.", "Punjab School Education Board, S.A.S. Nagar (Ropar).", "Board of Higher Secondary Eduation Tamilnadu, Depmiment of Govt. Exams, College Road, Chennai- 600006.", "Tripura Board of Secondary Education, P.O. - Abhayanagar, Agartala- 799005.", "Board ofHigh School & Intermediate Education, Uttar Pradesh, Allhabad- 211001.", "National Open School, 39, Community Centre, W.I.A. Ashok Vihar Road, Delhi-11", "West Bengal Board of Madrasah Examination.", "Rabindra Mukto Vidyalaya, West Bengal.", "West Bengal State Council of Vocational Education & Training, Kolkata.", "Jharkhand Academic Council- Jharkhand Board of Secondary Education", "Bihar School Examination Board.", "Central Board of Secondary Education in India (CBSE), 23, Ashiana Apartments, Pitampur, Delhi- 110034.", "Board of lntermediate Education, Andhra Pradesh,Vidya Bhawan, Nampally, Hyderabad-500001.", "Assam Higher Secondary Education Council, G.N.B. Board, Ambari, Guwahati-781014.", "Bihar Intermediate Education Council, Amrapali Bhawan, Barley Road, Patna-800005.", "Central Board of Secondary Education (Shiksha Kendra), 2, Community Centre, C.B.S.E. Preet Vihar, Delhi - 110092.", "Council for the India School Certificate Examination. Pragati House, 3'd Floor, 47-48 Nehru Place, I.C.S.E., New Delhi110019.", "Goa Board of Secondary and Higher Secondary Education, Alto Betim, Bardez, Goa- 403521.", "Gujrat Secondary Education Board, Sector- 10-6, Near Old Sachivalaya, Gandhinagar- 382010.", "Board of School Education, Bhiwani, Haryana.", "Himachal Pradesh Board of School Education, Dharmasala- 17621.6.", "The Jammu & Kashmir State Board of School Education, Lal Mandi, Srinagar-190005(Summer), Behari Colony,Jammu- 180005 (Winter).", "Board of Pre-University Education, Karnataka, Palace Road, Bangalore-550001.", "Board of Secondary Education, Manipur, Imphal-79500 1.", "Council ofHigher Secondary Education, Orissa, Kedar Gouri Road, Bhubaneswar-751002.", "Rajasthan Madhyamik Shiksha Board, Ajmer-305001.", "Punjab School Education Board, S.A.S. Nagar (Ropar).", "Board of Higher Secondary Eduation Tamilnadu, Depmiment of Govt. Exams, College Road, Chennai- 600006.", "Tripura Board of Secondary Education, P.O. - Abhayanagar, Agartala- 799005.", "Board ofHigh School & Intermediate Education, Uttar Pradesh, Allhabad- 211001.", "National Open School, 39, Community Centre, W.I.A. Ashok Vihar Road, Delhi-11 0052.", "West Bengal Board ofMadrasah Examination.", "Rabindra Mukto Vidyalaya, West Bengal.", "West Bengal State Council of Vocational Education & Training, Kolkata.", "Jharkhand Academic Council, Jharkhand.", "Andhra Pradesh Board of Intermediate Education, Hyderabad", "Andhra Pradesh Board of Secondary Education, Hyderabad", "Andhra Pradesh Open School Society, SCERT Campus, Hyderabad", "Assam Higher Secondary Education Council, Bamunimaidan, Guwahati", "Assam Board of Secondary Education, Guwahati", "Bihar Intermediate Education Council, Patna", "Bihar School Examination Board, Patna", "Bihar Sanskrit Shiksha Board, Patna", "Chhatisgarh Board of Secondary Education, Raipur", "Goa Board of Secondary & Higher Secondary Education, Goa", "Gujarat Secondary & Higher Secondary Education Board, Gandhi Nagar", "Haryana Board of Education, Hansi Road, Bhiwani", "Haryana Open School, Bhiwani", "Himachal Pradesh Board of School Education, Dharamshala", "J&K State Board of School Education, Jammu", "J&K State Open School, Srinagar", "Jharkhand Academic Council, Ranchi", "Karnataka Board of the Pre-University Education, Bangalore", "Karnataka Secondary Education Examination Borad, Bangalore", "Karnataka Open School, J.S.S. Maha Vidya Peeth, Mysore", "Kerala Board of Public Examinations, Pareeksha Bhawan, Thiruvananthpuram", "Kerala Board of Higher Secondary Education, Thiruvananthapuram", "Kerala State Open School, Thiruvananthapuram", "Maharashtra State Board of Secondary and Higher Secondary Education, Pune", "Madhya Pradesh Board of Secondary Education, Bhopal", "M.P. State Open School, Bhopal", "Manipur Council of Higher Secondary Education, Imphal", "Manipur Board of Secondary Education, Imphal", "Meghalaya Board of School Education, Meghalaya", "Mizoram Board of School Education Chaltlan, Aizawl", "Nagaland Board of School Education, Kohima", "Orissa Council of Higher Secondary Education Bhubaneswar", "Orissa Board of Secondary Education, Cuttack", "Punjab School Education Board, Mohali", "Rajasthan Board of Secondary Education, Ajmer", "Rajasthan State Open School, Jaipur", "Tamil Nadu Board of Secondary Education, Chennai", "Tamil Nadu Board of Higher Secondary Education, Chennai", "Tripura Board of Secondary Education, Agartala, Tripura West", "U.P. Board of High School & Intermediate Education, Allahabad", "Uttranchal Shiksha Evm Pariksha Parishad, Ram Nagar, Nanital", "West Bengal Board of Secondary Education, Calcutta", "West Bengal Council of Higher Secondary Education, Calcutta", "West Bengal Council for Rabindra Open Schooling", "West Bengal Board of Madrasa Education", "National Institute of Open Schooling (formarly National Open School), New Delhi", "Central Board of Secondary Education, Delhi", "Council for Indian School Certificate Examinations, New Delhi", "Rashtriya Sanskrit Sansthan, New Delhi.", "Gurukul Kangri Vishwavidyalaya, Haridwar,", "Directorate of Army Education, New Delhi.", "Aligarh Muslim University, Aligarh.", "Jamia Miliya Hamdard University.", "Banasthali Vidyapith, Banasthali, Rajasthan", "Jamia Miliya Islamia, New Delhi.", "IGCSE Programme from University of Cambridge (International Exam)", "Any recognised Board of foreign countries", "Maharastra State Board of Secondary and Higher Secondary Education, Shivaji Nagar, Pune-411010.", "Madhyamik Shiksha Monda!, Madhya Pradesh, Bhopal.", "Rajasthan Board of Secondary Education", "Tamil Nadu Board of Higher Secondary Education", "Tamil Nadu Board of Secondary Education", "Tripura Board of Secondary Education", "Telangana State Board of Intermediate Education", "Uttar Pradesh Board of High School and Intermediate Education", "Sampurnanand Sanskrit Vishwavidyalaya Varanasi Uttar Pradesh", "Uttarakhand Board of School Education", "West Bengal Board of Secondary Education", "West Bengal Council of Higher Secondary Education", "West Bengal State Council of Vocational Education and Training", "Board of Secondary Education Kant Shahjahanpur Uttar Pradesh", "The West Bengal Council of Rabindra Open Schooling");
    // $onboard_categories = OnboardCategory::with('onboardQuestions')->get(['id', 'category_name']);
    //$preferred_years=[date("Y"),strval(date("Y")+1),strval(date("Y")+2)];
    public function get_onboard()
    {
        try {
            
            $courses=Course::get(['id','name']);
            $user = JWTAuth::user()->only(['id','name','last_name','phone', 'email', 'country_code','alt_iso2','alternate_phone','secondary_email']);
            $lastActivityUser = User::FindOrFail($user['id']);
            $lastActivityUser->update([  
                'last_activity_date' =>  Carbon::now(),
            ]);
            $countries = Countries::orderBy('name', 'asc')->get(['id','name']);
            (!$candidate = Candidate::firstWhere('user_id', $user['id'])) ? $candidate = new Candidate() : "" ;
            ($candidate->user_id == null)?$candidate->user_id = $user_id : "";
            $personal_details=$candidate->where('user_id',$user['id'])->get(['country_id', 'state_id','city_id','passport_number','passport_expiry','visa_refusal','birth_date','gender','budget','fund_source','loan_type'])->first();
            $education_boards = [ "Andhra Pradesh Board of Secondary Education", "Arunachal Pradesh State Board of School Education", "Assam Higher Secondary Education Council", "Bihar School Examination Board", "Central Board of Secondary Education (CBSE)", "Chhattisgarh Board of Secondary Education", "Council for the Indian School Certificate Examinations (CISCE)", "Goa Board of Secondary & Higher Secondary Education", "Gujarat Secondary and Higher Secondary Education Board", "Haryana Board of School Education", "Himachal Pradesh Board of School Education","Indian Certificate of Secondary Education (ICSE)", "Jammu & Kashmir State Board of School Education", "Jharkhand Academic Council", "Karnataka Secondary Education Examination Board", "Kerala State Board of Education", "Madhya Pradesh Board of Secondary Education", "Maharashtra State Board of Secondary & Higher Secondary Education", "Manipur State Board of Examination", "Meghalaya Board of School Education", "Mizoram Board of School Education", "Nagaland Board of School Education", "National Institute of Open Schooling (NIOS)", "Odisha Board of Secondary Education", "Punjab School Education Board", "Rajasthan Board of Secondary Education", "Sikkim Board of School Education", "Tamil Nadu State Board of Examination", "Telangana State Board of Intermediate Education", "Tripura Board of Secondary Education", "Uttar Pradesh Board of High School and Intermediate Education", "Uttarakhand Board of School Education", "West Bengal Board of Secondary Education", ];
            $ind_universities = IndianUniversity::orderBy('name', 'asc')->get(['id', 'name']);
            ($candidate = Candidate::firstWhere('user_id', $user['id'])) ? 
            ($educations=CandidateEducation::where('candidate_id',$candidate->id)->get(['id','qualification','year','passing_year','education_board','grade_percentage','grade_type','medium','stream','degree','institute_name'])) .
            ($destination=CandidateDestination::where('candidate_id',$candidate->id)->get(['preferred_course','preferred_country','applied_university_name','consultant_name','intake'])).
            ($tests=CandidateExam::where('candidate_id',$candidate->id)->get(['id','test_type','test_name','test_scores','test_taken_date','test_result_date'])):
            ($educations=null).($destination=null).($tests=null);
            
         
            $response = [
                'status' => 1,
                'message' => "Success",
                'user' => $user,
                'courses'=>$courses,
                'education_boards'=>$education_boards,
                'countries'=> $countries,
                'ind_universities'=>$ind_universities,
                'personal_details'=>$personal_details,
                'educations'=>$educations,
                'destination'=>$destination,
                'tests'=>$tests
            ];
            $response_code = 200;
        } catch (\Exception $e) {
            $response = [
                'message' => $e->getMessage(),
                'status' => 0
            ];
            $response_code = 500;
        }
        return response()->json($response, $response_code);
    }

    public function store_onboard(Request $request)
    {
        $category_id = $request->category_id;
        $user_id=Auth::id();
        $lastActivityUser = User::FindOrFail($user_id);
        $lastActivityUser->update([  
            'last_activity_date' =>  Carbon::now(),
        ]);
        if ($category_id == 1) {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|min:2|max:50',
                'last_name' => 'nullable|string|min:2|max:50',
                // 'phone' => 'required|string|max:25',
                // 'country_code' => 'nullable|string|max:250',
                'alternate_phone' => 'nullable|string|max:20',
                'email' => 'required|email',
                'secondary_email' => 'nullable|email|max:50',
                'gender' => 'nullable|string|in:male,female,other',
                'passport_status' => 'required',
                'passport_number' => 'nullable|string|max:50',
                'passport_expiry' => 'nullable|date',
                'birth_date' => 'nullable|date',
                'visa_refusal'=>'nullable|numeric',
                'country_id' => 'nullable|numeric',
                'state_id' => 'nullable|numeric',
                'city_id' => 'nullable|numeric'
            ]);
            if ($validator->fails()) {
                $response = [
                    'message' => $validator->errors(),
                    'status' => 0
                ];
                $response_code = 403;
            } else {
                DB::beginTransaction();
                try {
                    $user_id = JWTAuth::user()->id;

                    $user = User::find($user_id);
                    (JWTAuth::user()->name != $request->name) ? $user->name = $request->name : "";
                    (JWTAuth::user()->last_name != $request->last_name) ? $user->last_name = $request->last_name : "";
                    $user->alternate_phone = $request->alternate_phone;
                    $user->alt_iso2 = $request->alt_iso2;
                    $user->secondary_email = $request->secondary_email;
                    
                    $user->save();

                    (!$candidate = Candidate::firstWhere('user_id', $user_id)) ? $candidate = new Candidate() : "" ;
                    ($candidate->user_id == null)?$candidate->user_id = $user_id : "";

                    (isset($request->gender))?$candidate->gender = $request->gender:"";
                    ($request->passport_status==1)? ($candidate->passport_number = $request->passport_number) . ($candidate->passport_expiry = $request->passport_expiry):($candidate->passport_number = null) . ($candidate->passport_expiry = null);
                    
                    (isset($request->visa_refusal))?$candidate->visa_refusal = $request->visa_refusal:$candidate->visa_refusal =null;
                    (isset($request->birth_date))?$candidate->birth_date = $request->birth_date:"";
                    (isset($request->city_id))?$candidate->city_id = $request->city_id:$candidate->city_id =null;
                    (isset($request->state_id))?$candidate->state_id = $request->state_id:$candidate->state_id=null;
                    (isset($request->country_id))?$candidate->country_id = $request->country_id:$candidate->country_id =null;
                    $candidate->save();

                    DB::commit();
                    $response = [
                        'user_id'=>$user_id ,
                        'message' => "Personal Information Successfully Stored",
                        'status' => 1
                    ];
                    $response_code = 200;
                } catch (\Exception $e) {
                    DB::rollback();
                    $response = [
                        'message' => $e->getMessage(),
                        'status' => 0
                    ];
                    $response_code = 500;
                }
            }
            

        } 
        elseif ($category_id == 2) {
            $validator = Validator::make($request->all(), [
                'qualification' => 'nullable|string|max:120',
                'degree' => 'nullable|string|max:120',
                'admission_year' => 'nullable|string|max:4',
                'passing_year' => 'nullable|string|max:4',
                'stream' => 'nullable|string|max:120',
                'education_board' => 'nullable|string|max:120',
                'institute_name' => 'nullable|string|max:120',
                'grade_percentage' => 'nullable|string|max:10',
                'grade_type' => 'nullable|string',
                'medium' => 'nullable|string|max:50'
            ]);
            if ($validator->fails()) {
                $response = [
                    'message' => $validator->errors(),
                    'status' => 0
                ];
                $response_code = 403;
            } else {
                DB::beginTransaction();
                try {
                    $user_id = JWTAuth::user()->id;
                    (!$candidate = Candidate::firstWhere('user_id', $user_id)) ? $candidate = new Candidate() : "" ;
                    ($candidate->user_id == null)?$candidate->user_id = $user_id : "";
                    $candidate->save();

                    (isset($request->education_id))?($candidate_education = CandidateEducation::firstWhere('id', $request->education_id)): $candidate_education = new CandidateEducation();
                    
                    $candidate_education->candidate_id=$candidate->id;
                    $candidate_education->qualification=$request->input("qualification");

                    // $candidate_education->degree=(isset($request->degree))?$request->input("degree"):"NA";
                    // $candidate_education->stream = isset($request->stream) ? $request->input("stream") : "NA";
                    // $candidate_education->year = isset($request->admission_year) ? $request->input("admission_year") : "NA";
                    // $candidate_education->passing_year = isset($request->passing_year) ? $request->input("passing_year") : "NA";
                    // $candidate_education->institute_name = isset($request->institute_name) ? $request->input("institute_name") : "NA";
                    // $candidate_education->education_board = isset($request->education_board) ? $request->input("education_board") : "NA";
                    // $candidate_education->grade_percentage = isset($request->grade_percentage) ? $request->input("grade_percentage") : "NA";
                    // $candidate_education->grade_type = isset($request->grade_type) ? $request->input("grade_type") : "NA";
                    // $candidate_education->medium = isset($request->medium) ? $request->input("medium") : "NA";

                    $candidate_education->degree=$request->input("degree");
                    $candidate_education->stream=$request->input("stream");
                    $candidate_education->year=$request->input("admission_year");
                    $candidate_education->passing_year=$request->input("passing_year");
                    $candidate_education->institute_name=$request->input("institute_name");
                    $candidate_education->education_board=$request->input("education_board");
                    $candidate_education->grade_percentage=$request->input("grade_percentage");
                    $candidate_education->grade_type=$request->input("grade_type");
                    $candidate_education->medium=$request->input("medium");
                    $candidate_education->save();
                    
                    DB::commit();
                    $educations=CandidateEducation::where('candidate_id',$candidate->id)->get(['id','qualification','year','passing_year','education_board','grade_percentage','grade_type','medium','stream','degree','institute_name']);
                    
                    $response = [
                        'message' => "Education Preferences Successfully Stored",
                        'status' => 1,
                        'educations'=>$educations
                    ];
                    $response_code = 200;
                } catch (\Exception $e) {
                    DB::rollback();
                    $response = [
                        'message' => $e->getMessage(),
                        'status' => 0
                    ];
                    $response_code = 500;
                }
            }
        }elseif ($category_id == 3) {
            $validator = Validator::make($request->all(), [
                'preferred_course' => 'nullable|string|max:250',//array
                'preferred_country' => 'nullable|string|max:80',
                'applied_university_status' => 'nullable',
                'applied_university_name' => 'nullable|string|max:255',
                'consultant_status' => 'nullable',
                'consultant_name' => 'nullable|string|max:100',
                // 'intake_years' => 'nullable',
                'intake' => 'nullable|string|max:255'
            ]);
            if ($validator->fails()) {
                $response = [
                    'message' => $validator->errors(),
                    'status' => 0
                ];
                $response_code = 403;
            } else {
                DB::beginTransaction();
                try {
                    $user_id = JWTAuth::user()->id;
                    (!$candidate = Candidate::firstWhere('user_id', $user_id)) ? $candidate = new Candidate() : "" ;
                    ($candidate->user_id == null)?$candidate->user_id = $user_id : "";
                    $candidate->save();

                    (!$candidate_destination=CandidateDestination::firstWhere('candidate_id', $candidate->id)) ? $candidate_destination= new CandidateDestination() :"";
                    ($candidate_destination->candidate_id == null)?$candidate_destination->candidate_id=$candidate->id:"";
                    
                    $candidate_destination->preferred_course=$request->preferred_course;
                    $candidate_destination->preferred_country=$request->preferred_country;
                    
                    // $candidate_destination->applied_university_status=$request->applied_university_status;
                    (isset($request->applied_university_status) && $request->applied_university_status)?$candidate_destination->applied_university_name=$request->applied_university_name:$candidate_destination->applied_university_name=null;
                    // $candidate_destination->consultant_status=$request->consultant_status;
                    (isset($request->consultant_status) && $request->consultant_status)?$candidate_destination->consultant_name=$request->consultant_name:$candidate_destination->consultant_name=null;
                    $candidate_destination->intake=$request->intake;
                    // $candidate_destination->intake_sessions=$request->intake_sessions;
                    $candidate_destination->save();
                    DB::commit();
                    $response = [
                        'message' => "Study Abroad Preferences Successfully Stored",
                        'status' => 1
                    ];
                    $response_code = 200;
                } catch (\Exception $e) {
                    DB::rollback();
                    $response = [
                        'message' => $e->getMessage(),
                        'status' => 0
                    ];
                    $response_code = 500;
                }
            }
        } elseif ($category_id == 4) {
            $validator = Validator::make($request->all(), [
                'budget' => 'nullable|string|max:4',
                'fund_source' => 'nullable|string|max:100',
                'loan_type' => 'nullable|string|max:100'
            ]);
            if ($validator->fails()) {
                $response = [
                    'message' => $validator->errors(),
                    'status' => 0
                ];
                $response_code = 403;
            } else {
                DB::beginTransaction();
                try {
                    $user_id = JWTAuth::user()->id;
                    (!$candidate = Candidate::firstWhere('user_id', $user_id)) ? $candidate = new Candidate() : "" ;
                    ($candidate->user_id == null)?$candidate->user_id = $user_id : "";
                    $candidate->budget = $request->budget;
                    $candidate->fund_source = $request->fund_source;
                    $candidate->loan_type = $request->loan_type;
                    $candidate->save();
                    
                    DB::commit();
                    $response = [
                        'message' => "Budget Preferences Successfully Stored",
                        'status' => 1
                    ];
                    $response_code = 200;
                } catch (\Exception $e) {
                    DB::rollback();
                    $response = [
                        'message' => $e->getMessage(),
                        'status' => 0
                    ];
                    $response_code = 500;
                }
            }
            
        } elseif ($category_id == 5) {
            $validator = Validator::make($request->all(), [
                'english_test' => 'required|string|max:80',
                'english_taken_date' => 'nullable|date',
                'english_result_date' => 'nullable|date',
                'english_score' => 'nullable|string|max:10',
                
                'aptitude_test' => 'required|string|max:80',
                'aptitude_taken_date' => 'nullable|date',
                'aptitude_result_date' => 'nullable|date',
                'aptitude_score' => 'nullable|string|max:10'
            ]);
            if ($validator->fails()) {
                $response = [
                    'message' => $validator->errors(),
                    'status' => 0
                ];
                $response_code = 403;
            } else {
                DB::beginTransaction();
                try {
                    $user_id = JWTAuth::user()->id;
                    (!$candidate = Candidate::firstWhere('user_id', $user_id)) ? $candidate = new Candidate() : "" ;
                    ($candidate->user_id == null)?$candidate->user_id = $user_id : "";
                    $candidate->save();



                    if(strtolower($request->english_test)!="none"){
                        (!$candidate_exam=CandidateExam::firstWhere('id', $request->english_test_id)) ? $candidate_exam= new CandidateExam() :"";
                        $candidate_exam->candidate_id = $candidate->id;
                        $candidate_exam->test_type = "English Proficiency";
                        $candidate_exam->test_name = $request->english_test;
                        $candidate_exam->test_taken_date = $request->english_taken_date;
                        $candidate_exam->test_result_date = $request->english_result_date;
                        $candidate_exam->test_scores = $request->english_score;
                        $candidate_exam->save();

                        $english_test_id=$candidate_exam->id;

                    }else if($request->english_test_id!=-1){
                        $candidate_exam=CandidateExam::firstWhere('id', $request->english_test_id);
                        $candidate_exam->delete();
                        $english_test_id=-1;
                    }

                    if(strtolower($request->aptitude_test)!="none"){
                        (!$candidate_exam=CandidateExam::firstWhere('id', $request->aptitude_test_id)) ? $candidate_exam= new CandidateExam() :"";
                        $candidate_exam->candidate_id = $candidate->id;
                        $candidate_exam->test_type = "Study Abroad Test";
                        $candidate_exam->test_name = $request->aptitude_test;
                        $candidate_exam->test_taken_date = $request->aptitude_taken_date;
                        $candidate_exam->test_result_date = $request->aptitude_result_date;
                        $candidate_exam->test_scores = $request->aptitude_score;
                        $candidate_exam->save();

                        $aptitude_test_id=$candidate_exam->id;

                    }else if($request->aptitude_test_id!=-1){
                        $candidate_exam=CandidateExam::firstWhere('id', $request->aptitude_test_id);
                        $candidate_exam->delete();
                        $aptitude_test_id=-1;
                    }
                  
                    DB::commit();
                    if(isset($english_test_id) && isset($aptitude_test_id)){
                        $response = [
                            'english_test_id'=>$english_test_id,
                            'aptitude_test_id'=>$aptitude_test_id,
                            'message' => "Test Status Successfully Stored",
                            'status' => 1
                        ]; 
                    } else if(isset($english_test_id)){
                        $response = [
                            'english_test_id'=>$english_test_id,
                            'message' => "Test Status Successfully Stored",
                            'status' => 1
                        ]; 
                    }
                    else if(isset($aptitude_test_id)){
                        $response = [
                            'aptitude_test_id'=>$aptitude_test_id,
                            'message' => "Test Status Successfully Stored",
                            'status' => 1
                        ]; 
                    }else{
                        $response = [
                            'message' => "Test Status Successfully Stored",
                            'status' => 1
                        ]; 
                    }
                    
                    $response_code = 200;
                } catch (\Exception $e) {
                    DB::rollback();
                    $response = [
                        'message' => $e->getMessage(),
                        'status' => 0
                    ];
                    $response_code = 500;
                }
            }
        }
        return response()->json($response, $response_code);
    }

    public function delete_documents($document_id){
        try {
            // $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);
            if(isset($document)){
                $document_path=$document->get()->toArray()[0]["document_location"];
                $path = Storage::disk('s3')->delete($document_path);
                if($path){
                    $document->delete();
                    $response = [
                        'message' => "Document Successfully Deleted",
                        'status' => 1
                    ];
                    $response_code = 200;
                }
            }
        } catch (\Exception $e) {
            DB::rollback();
            $response = [
                'message' => $e->getMessage(),
                'status' => 0
            ];
            $response_code = 500;
        }
        return response()->json($response, $response_code);
        
    }

    public function get_documents(){
        try {
            // $document_categories=DocumentCategory::with('documentSubcategory')->get(['id','document_category_name'])->toArray();
            $subcategories = [
                "school" => [
                    "Class 10 Marksheet" => 37,
                    "Class 12 Marksheet" => 12
                ],
                "degree" => [
                    "Bachelor's Degree Transcripts" => 8,
                    "Master's Degree Transcripts" => 9,
                    "Bachelor's Degree" => 10,
                    "Master's Degree" => 11
                ],
                "additional" => [
                    "LOR 1" => 2,
                    "LOR 2" => 3,
                    "SOP" => 5,
                    "Resume" => 1
                ]
            ];


            $document_link=Storage::disk('s3')->url('/');
            $user_id=JWTAuth::user()->id;
            // $uploaded_documents=User::where('id' , $user_id)->with('documents')->get()->toArray()[0]["documents"];

            $uploaded_documents=Documents::where('user_id' , $user_id)->get(['id','document_subcategory_id','updated_at','document_location','document_name'])->toArray();
            // dd($uploaded_documents);
            // $data=compact(['document_categories','uploaded_documents','document_link']);
            $response = [
                'message' => "Documents Fetched Successfully",
                'status' => 1,
                'subcategories'=>$subcategories,
                'uploaded_documents'=>$uploaded_documents,
                'document_link'=>$document_link
            ];
            $response_code = 200;
        } catch (\Exception $e) {
            DB::rollback();
            $response = [
                'message' => $e->getMessage(),
                'status' => 0
            ];
            $response_code = 500;
        }
        
        return response()->json($response, $response_code);
        
    }

    public function documents_upload(Request $request){
        if ($request->hasFile('file')) {
            $validator = Validator::make($request->all(), [
                "file" => "required|mimes:pdf,jpeg,jpg,png|max:5000000"
            ]);
            if ($validator->fails()) {
                $response = [
                    'message' => $validator->errors(),
                    'status' => 0
                ];
                $response_code = 403;
            } else {
                DB::beginTransaction();
                try {

                    $user_id=JWTAuth::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=str_replace("_"," ",$subcategory);

                    $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();
                        DB::commit();
                        $response = [
                            'message' => "Document Successfully Uploaded",
                            'status' => 1,
                            'document_subcategory_id'=>$request->document_subcategory_id
                        ];
                        $response_code = 200;
                    }
                } catch (\Exception $e) {
                    DB::rollback();
                    $response = [
                        'message' => $e->getMessage(),
                        'status' => 0
                    ];
                    $response_code = 500;
                }
            }
        }else {
            $response = [
                'message' => "No Document to Upload",
                'status' => 0,
            ];
            $response_code = 200;
        }
        return response()->json($response, $response_code);
    }
}




