<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use App\Models\Employer;
use App\Models\Admin;
use App\Models\Job;
use App\Models\Staff;
use App\Models\Skill;
use App\Models\SelectedCandidate;
use App\Models\CandidateJobApply;
use App\Models\CandidateEducation;
use App\Models\CandidateExperience;
use App\Models\Qualification;
use App\Models\OfferDraftData;
use App\Models\Certificate;
use App\Models\GeneralSetting;
use App\Models\Preference;
use Illuminate\Support\Facades\Auth;
use App\Models\Industry;
use Carbon\Carbon;
use Mail;
use App\Models\EmailTemplate;
use App\Mail\SendMail;


class OnboardingController extends Controller
{
    public function getCandidateDetails(Request $request){
        
        $candidateId = $request->candidate_id;
        $employerId = $request->employer_id;
        
        $candidate = SelectedCandidate::where('candidate_id', $candidateId)->first(['onboarding_link_status', 'send_time', 'expire_time']);

        // if (!empty($candidate->onboarding_link_status)) {
        //     if (Carbon::parse($candidate->send_time)->lessThan(Carbon::parse($candidate->expire_time))) {
        //         return Response(['response' => 'The link has been expired', 'message' => 'successful', 'status' => 500], 200);
        //     }
        // }
        
        
        $generalData = GeneralSetting::where('employer_id', $employerId)->first();

        $onboardingExpiry = $generalData->onboarding_expiry; 
        $onboardingExpiryValue = $generalData->onboarding_expiry_value; 
        
        if (!empty($candidate->onboarding_link_status)) {
            $currentTime = Carbon::now();
        
            if ($onboardingExpiry === 'minutes') {
                $expirationTime = Carbon::parse($candidate->send_time)->addMinutes($onboardingExpiryValue);
            } elseif ($onboardingExpiry === 'hours') {
                $expirationTime = Carbon::parse($candidate->send_time)->addHours($onboardingExpiryValue);
            } else {
                return Response(['response' => 'Invalid expiry setting', 'message' => 'error', 'status' => 500], 200);
            }
        
            if ($currentTime->greaterThan($expirationTime)) {
                return Response(['response' => 'The link has expired', 'message' => 'success', 'status' => 500], 200);
            }
        }
        
        
        
        
        
        
        // if (!empty($candidate->onboarding_link_status)) {
        //     $currentTime = Carbon::now();
        //     if ($currentTime->greaterThan(Carbon::parse($candidate->expire_time))) {
        //         return Response(['response' => 'The link has been expired', 'message' => 'successful', 'status' => 500], 200);
        //     }
        // }

        
        
        $candidateDetails = CandidateJobApply::where('id',$candidateId)->first();
        $candidateData = array();
        
        $candidateData['candidate_id'] = $candidateDetails->id;
        $candidateData['job_id'] = $candidateDetails->job_form_id;
        $candidateData['first_name'] = $candidateDetails->first_name;
        $candidateData['last_name'] = $candidateDetails->last_name;
        $candidateData['email'] = $candidateDetails->email;
        $candidateData['phone'] = $candidateDetails->contact_number;
        $candidateData['address'] = $candidateDetails->address;
        $candidateData['gender'] = $candidateDetails->gender;
        $candidateData['dateofbirth'] = $candidateDetails->date_of_birth;
        $candidateData['martialstatus'] = $candidateDetails->martial_status;
        $candidateData['physical_challenged'] = $candidateDetails->physical_challenge;
        $candidateData['created'] = format_date($candidateDetails->created);
        $candidateData['status'] = $candidateDetails->status;
        $candidateData['interview_status'] = $candidateDetails->interview_status;
        $candidateData['interviewDetails'] = getFeedbackData($candidateDetails->id);
        $candidateData['jobAppliedFor'] = Job::where('id',$candidateDetails->job_form_id)->value('title');
        
        return Response(['response' => $candidateData, 'message' => "", 'status' => 200],200);
    }
    
    public function savePersonalDetails(Request $request) {
        $candidateId = $request->candidate_id;
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'date_of_birth' => 'required',
            'fathers_name' => 'required',
            'mothers_name' => 'required',
            'fathers_occupation' => 'required',
            'mothers_occupation' => 'required',
            'gender' => 'required',
            'marital_status' => 'required',
            'physically_challenged' => 'required',
            'current_address' => 'required',
            'permanent_address' => 'required',
            'email_address' => 'required',
            'phone_number' => 'required'
        ]);
        $validator->setAttributeNames([
            'name' => 'Name',
            'date_of_birth' => 'Date of birth',
            'fathers_name' => 'Fathers Name',
            'mothers_name' => 'Mothers Name',
            'fathers_occupation' => 'Occupation of father',
            'mothers_occupation' => 'Occupation of mother',
            'gender' => 'Gender',
            'marital_status' => 'Marital Status',
            'physically_challenged' => 'Physically Challenged',
            'current_address' => 'Current Address',
            'permanent_address' => 'Permanent Address',
            'email_address' => 'Email Address',
            'phone_number' => 'Phone Number'
        ]);
        if($validator->fails()){
            return Response(['response' => $validator->errors(), 'status' => 500], 200);
        } else {
            
            $savePersonalDetails = SelectedCandidate::where('candidate_id', $candidateId)->update([
                'name' => $request->name,
                'date_of_birth' => $request->date_of_birth,
                'fathers_name' => $request->fathers_name,
                'mothers_name' => $request->mothers_name,
                'fathers_occupation' => $request->fathers_occupation,
                'mothers_occupation' => $request->mothers_occupation,
                'gender' => $request->gender,
                'marital_status' => $request->marital_status,
                'physically_challenged' => $request->physically_challenged,
                'current_address' => $request->current_address,
                'permanent_address' => $request->permanent_address,
                'email_address' => $request->email_address,
                'phone_number' => $request->phone_number
                    
            ]);
            
            return Response(['response' => '', 'message' => 'Personal Details Saved Successfully', 'status' => 200], 200);
        }
    }
    
    
    public function sendOfferLetterEmail(Request $request)
    {
        $candidateId = $request->candidate_id;
        $jobId = $request->job_id;
        
        date_default_timezone_set('Asia/Kolkata'); // Set timezone
        
        $selectedCandidate = SelectedCandidate::insert([
                    'candidate_id' => $request->candidate_id,
                    'employer_id' => $request->employer_id,
                    'job_id' => $request->job_id,
                    'position_name' => $request->position_name,
                    'reporting_person' => $request->reporting_person,
                    'joining_date' => $request->joining_date,
                    'work_location' => $request->work_location,
                    'compensation' => $request->compensation,
                    'comment' => $request->comment,
                    'benefits' => $request->benefits,
                    'offer_letter_expiry' => $request->offer_letter_expiry,
                    'offer_letter_expiry_value' => $request->offer_letter_expiry_value,
                ]);
    
        
        
        $candidateEmail = CandidateJobApply::where('id', $candidateId)
                            ->where('job_form_id', $jobId)
                            ->value('email');
                            
        $employerCompanyName = Employer::where('id', $request->employer_id)->value('company_name');
        
        $candidateData = CandidateJobApply::where('id', $candidateId)
                            ->where('job_form_id', $jobId)
                            ->first();
                            
       $candidateName = trim(
            ($candidateData['first_name'] ?? '') . ' ' . ($candidateData['middle_name'] ?? '') . ' ' . ($candidateData['last_name'] ?? '')
        );
        
        $formattedJoiningDate = Carbon::parse($request->joining_date)->format('d/m/Y');
        
        $jobTitle = Job::where('id', $jobId)->value('title');
        
        $reportingPersonData = Staff::where('id', $request->reporting_person)->first();
        $reportingPersonName = $reportingPersonData['first_name'] . ' ' . $reportingPersonData['last_name'];
        
        $panel_link = HTTP_PATH_FRONTEND . "/offer-letter/" . $request->employer_id . "/offer/" . $candidateId;
    
        
        if (empty($candidateEmail)) {
            return response()->json(['error' => 'Invalid or missing candidate email address.'], 400);
        }
    
        
        $emailTemplate = EmailTemplate::where('id', 1)->first();
    
    
        
        $toRepArray = ['[!candidate_name!]', '[!position_name!]', '[!company_name!]', '[!reporting_person!]', '[!joining_date!]', '[!work_location!]', '[!compensation!]', '[!comment!]', '[!benefits!]', '[!job_title!]', '[!panel_link!]'];
        $fromRepArray = [
            $candidateName,
            $request->position_name, $employerCompanyName, $reportingPersonName, $formattedJoiningDate,
            $request->work_location, $request->compensation, $request->comment, $request->benefits, $jobTitle, $panel_link
            ]; 
        $emailSubject = str_replace($toRepArray, $fromRepArray, $emailTemplate->subject);
        $emailBody = str_replace($toRepArray, $fromRepArray, $emailTemplate->template);
        
        $logo = Employer::where('id', $request->employer_id)->value('company_logo');
                
                if(!empty($logo)){
                    $logoPath = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $logo;
                } else{
                    $logoPath = LOGO_PATH;
                }
    
        // Send the email
        try {
            Mail::to($candidateEmail)->send(new SendMail($emailBody, $emailSubject, $logoPath));
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to send email.', 'message' => $e->getMessage()], 500);
        }
        
        $offerStatus = CandidateJobApply::where('id', $candidateId)->update([
            'offer_letter_status' => 1,
        ]);
        
        $sendTime = SelectedCandidate::where('candidate_id', $candidateId)->update([
            'send_time' => now(),
        ]);
    
        return Response(['response' => 'thank you', 'message' => 'Email sent successfully.', 'status' => 200], 200);
    }
    
    
    public function offerInitialData(Request $request) {
        $candidateId = $request->candidate_id;
        $employerId = $request->id;
        $draftStatus = CandidateJobApply::where('id', $candidateId)->value('draft_status');
        
        if($draftStatus == "1"){
            $draftData = OfferDraftData::where('candidate_id', $candidateId)->first();
            $data['draftData'] = $draftData;
            $data['draft_status'] = $draftStatus;
            $staffExists = Staff::where('employer_id', $employerId)->exists();
    
            if (!$staffExists) {
                return Response(['response' => null, 'message' => 'No staff found with the given employer ID.', 'status' => 404], 404);
            }
        
           
            $staffList = Staff::all();
            $data['staffList'] = $staffList;
        
            $candidate = CandidateJobApply::where('id', $candidateId)->get();
            $data['candidate'] = $candidate;
        }
        else{
             $staffExists = Staff::where('employer_id', $employerId)->exists();
    
            if (!$staffExists) {
                return Response(['response' => null, 'message' => 'No staff found with the given employer ID.', 'status' => 404], 404);
            }
        
           
            $staffList = Staff::all();
            $data['staffList'] = $staffList;
        
            $candidate = CandidateJobApply::where('id', $candidateId)->get();
            $data['candidate'] = $candidate;
            $data['draft_status'] = "0";
        }
        
        return Response(['response' => $data, 'message' => 'Data fetched successfully.', 'status' => 200], 200);
    }
    
    
    public function onBoardingForm(Request $request){
        $candidateId = $request->candidate_id;
        $employerId = $request->employer_id;
        
        $link = HTTP_PATH_FRONTEND . "/onboarding/" . $employerId . "/welcome/" . $candidateId;
        
        $companyName =  Employer::where('id', $employerId)->value('company_name');
        $employerEmail = Employer::where('id', $employerId)->value('email_address');
        
        $candidateData = CandidateJobApply::where('id', $candidateId)->first();
        
        $candidateEmail = $candidateData['email'];
       
        $candidateName = trim(
            ($candidateData['first_name'] ?? '') . ' ' . ($candidateData['middle_name'] ?? '') . ' ' . ($candidateData['last_name'] ?? '')
        );
        
        $joiningDate = SelectedCandidate::where('candidate_id', $candidateId)->value('joining_date');
        
        
        $emailTemplate = EmailTemplate::where('id', 2)->first();
    
    
        
        $toRepArray = ['[!link!]', '[!company_name!]', '[!candidate_name!]', '[!joining_date!]', '[!employer_email!]'];
        $fromRepArray = [$link, $companyName, $candidateName, $joiningDate, $employerEmail];
        
        $emailSubject = str_replace($toRepArray, $fromRepArray, $emailTemplate->subject);
        $emailBody = str_replace($toRepArray, $fromRepArray, $emailTemplate->template);
        
        $logo = Employer::where('id', $employerId)->value('company_logo');
                
                if(!empty($logo)){
                    $logoPath = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $logo;
                } else{
                    $logoPath = LOGO_PATH;
                }
    
        // Send the email
        try {
            Mail::to($candidateEmail)->send(new SendMail($emailBody, $emailSubject, $logoPath));
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to send email.', 'message' => $e->getMessage()], 500);
        }
        
         $onboardingStatus = CandidateJobApply::where('id', $candidateId)->update([
            'on_boarding_status' => 1,
        ]);
        
        
        $onboardingLinkStatus = SelectedCandidate::where('candidate_id', $candidateId)->update([
            'onboarding_link_status' => 1,
            'send_time' => now(),
            // 'expire_time' => Carbon::now()->addMinutes(30),
        ]);
        
        return Response(['response' => 'thank you', 'message' => 'Onboarding Form Email sent successfully.', 'status' => 200], 200);
    }
    
    
    public function academicDetailsData(Request $request, $id) {
        $candidateId = $id;
        $candidateName = SelectedCandidate::where('candidate_id', $candidateId)->value('name');
        $employerId = CandidateJobApply::where('id', $candidateId)->value('employer_id');
        $qualificationData = Qualification::where('employer_id', $employerId)->orWhere('employer_id','0')->get();
        
        $candidate = SelectedCandidate::where('candidate_id', $candidateId)->first(['onboarding_link_status', 'send_time', 'expire_time']);

         if (!empty($candidate->onboarding_link_status)) {
            $currentTime = Carbon::now();
            if ($currentTime->greaterThan(Carbon::parse($candidate->expire_time))) {
                return Response(['response' => 'The link has been expired', 'message' => 'successful', 'status' => 500], 200);
            }
        }
        
        if(empty($candidateName)){
            return Response(['response' => '', 'message' => 'Please fill personal details.', 'status' => '404'], 200);
        } else{
            $yearList = $GLOBALS['yearsArray'];
            $candidate_education = CandidateEducation::where('candidate_job_apply_id', $candidateId)->get();
            return Response(['response' => ['yearList' => $yearList, 'candidate_education' => $candidate_education, 'qualificationData' => $qualificationData], 'message' => 'Year List fetch successfully', 'status' => 200], 200);
        }
    }
    
    
    // public function saveAcademicDetails(Request $request, $candidate_id)
    // {
    //     // Validate the incoming data
    //     $validatedData = $request->validate([
    //         'academicDetails.*.course' => 'required|string',
    //         'academicDetails.*.school_college' => 'required|string',
    //         'academicDetails.*.city' => 'required|string',
    //         'academicDetails.*.university' => 'required|string',
    //         'academicDetails.*.year' => 'required|integer',
    //         'academicDetails.*.percentage' => 'required|numeric',
    //     ]);
    
    //     $academicDetails = $request->input('academicDetails');
    
    //     // Process file uploads if present
    //     foreach ($academicDetails as $index => $detail) {
    //         if ($request->hasFile("academicDetails.$index.documents")) {
    //             // Store the file in the specified directory and get the full path
    //             $file = $request->file("academicDetails.$index.documents");
    //             $filePath = $file->store('uploads/academic_documents', 'public');
    //             $fileName = str_replace('uploads/academic_documents/', '', $filePath);
            
    //             // Save the full storage path in the documents field
    //             $academicDetails[$index]['documents'] = $fileName;
    //         } else {
    //             $academicDetails[$index]['documents'] = $detail['documents'] ?? null; // Keep existing value or set null
    //         }
    //     }
    
    //     // Save or update academic details in the database
    //     foreach ($academicDetails as $value) {

    //         CandidateEducation::where('id', $value['id'])
    //             ->where('candidate_job_apply_id', $candidate_id)
    //             ->update([
    //                 'course' => $value['course'],
    //                 'school_college' => $value['school_college'],
    //                 'city' => $value['city'],
    //                 'university_board' => $value['university'],
    //                 'passing_year' => $value['year'],
    //                 'percentage' => $value['percentage'],
    //                 'documents' => $value['documents'], // Store the path to the uploaded file
    //             ]);
    //     }
        

    
    //     return response()->json(['response' => '', 'message' => 'Academic details saved successfully', 'status' => '200'], 200);
    // }


public function saveAcademicDetails(Request $request, $candidate_id)
{
    // Validate the incoming data
    $validatedData = $request->validate([
        'academicDetails.*.course' => 'required|string',
        'academicDetails.*.qualification_id' => 'required|numeric',
        'academicDetails.*.school_college' => 'required|string',
        'academicDetails.*.city' => 'required|string',
        'academicDetails.*.university' => 'required|string',
        'academicDetails.*.year' => 'required|integer',
        'academicDetails.*.percentage' => 'required|numeric',
    ]);

    $academicDetails = $request->input('academicDetails');

    // Process file uploads if present
    foreach ($academicDetails as $index => $detail) {
        if ($request->hasFile("academicDetails.$index.documents")) {
            // Store the file in the specified directory and get the full path
            $file = $request->file("academicDetails.$index.documents");
            $filePath = $file->store('uploads/academic_documents', 'public');
            $fileName = str_replace('uploads/academic_documents/', '', $filePath);

            // Save the full storage path in the documents field
            $academicDetails[$index]['documents'] = $fileName;
        } else {
            $academicDetails[$index]['documents'] = $detail['documents'] ?? null; // Keep existing value or set null
        }
    }

    // Iterate through the academic details and either update or insert the record
    foreach ($academicDetails as $value) {
        if (isset($value['id']) && CandidateEducation::where('id', $value['id'])->where('candidate_job_apply_id', $candidate_id)->exists()) {
            // Update the existing record
            CandidateEducation::where('id', $value['id'])
                ->where('candidate_job_apply_id', $candidate_id)
                ->update([
                    'course' => $value['course'],
                    'qualification_id' => $value['qualification_id'],
                    'school_college' => $value['school_college'],
                    'city' => $value['city'],
                    'university_board' => $value['university'],
                    'passing_year' => $value['year'],
                    'percentage' => $value['percentage'],
                    'documents' => $value['documents'], // Store the path to the uploaded file
                ]);
        } else {
            // Insert a new record
            CandidateEducation::create([
                'candidate_job_apply_id' => $candidate_id,
                'course' => $value['course'],
                'qualification_id' => $value['qualification_id'],
                'school_college' => $value['school_college'],
                'city' => $value['city'],
                'university_board' => $value['university'],
                'passing_year' => $value['year'],
                'percentage' => $value['percentage'],
                'documents' => $value['documents'], // Store the path to the uploaded file
            ]);
        }
    }

    return response()->json(['response' => '', 'message' => 'Academic details saved successfully', 'status' => 200], 200);
}

    
    
    public function offerDraftData(Request $request) {
        $candidateId = $request->candidate_id;
        $jobId = $request->job_id;
        
        $draftPresent = OfferDraftData::where('candidate_id', $candidateId)->first();
        if(!empty($draftPresent)){
            $draftData = OfferDraftData::where('candidate_id', $candidateId)->update([
                'candidate_id' => $request->candidate_id,
                'position_name' => $request->position_name,
                'reporting_person' => $request->reporting_person,
                'joining_date' => $request->joining_date,
                'work_location' => $request->work_location,
                'compensation' => $request->compensation,
                'comment' => $request->comment,
                'benefits' => $request->benefits,
                'offer_letter_expiry' => $request->offer_letter_expiry,
                'offer_letter_expiry_value' => $request->offer_letter_expiry_value,
            ]);
        }else{
            $draftData = OfferDraftData::insert([
                'candidate_id' => $request->candidate_id,
                'position_name' => $request->position_name,
                'reporting_person' => $request->reporting_person,
                'joining_date' => $request->joining_date,
                'work_location' => $request->work_location,
                'compensation' => $request->compensation,
                'comment' => $request->comment,
                'benefits' => $request->benefits,
                'offer_letter_expiry' => $request->offer_letter_expiry,
                'offer_letter_expiry_value' => $request->offer_letter_expiry_value,
            ]);
        }
                
        $draftStatus = CandidateJobApply::where('id', $candidateId)->update([
            'draft_status' => 1,
        ]);
        
        return Response(['response' => '', 'message' => 'Draft data saved successfully', 'status' => 200], 200);
    }
    
    public function fetchPersonalDetails(Request $request){
        
        $candidateId = $request->candidate_id;
                // return Response(['response' => $candidateId, 'message' => "",'status' => 200], 200);

        $candidateDetails = CandidateJobApply::where('id', $candidateId)->first();
    
    
        if (empty($candidateDetails)) {
            return Response(['response' => null, 'message' => "Candidate not found.", 'status' => 404], 404);
        }
        
        
        $candidate = SelectedCandidate::where('candidate_id', $candidateId)->first(['onboarding_link_status', 'send_time', 'expire_time']);

         if (!empty($candidate->onboarding_link_status)) {
            $currentTime = Carbon::now();
            if ($currentTime->greaterThan(Carbon::parse($candidate->expire_time))) {
                return Response(['response' => 'The link has been expired', 'message' => 'successful', 'status' => 500], 200);
            }
        }
        
    
        $candidateData = [
            'candidate_id' => $candidateDetails->id,
            'job_id' => $candidateDetails->job_form_id,
            'name' => $candidateDetails->first_name . ' ' . $candidateDetails->last_name,
            'email_address' => $candidateDetails->email,
            'phone_number' => $candidateDetails->contact_number,
            'address' => $candidateDetails->address,
            'gender' => $candidateDetails->gender,
            'date_of_birth' => Carbon::parse($candidateDetails->date_of_birth)->format('Y-m-d'),
            'marital_status' => $candidateDetails->martial_status,
            'physically_challenged' => $candidateDetails->physically_challenged,
            'created' => format_date($candidateDetails->created),
            'status' => $candidateDetails->status,
            'interview_status' => $candidateDetails->interview_status,
            'interviewDetails' => getFeedbackData($candidateDetails->id),
            'jobAppliedFor' => Job::where('id', $candidateDetails->job_form_id)->value('title'),
        ];
    
        return Response(['response' => $candidateData, 'message' => "",'status' => 200], 200);

    }
    
    public function getExperience(Request $request, $id){
        $candidateId = $id;
        $candidateName = SelectedCandidate::where('candidate_id', $candidateId)->value('name');
        $employerId = CandidateJobApply::where('id', $candidateId)->value('employer_id');
        $designationData = Skill::where(function ($query) use ($employerId) {
            $query->where('employer_id', $employerId)
                  ->orWhere('employer_id', '0');
        })
        ->where('type', 'Designation')
        ->get();
        
        $candidate = SelectedCandidate::where('candidate_id', $candidateId)->first(['onboarding_link_status', 'send_time', 'expire_time']);

         if (!empty($candidate->onboarding_link_status)) {
            $currentTime = Carbon::now();
            if ($currentTime->greaterThan(Carbon::parse($candidate->expire_time))) {
                return Response(['response' => 'The link has been expired', 'message' => 'successful', 'status' => 500], 200);
            }
        }
        
        if(empty($candidateName)){
            return Response(['response' => '', 'message' => 'Please fill personal details.', 'status' => 404], 200);
        } else{
            // $yearList = $GLOBALS['yearsArray'];
            $candidate_experience = CandidateExperience::where('candidate_job_apply_id', $id)->get();
            return Response(['response' => ['candidate_experience' => $candidate_experience, 'designationData' => $designationData], 'message' => 'Candidate Experience Fetch Successfully', 'status' => 200], 200);
        }
    }
    
    public function saveExperience(Request $request, $candidate_id) {
         // Validate the incoming data
        $validatedData = $request->validate([
            'experienceDetails.*.start_date' => 'required|date',
            'experienceDetails.*.end_date' => 'required|date',
            'experienceDetails.*.organisation_name' => 'required|string',
            'experienceDetails.*.designation' => 'required|numeric',
            'experienceDetails.*.reason_of_leaving' => 'required|string',
        ]);
    
        $experienceDetails = $request->input('experienceDetails');
    
        // Process file uploads if present
        foreach ($experienceDetails as $index => $detail) {
            if ($request->hasFile("experienceDetails.$index.documents")) {
                // Store the file in the specified directory and get the full path
                $file = $request->file("experienceDetails.$index.documents");
                $filePath = $file->store('uploads/experience_documents', 'public');
                $fileName = str_replace('uploads/experience_documents/', '', $filePath);
    
                // Save the full storage path in the documents field
                $experienceDetails[$index]['documents'] = $fileName;
            } else {
                $experienceDetails[$index]['documents'] = $detail['documents'] ?? null; // Keep existing value or set null
            }
        }
    
        // Iterate through the academic details and either update or insert the record
        foreach ($experienceDetails as $value) {
            if (isset($value['id']) && CandidateExperience::where('id', $value['id'])->where('candidate_job_apply_id', $candidate_id)->exists()) {
                // Update the existing record
                CandidateExperience::where('id', $value['id'])
                    ->where('candidate_job_apply_id', $candidate_id)
                    ->update([
                        'start_date' => $value['start_date'],
                        'end_date' => $value['end_date'],
                        'organisation_name' => $value['organisation_name'],
                        'designation' => $value['designation'],
                        'reason_of_leaving' => $value['reason_of_leaving'],
                        'documents' => $value['documents'], // Store the path to the uploaded file
                    ]);
            } else {
                // Insert a new record
                CandidateExperience::create([
                    'candidate_job_apply_id' => $candidate_id,
                    'start_date' => $value['start_date'],
                    'end_date' => $value['end_date'],
                    'organisation_name' => $value['organisation_name'],
                    'designation' => $value['designation'],
                    'reason_of_leaving' => $value['reason_of_leaving'],
                    'documents' => $value['documents'], // Store the path to the uploaded file
                ]);
            }
        }
    
        return response()->json(['response' => '', 'message' => 'Experience details saved successfully', 'status' => 200], 200);
    }
    
    
    // public function saveDocuments(Request $request, $candidate_id) {
    //     $validateData = $request->validate([
    //         'documentsDetails.*.identification' => 'required|file',
    //         'documentsDetails.*.portfolio' => 'required',
    //         'documentsDetails.*.certificate' => 'required|file',
    //     ]);
    
    //     $documentsDetails = $request->input('documentsDetails');
        
    //     foreach ($documentsDetails as $index => $document) {
    //         if ($request->hasFile("documentsDetails.$index.identification")) {
    //             $file = $request->file("documentsDetails.$index.identification");
    //             $filePath = $file->store('uploads/identification_documents', 'public'); 
    //         } else {        
    //             $filePath = null;
    //         }
    
    //         SelectedCandidate::updateOrCreate(
    //             ['candidate_id' => $candidate_id],
    //             [
    //                 'identification' => $filePath,
    //                 'portfolio' => $document['portfolio'],
    //             ]
    //         );
    //     }
        
    //     foreach ($documentsDetails as $index => $document) {
    //         if ($request->hasFile("documentsDetails.$index.certificate")) {
    //             $file = $request->file("documentsDetails.$index.certificate");
    //             $filePath = $file->store('uploads/certificates', 'public'); 
    //         } else {        
    //             $filePath = null;
    //         }
    
    //         Certificate::Insert(
    //             ['candidate_id' => $candidate_id],
    //             ['certificates' => $filePath]
    //         );
    //     }
        
    
    //     return Response(['response' => '', 'message' => 'Documents store succesfully', 'status' => 200], 200);
    // }
    
    public function getDocument($candidate_id){
        $candidate = SelectedCandidate::where('candidate_id', $candidate_id)->first(['onboarding_link_status', 'send_time', 'expire_time']);

         if (!empty($candidate->onboarding_link_status)) {
            $currentTime = Carbon::now();
            if ($currentTime->greaterThan(Carbon::parse($candidate->expire_time))) {
                return Response(['response' => 'The link has been expired', 'message' => 'successful', 'status' => 500], 200);
            }
        }
        return Response(['response' => '', 'message' => 'successful', 'status' => 200], 200);
    }

    // public function saveDocuments(Request $request, $candidate_id) {
    //     $validateData = $request->validate([
    //         'documentsDetails.*.identification' => 'required|file',
    //         // 'documentsDetails.*.portfolio' => 'required',
    //         // 'documentsDetails.*.certificate' => 'required|file',
    //     ]);
    
    //     $documentsDetails = $request->input('documentsDetails');
        
    //     foreach ($documentsDetails as $index => $document) {
            
    //         if ($request->hasFile("documentsDetails.$index.identification")) {
    //             $file = $request->file("documentsDetails.$index.identification");
    //             $filePath = $file->store('uploads/identification_documents', 'public'); 
    //         } else {        
    //             $filePath = null;
    //         }
    
    //         SelectedCandidate::updateOrCreate(
    //             ['candidate_id' => $candidate_id],
    //             [
    //                 'identification' => $filePath,
    //                 'portfolio' => $document['portfolio'],
    //             ]
    //         );
    
            
    //         foreach ($request->file("documentsDetails.$index.certificate") as $certificate) {
    //             $certificatePath = $certificate->store('uploads/certificates', 'public');
    
    //             Certificate::insert([
    //                 'candidate_id' => $candidate_id,
    //                 'certificates' => $certificatePath
    //             ]);
    //         }
    //     }
    
    //     return response(['response' => '', 'message' => 'Documents stored successfully', 'status' => 200], 200);
    // }
    
    public function saveDocuments(Request $request, $candidate_id) {
        //         $validateData = $request->validate([
        //     'identification' => 'required|file',
        //     'portfolio' => 'nullable|string',
        //     'certificate' => 'nullable|file', // Assuming certificate is optional
        // ]);
        
        // Handle identification file upload
        $identificationFileName = null;
        if ($request->hasFile('identification')) {
            $file = $request->file('identification');
            $path = $file->store('uploads/identification_documents', 'public');
            $identificationFileName = basename($path); // Extract only the file name
        }
        
        // Update or create SelectedCandidate entry
        SelectedCandidate::updateOrCreate(
            ['candidate_id' => $candidate_id],
            [
                'identification' => $identificationFileName,
                'portfolio' => $request->input('portfolio'),
            ]
        );
        
        // Handle single certificate file upload
        if ($request->hasFile('certificates')) {
            $file = $request->file('certificates');
            $path = $file->store('uploads/certificates', 'public');
            $certificateFileName = basename($path); // Extract only the file name
        
            Certificate::create([
                'candidate_id' => $candidate_id,
                'certificates' => $certificateFileName,
            ]);
        }
        
        return response(['response' => '', 'message' => 'Documents stored successfully', 'status' => 200], 200);

    }

    
    
    // public function getProfileSummary(Request $request, $candidate_id)
    // {
    //     $candidateData = SelectedCandidate::where('candidate_id', $candidate_id)->first();
    //     $experienceData = CandidateExperience::where('candidate_job_apply_id', $candidate_id)->get();
    //     $experienceDataArray = array();
        
    //     foreach($experienceData as $key => $value){
    //         $experienceDataArray['id'] = $value->id;
    //         $experienceDataArray['candidate_job_apply_id'] = $value->candidate_job_apply_id;
    //         $experienceDataArray['start_date'] = $value->start_date;
    //         $experienceDataArray['end_date'] = $value->end_date;
    //         $experienceDataArray['organisation_name'] = $value->organisation_name;
    //         $experienceDataArray['designation'] = $value->designation;
    //         $experienceDataArray['reason_of_leaving'] = $value->reason_of_leaving;
    //         $experienceDataArray['documents'] = DISPLAY_CANDIDATE_EXPERIENCE_DOCUMENTS_PATH . $value->documents;
    //     }
        
    //     $academicData = CandidateEducation::where('candidate_job_apply_id', $candidate_id)->get();
    //     $academicDataArray = array();
        
    //     foreach($academicData as $key => $value){
    //         $academicDataArray['id'] = $value->id;
    //         $academicDataArray['candidate_job_apply_id'] = $value->candidate_job_apply_id;
    //         $academicDataArray['qualification_id'] = $value->qualification_id;
    //         $academicDataArray['course'] = $value->course;
    //         $academicDataArray['school_college'] = $value->school_college;
    //         $academicDataArray['city'] = $value->city;
    //         $academicDataArray['university_board'] = $value->university_board;
    //         $academicDataArray['passing_year'] = $value->passing_year;
    //         $academicDataArray['percentage'] = $value->percentage;
    //         $academicDataArray['documents'] = DISPLAY_CANDIDATE_ACADEMIC_DOCUMENTS_PATH . $value->documents;
    //     }
        
    //     $designationIds = CandidateExperience::where('candidate_job_apply_id', $candidate_id)->pluck('designation');
        
        
    //     $designationNames = Skill::whereIn('id', $designationIds)->get();
        
    //     $certificateData = Certificate::where('candidate_id', $candidate_id)->first();
        
    //     $data = array();
    //     $data['identification'] = DISPLAY_CANDIDATE_DOCUMENTS_PATH . $candidateData->identification;
    //     $data['certificate'] = DISPLAY_CANDIDATE_CERTIFICATE_PATH . $certificateData->cerificates;
    
    //     return response(['response' => ['data' => $data, 'candidateData' => $candidateData, 'experienceDataArray' => $experienceDataArray, 'designationNames' => $designationNames, 'academicDataArray' => $academicDataArray],
    //         'message' => 'Data fetched successfully',
    //         'status' => 200
    //     ], 200);
    // }
    
    
    public function getProfileSummary(Request $request, $candidate_id)
    {
        $candidateData = SelectedCandidate::where('candidate_id', $candidate_id)->first();
        $experienceData = CandidateExperience::where('candidate_job_apply_id', $candidate_id)->get();
        $experienceDataArray = [];
        
        foreach ($experienceData as $key => $value) {
            $experienceDataArray[] = [
                'id' => $value->id,
                'candidate_job_apply_id' => $value->candidate_job_apply_id,
                'start_date' => $value->start_date,
                'end_date' => $value->end_date,
                'organisation_name' => $value->organisation_name,
                'designation' => $value->designation,
                'reason_of_leaving' => $value->reason_of_leaving,
                'documents' => DISPLAY_CANDIDATE_EXPERIENCE_DOCUMENTS_PATH . $value->documents,
            ];
        }
        
        $academicData = CandidateEducation::where('candidate_job_apply_id', $candidate_id)->get();
        $academicDataArray = [];
        
        foreach ($academicData as $key => $value) {
            $academicDataArray[] = [
                'id' => $value->id,
                'candidate_job_apply_id' => $value->candidate_job_apply_id,
                'qualification_id' => $value->qualification_id,
                'course' => $value->course,
                'school_college' => $value->school_college,
                'city' => $value->city,
                'university_board' => $value->university_board,
                'passing_year' => $value->passing_year,
                'percentage' => $value->percentage,
                'documents' => DISPLAY_CANDIDATE_ACADEMIC_DOCUMENTS_PATH . $value->documents,
            ];
        }
        
        $designationIds = CandidateExperience::where('candidate_job_apply_id', $candidate_id)->pluck('designation');
        $designationNames = Skill::whereIn('id', $designationIds)->get();
        $certificateData = Certificate::where('candidate_id', $candidate_id)->first();
        
        $data = [];
        $data['identification'] = DISPLAY_CANDIDATE_DOCUMENTS_PATH . $candidateData->identification;
        $data['certificate'] = DISPLAY_CANDIDATE_CERTIFICATE_PATH . $certificateData->cerificates;
        
        return response([
            'response' => [
                'data' => $data,
                'candidateData' => $candidateData,
                'experienceDataArray' => $experienceDataArray,
                'designationNames' => $designationNames,
                'academicDataArray' => $academicDataArray,
            ],
            'message' => 'Data fetched successfully',
            'status' => 200
        ], 200);
    }
    
    public function get_preference_data(Request $request)
    {
        $employerId = $request->employer_id;
    
        // Validate the employer ID
        if (!$employerId) {
            return response([
                'response' => 'Employer ID is required.',
                'status' => 500
            ], 200);
        }
    
        // Fetch preferences matching the employer ID
        $preferences = Preference::where('employer_id', $employerId)
            ->get(['id', 'question', 'values as value_type', 'options', 'created_at', 'updated_at'])
            ->map(function ($preference) {
                // Decode the JSON options back to an array
                $preference->options = json_decode($preference->options, true);
                return $preference;
            });
    
        // Check if preferences exist for the employer
        if ($preferences->isEmpty()) {
            return response([
                'response' => 'No preferences found for the specified employer.',
                'status' => 500
            ], 200);
        }
    
        // Return preferences
        return response([
            'response' => [
                'preferences' => $preferences
            ],
            'message' => 'Preferences retrieved successfully.',
            'status' => 200
        ], 200);
    }


    
    // public function savePreferences(Request $request, $candidate_id)
    // {
    //     $validatedData = $request->validate([
    //         // '*.question' => 'required',
    //         // '*.value_type' => 'required',
    //         // '*.options' => 'required',
    //         // '*.answer' => 'required',
    //     ]);
    
        
    //     $preferenceData = json_encode($validatedData);
    

    //     $updated = SelectedCandidate::where('candidate_id', $candidate_id)
    //         ->update(['preference_data' => $preferenceData]);
    
    //     if ($updated) {
    //         return Response(['response' => '', 'message' => 'Preferences saved successfully.', 'status' => 200], 200);
    //     } else {
    //         return Response(['response' => '', 'message' => 'Failed to save preferences.', 'status' => 200], 200);
    //     }
    // }
    
    
    public function savePreferences(Request $request, $candidate_id)
    {
        $preferenceData = json_encode($request->all());
    
        $exists = SelectedCandidate::where('candidate_id', $candidate_id)->exists();
        if (!$exists) {
            return response()->json(['message' => 'Candidate not found.'], 500);
        }
    
        $updated = SelectedCandidate::where('candidate_id', $candidate_id)
            ->update(['preference_data' => $preferenceData]);
            
        SelectedCandidate::where('candidate_id', $candidate_id)->update([
            'on_boarding_status' => 1
            ]);
            
        CandidateJobApply::where('id', $candidate_id)->update([
            'on_boarding_status' => 1
            ]);
    
        if ($updated) {
            return response()->json(['response' => '', 'message' => 'Preferences saved successfully.', 'status' => 200]);
        } else {
            return response()->json(['response' => '', 'message' => 'Failed to save preferences.', 'status' => 500]);
        }
    }


    
    // public function getOfferLetterData(Request $request){
    //     $candidateId = $request->candidate_id;
    //     $employerId = $request->employer_id;
        
    //     $candidate = SelectedCandidate::where('candidate_id', $candidateId)->first(['onboarding_link_status', 'send_time', 'expire_time']);

    //     $generalSettingData = GeneralSetting::where('employer_id', $employerId)->first();
    //     if (empty($generalSettingData)) {
    //         return Response(['response' => 'General setting not found', 'message' => 'error', 'status' => 500], 200);
    //     }
    //     $sendTime = $candidate->send_time;

    //     $offerLetterExpiry = $generalSettingData->offer_letter_expiry; 
    //     $offerLetterExpiryValue = $generalSettingData->offer_letter_expiry_value; 
        
    //     if (!empty($candidate->onboarding_link_status)) {
    //         $currentTime = Carbon::now();
        
    //         if ($offerLetterExpiry === 'minutes') {
    //             $expirationTime = Carbon::parse($candidate->send_time)->addMinutes($offerLetterExpiryValue);
    //         } elseif ($offerLetterExpiry === 'hours') {
    //             $expirationTime = Carbon::parse($candidate->send_time)->addHours($offerLetterExpiryValue);
    //         } else {
    //             return Response(['response' => 'Invalid expiry setting', 'message' => 'error', 'status' => 500], 200);
    //         }
        
    //         if ($currentTime->greaterThan($expirationTime)) {
    //             return Response(['response' => 'The link has expired', 'message' => 'success', 'status' => 500], 200);
    //         }
    //     }
        
    //     $candidateDetails = CandidateJobApply::where('id',$candidateId)->first();
    //     $candidateData = array();
        
    //     $candidateData['candidate_id'] = $candidateDetails->id;
    //     $candidateData['job_id'] = $candidateDetails->job_form_id;
    //     $candidateData['first_name'] = $candidateDetails->first_name;
    //     $candidateData['last_name'] = $candidateDetails->last_name;
    //     $candidateData['email'] = $candidateDetails->email;
    //     $candidateData['phone'] = $candidateDetails->contact_number;
    //     $candidateData['address'] = $candidateDetails->address;
    //     $candidateData['gender'] = $candidateDetails->gender;
    //     $candidateData['dateofbirth'] = $candidateDetails->date_of_birth;
    //     $candidateData['martialstatus'] = $candidateDetails->martial_status;
    //     $candidateData['physical_challenged'] = $candidateDetails->physical_challenge;
    //     $candidateData['created'] = format_date($candidateDetails->created);
    //     $candidateData['status'] = $candidateDetails->status;
    //     $candidateData['interview_status'] = $candidateDetails->interview_status;
    //     $candidateData['interviewDetails'] = getFeedbackData($candidateDetails->id);
    //     $candidateData['jobAppliedFor'] = Job::where('id',$candidateDetails->job_form_id)->value('title');
        
    //     $data['candidateData'] = $candidateData;
        
    //     $candidateOfferDetails = SelectedCandidate::where('candidate_id',$candidateId)->where('employer_id', $employerId)->first();
        
    //     $candidateOfferDetailsData = array();
        
    //     $candidateOfferDetailsData['position_name'] = $candidateOfferDetails->position_name;
    //     $candidateOfferDetailsData['joining_date'] = $candidateOfferDetails->joining_date;
    //     $candidateOfferDetailsData['work_location'] = $candidateOfferDetails->work_location;
    //     $candidateOfferDetailsData['compensation'] = $candidateOfferDetails->compensation;
    //     $candidateOfferDetailsData['comment'] = $candidateOfferDetails->comment;
    //     $candidateOfferDetailsData['benefits'] = $candidateOfferDetails->comment;
    //     $candidateOfferDetailsData['department'] = $candidateOfferDetails->comment;
    //     $candidateOfferDetailsData['offer_letter_link_expiry'] = $candidateOfferDetails->comment;
    //     $candidateOfferDetailsData['employer_email'] = Employer::where('id', $employerId)->first()->value('email_address');
    //     $candidateOfferDetailsData['company_logo'] = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH.Employer::where('id', $employerId)->first()->value('company_logo');
        
    //     $data['candidateOfferDetailsData'] = $candidateOfferDetailsData;

        
    //     return Response(['response' => $data, 'message' => "", 'status' => 200],200);
    //     // position
    //     // department
    //     // location
    //     // start date
    //     // salary
    //     // benefits
    //     // offer letter link expiry
    //     // employer email
    //     // company logo
        
    // }
    
//     public function getOfferLetterData(Request $request)
// {
//     $candidateId = $request->candidate_id;
//     $employerId = $request->employer_id;

//     $candidate = SelectedCandidate::where('candidate_id', $candidateId)->first(['onboarding_link_status', 'send_time', 'expire_time']);

//     $generalSettingData = GeneralSetting::where('employer_id', $employerId)->first();
//     if (empty($generalSettingData)) {
//         return Response(['response' => 'General setting not found', 'message' => 'error', 'status' => 500], 200);
//     }
//     $sendTime = $candidate->send_time;

//     $offerLetterExpiry = $generalSettingData->offer_letter_expiry;
//     $offerLetterExpiryValue = $generalSettingData->offer_letter_expiry_value;

//     $remainingTime = null; // Default value

//     if (!empty($candidate->onboarding_link_status)) {
//         $currentTime = Carbon::now();

//         if ($offerLetterExpiry === 'minutes') {
//             $expirationTime = Carbon::parse($candidate->send_time)->addMinutes($offerLetterExpiryValue);
//         } elseif ($offerLetterExpiry === 'hours') {
//             $expirationTime = Carbon::parse($candidate->send_time)->addHours($offerLetterExpiryValue);
//         } else {
//             return Response(['response' => 'Invalid expiry setting', 'message' => 'error', 'status' => 500], 200);
//         }

//         if ($currentTime->lessThanOrEqualTo($expirationTime)) {
//             // Calculate total remaining time in minutes
//             $remainingMinutes = $expirationTime->diffInMinutes($currentTime);
//             $remainingTime = $remainingMinutes; // Total remaining time in minutes
//         }

//     }

//     $candidateDetails = CandidateJobApply::where('id', $candidateId)->first();
//     $candidateData = [];

//     $candidateData['candidate_id'] = $candidateDetails->id;
//     $candidateData['job_id'] = $candidateDetails->job_form_id;
//     $candidateData['first_name'] = $candidateDetails->first_name;
//     $candidateData['last_name'] = $candidateDetails->last_name;
//     $candidateData['email'] = $candidateDetails->email;
//     $candidateData['phone'] = $candidateDetails->contact_number;
//     $candidateData['address'] = $candidateDetails->address;
//     $candidateData['gender'] = $candidateDetails->gender;
//     $candidateData['dateofbirth'] = $candidateDetails->date_of_birth;
//     $candidateData['martialstatus'] = $candidateDetails->martial_status;
//     $candidateData['physical_challenged'] = $candidateDetails->physical_challenge;
//     $candidateData['created'] = format_date($candidateDetails->created);
//     $candidateData['status'] = $candidateDetails->status;
//     $candidateData['interview_status'] = $candidateDetails->interview_status;
//     $candidateData['interviewDetails'] = getFeedbackData($candidateDetails->id);
//     $candidateData['jobAppliedFor'] = Job::where('id', $candidateDetails->job_form_id)->value('title');

//     $data['candidateData'] = $candidateData;

//     $candidateOfferDetails = SelectedCandidate::where('candidate_id', $candidateId)->where('employer_id', $employerId)->first();

//     $candidateOfferDetailsData = [];

//     $candidateOfferDetailsData['position_name'] = $candidateOfferDetails->position_name;
//     $candidateOfferDetailsData['joining_date'] = $candidateOfferDetails->joining_date;
//     $candidateOfferDetailsData['work_location'] = $candidateOfferDetails->work_location;
//     $candidateOfferDetailsData['compensation'] = CURR." ".$candidateOfferDetails->compensation;
//     $candidateOfferDetailsData['comment'] = $candidateOfferDetails->comment;
//     $candidateOfferDetailsData['benefits'] = $candidateOfferDetails->comment;
//     $candidateOfferDetailsData['department'] = $candidateOfferDetails->comment;
//     $candidateOfferDetailsData['remaining_time'] = $remainingTime ?? 'The link has expired';
//     $candidateOfferDetailsData['employer_email'] = Employer::where('id', $employerId)->value('email_address');
    
//     $employerCompanyLogo = Employer::where('id', $employerId)->value('company_logo');
    
//     if(!empty($employerCompanyLogo)){
//         $candidateOfferDetailsData['company_logo'] = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . Employer::where('id', $employerId)->value('company_logo');
//     } else{
//         $candidateOfferDetailsData['company_logo'] = "";
//     }

//     $data['candidateOfferDetailsData'] = $candidateOfferDetailsData;

//     return Response(['response' => $data, 'message' => "", 'status' => 200], 200);
// }

    public function getOfferLetterData(Request $request)
    {
        $candidateId = $request->candidate_id;
        $employerId = $request->employer_id;
    
        $candidate = SelectedCandidate::where('candidate_id', $candidateId)->first(['onboarding_link_status', 'send_time', 'expire_time']);
        $generalSettingData = SelectedCandidate::where('candidate_id', $candidateId)->first();
    
        if (empty($generalSettingData)) {
            return Response(['response' => 'General setting not found', 'message' => 'error', 'status' => 500], 200);
        }
    
        $sendTime = $candidate->send_time;
        $offerLetterExpiry = $generalSettingData->offer_letter_expiry;
        $offerLetterExpiryValue = $generalSettingData->offer_letter_expiry_value;
    // return Response(['response' => ['offerLetterExpiry' =>$offerLetterExpiry, 'offerLetterExpiryValue' => $offerLetterExpiryValue], 'message' => 'error', 'status' => 200], 200);
    // exit();
        $expirationTime = null;
    
        // if (!empty($candidate->onboarding_link_status)) {
             $currentTime = Carbon::now();
            if ($offerLetterExpiry === 'minutes') {
                $expirationTime = Carbon::parse($sendTime)->addMinutes($offerLetterExpiryValue);
            } elseif ($offerLetterExpiry === 'hours') {
                $expirationTime = Carbon::parse($sendTime)->addHours($offerLetterExpiryValue);
            } else {
                return Response(['response' => 'Invalid expiry setting', 'message' => 'error', 'status' => 500], 200);
            }
            
            if ($currentTime->lessThanOrEqualTo($expirationTime)) {
                // Calculate total remaining time in minutes
                $remainingMinutes = $expirationTime->diffInMinutes($currentTime);
                $remainingTime = $remainingMinutes; // Total remaining time in minutes
            }
        // }
    
        $candidateDetails = CandidateJobApply::where('id', $candidateId)->first();
        $candidateData = [
            'candidate_id' => $candidateDetails->id,
            'job_id' => $candidateDetails->job_form_id,
            'first_name' => $candidateDetails->first_name,
            'last_name' => $candidateDetails->last_name,
            'email' => $candidateDetails->email,
            'phone' => $candidateDetails->contact_number,
            'address' => $candidateDetails->address,
            'gender' => $candidateDetails->gender,
            'dateofbirth' => $candidateDetails->date_of_birth,
            'martialstatus' => $candidateDetails->martial_status,
            'physical_challenged' => $candidateDetails->physical_challenge,
            'created' => format_date($candidateDetails->created),
            'status' => $candidateDetails->status,
            'interview_status' => $candidateDetails->interview_status,
            'interviewDetails' => getFeedbackData($candidateDetails->id),
            'jobAppliedFor' => Job::where('id', $candidateDetails->job_form_id)->value('title')
        ];
    
        $candidateOfferDetails = SelectedCandidate::where('candidate_id', $candidateId)->where('employer_id', $employerId)->first();
        // return Response(['response' => $candidateOfferDetails, 'message' => "", 'status' => 200], 200);
        // exit();
        $employerCompanyLogo = Employer::where('id', $employerId)->value('company_logo');
    
        $candidateOfferDetailsData = [
            'position_name' => $candidateOfferDetails->position_name,
            'joining_date' => $candidateOfferDetails->joining_date,
            'work_location' => $candidateOfferDetails->work_location,
            'compensation' => CURR . " " . $candidateOfferDetails->compensation,
            'comment' => $candidateOfferDetails->comment,
            'benefits' => $candidateOfferDetails->benefits,
            // 'department' => $candidateOfferDetails->comment,
            'remaining_time' => $expirationTime ? $expirationTime->format('Y-m-d H:i:s') : 'The link has expired',
    
            'expiration_time' => $expirationTime ? $expirationTime->timestamp : null,
            'employer_email' => Employer::where('id', $employerId)->value('email_address'),
            'company_logo' => !empty($employerCompanyLogo) ? EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $employerCompanyLogo : "",
            'offer_letter_status' => $candidateOfferDetails->offer_letter_status,
            'offer_letter_accepted' => $candidateOfferDetails->offer_letter_accepted,
        ];
        
    
        $data = [
            'candidateData' => $candidateData,
            'candidateOfferDetailsData' => $candidateOfferDetailsData
        ];
    
        return Response(['response' => $data, 'message' => "", 'status' => 200], 200);
    }



    public function changeOfferLetterStatus(Request $request)
    {
        $candidateId = $request->candidate_id;
        $employerId = $request->employer_id;
        $statusId = $request->status_id;
    
        if ($statusId == "1") {
            $updated = SelectedCandidate::where('candidate_id', $candidateId)->where('employer_id', $employerId)->update([
                'offer_letter_accepted' => 1,
            ]);
        } else {
            $updated = SelectedCandidate::where('candidate_id', $candidateId)->where('employer_id', $employerId)->update([
                'offer_letter_accepted' => 0,
            ]);
        }
    
        // Check if the update query was successful
        if ($updated) {
            return response()->json(['response' => '', 'message' => 'Offer letter status changed successfully', 'status' => 200], 200);
        } else {
            return response()->json(['response' => '', 'message' => 'Failed to change offer letter status', 'status' => 500], 500);
        }
    }
    
    public function showDocumentDetails(Request $request){
        $candidateId = $request->candidate_id;
        $employerId = $request->employer_id;
        $jobId = $request->job_id;
        
        $documentData = SelectedCandidate::where('candidate_id', $candidateId)->where('employer_id', $employerId)
                                           ->where('job_id', $jobId)->first();
        $data = array();
        $data['identification'] = $documentData->identification;
        $data['protfolio'] = $documentData->protfolio;
        
        return Response(['response' => $data, 'message' => 'success', 'status' => 200], 200);
    }
    
    
    public function get_candidate_details_after_onboarding(Request $request){
        $candidateId = $request->candidate_id;
        
        //for old values
        $candidateJobApplyData = CandidateJobApply::where('id', $candidateId)->first();
        $oldEducationData = json_decode($candidateJobApplyData->education_details, true);
        $oldExperienceData = json_decode($candidateJobApplyData->experience_details, true);
        
       
        
        //for new values
        $selectedCandidateData = SelectedCandidate::where('candidate_id', $candidateId)->first();
        $educationData = CandidateEducation::where('candidate_job_apply_id', $candidateId)->get();
        $experienceData = CandidateExperience::where('candidate_job_apply_id', $candidateId)->get();
        
        //  return Response(['response' => ['educationData' => $educationData, 'experienceData' => $experienceData], 'message' => 'test', 'status' => 200], 200);
        // exit();
        
        $data = [];
        
        // Gender mapping
        $genderMap = [
            1 => 'Male',
            2 => 'Female',
            3 => 'Other',
        ];
        
        // marital status mapping
        $maritalStausMap = [
            1 => 'Single',
            2 => 'Married',
            3 => 'Divorced'
        ];
        
        // physically challenged mapping
        $physicallyChallengedMap = [
            1 => 'Yes',
            2 => 'No',
            3 => 'Not To Say'
        ];
        
        //name
        $data['name'] = $selectedCandidateData->name;
        
        //gender
        if($candidateJobApplyData->gender != $selectedCandidateData->gender){
            $data['gender'] = $genderMap[$selectedCandidateData->gender] ?? 'unknown';
            $data['gender_old'] = $genderMap[$candidateJobApplyData->gender] ?? 'unknown';
        } else{
            $data['gender'] = $genderMap[$selectedCandidateData->gender] ?? 'unknown';
        }
        
        //email
        if($candidateJobApplyData->email != $selectedCandidateData->email_address) {
            $data['email'] = $selectedCandidateData->email_address;
            $data['email_old'] = $candidateJobApplyData->email;
        } else{
            $data['email'] = $selectedCandidateData->email_address;
        }
        
        //contact number
        if($candidateJobApplyData->contact_number != $selectedCandidateData->phone_number){
            $data['phone_number'] = $selectedCandidateData->phone_number;
            $data['phone_number_old'] = $candidateJobApplyData->contact_number;
        } else{
            $data['phone_number'] = $selectedCandidateData->phone_number;
        }
        
        // Date of Birth
        $dob = $candidateJobApplyData->date_of_birth;
        $dobFormattedOld = (new \DateTime($dob))->format('d M. Y');
        $dobFormattedNew = (new \DateTime($selectedCandidateData->date_of_birth))->format('d M. Y');
        
        if ($dobFormattedOld != $dobFormattedNew) {
            $data['date_of_birth'] = $dobFormattedNew;       
            $data['date_of_birth_old'] = $dobFormattedOld;   
        } else {
            $data['date_of_birth'] = $dobFormattedNew;       
        }

        
        //marital status
        if($candidateJobApplyData->martial_status  != $selectedCandidateData->marital_status){
            $data['marital_status'] = $maritalStausMap[$selectedCandidateData->marital_status] ?? 'unknown';
            $data['marital_status_old'] = $maritalStausMap[$candidateJobApplyData->martial_status] ?? 'unknown';
        } else{
            $data['marital_status'] = $maritalStausMap[$selectedCandidateData->marital_status] ?? 'unknown';
        }
        
        //physically chanllegend
        if($candidateJobApplyData->physically_challenged  != $selectedCandidateData->physically_challenged){
            $data['physically_challenged'] = $physicallyChallengedMap[$selectedCandidateData->physically_challenged] ?? 'unknown';
            $data['physically_challenged_old'] = $physicallyChallengedMap[$candidateJobApplyData->physically_challenged] ?? 'unknown';
        } else{
            $data['physically_challenged'] = $physicallyChallengedMap[$selectedCandidateData->physically_challenged] ?? 'unknown';
        }
        
        //profile image
        $data['profile_img'] = DISPLAY_FULL_PROFILE_IMAGE_PATH . $candidateJobApplyData->profile_img;
        
        //cv
        $data['document_cv'] = DISPLAY_RESUME_PATH . $candidateJobApplyData->document_cv;
        
        //current_address
        $data['current_address'] = $selectedCandidateData->current_address;
        $data['permanent_address'] = $selectedCandidateData->permanent_address;
        
        
        //for education
        
        if (!empty($oldEducationData) && !empty($educationData)) {
            foreach ($educationData as $index => $newData) {
                $oldData = $oldEducationData[$index] ?? [];
        
                $education = [];
                
                // Fetch qualification names
                $newQualificationName = !empty($newData['qualification_id']) 
                    ? Qualification::where('id', $newData['qualification_id'])->value('qualification_name') 
                    : 'unknown';
                $oldQualificationName = !empty($oldData['qualification_id']) 
                    ? Qualification::where('id', $oldData['qualification_id'])->value('qualification_name') 
                    : 'unknown';
        
                // qualification_id
                if (!empty($oldData) && $oldData['qualification_id'] != $newData['qualification_id']) {
                    $education['qualification_id'] = $newData['qualification_id'];
                    $education['qualification_id_old'] = $oldData['qualification_id'];
                    $education['qualification_name'] = $newQualificationName;
                    $education['qualification_name_old'] = $oldQualificationName;
                } else {
                    $education['qualification_id'] = $newData['qualification_id'] ?? 'unknown';
                    $education['qualification_name'] = $newQualificationName;
                }
        
                // course
                if (!empty($oldData) && $oldData['course'] != $newData['course']) {
                    $education['course'] = $newData['course'];
                    $education['course_old'] = $oldData['course'];
                } else {
                    $education['course'] = $newData['course'] ?? 'unknown';
                }
        
                // school_college
                if (!empty($oldData) && $oldData['school_college'] != $newData['school_college']) {
                    $education['school_college'] = $newData['school_college'];
                    $education['school_college_old'] = $oldData['school_college'];
                } else {
                    $education['school_college'] = $newData['school_college'] ?? 'unknown';
                }
        
                // city
                if (!empty($oldData) && $oldData['city'] != $newData['city']) {
                    $education['city'] = $newData['city'];
                    $education['city_old'] = $oldData['city'];
                } else {
                    $education['city'] = $newData['city'] ?? 'unknown';
                }
        
                // university_board
                if (!empty($oldData) && $oldData['university_board'] != $newData['university_board']) {
                    $education['university_board'] = $newData['university_board'];
                    $education['university_board_old'] = $oldData['university_board'];
                } else {
                    $education['university_board'] = $newData['university_board'] ?? 'unknown';
                }
        
                // passing_year
                if (!empty($oldData) && $oldData['passing_year'] != $newData['passing_year']) {
                    $education['passing_year'] = $newData['passing_year'];
                    $education['passing_year_old'] = $oldData['passing_year'];
                } else {
                    $education['passing_year'] = $newData['passing_year'] ?? 'unknown';
                }
        
                // percentage
                $education['percentage'] = $newData['percentage'] ?? 'unknown';
        
                // document
                $education['document'] = DISPLAY_CANDIDATE_ACADEMIC_DOCUMENTS_PATH . ($newData['documents'] ?? '');
        
                $data['education'][] = $education; 
            }
        } else {
            $data['education'] = [];
        }
        
        
        // for experience
        
        if (!empty($oldExperienceData) && !empty($experienceData)) {
            foreach ($experienceData as $index => $newData) {
                $oldData = $oldExperienceData[$index] ?? []; 
        
                $experience = []; 
                
                // Fetch designation names
                $newDesignationName = !empty($newData['designation']) 
                    ? Skill::where('id', $newData['designation'])->where('type', 'Designation')->value('skill_name') 
                    : 'unknown';
                $oldDesignationName = !empty($oldData['designation']) 
                    ? Skill::where('id', $oldData['designation'])->where('type', 'Designation')->value('skill_name') 
                    : 'unknown';
        
                // start_date
                if (!empty($oldData) && $oldData['startDate'] != $newData['start_date']) {
                    $experience['start_date'] = $newData['start_date'];
                    $experience['start_date_old'] = $oldData['startDate'];
                } else {
                    $experience['start_date'] = $newData['start_date'] ?? 'unknown';
                }
        
                // end_date
                if (!empty($oldData) && $oldData['endDate'] != $newData['end_date']) {
                    $experience['end_date'] = $newData['end_date'];
                    $experience['end_date_old'] = $oldData['endDate'];
                } else {
                    $experience['end_date'] = $newData['end_date'] ?? 'unknown';
                }
        
                // organisation_name
                if (!empty($oldData) && $oldData['organisation_name'] != $newData['organisation_name']) {
                    $experience['organisation_name'] = $newData['organisation_name'];
                    $experience['organisation_name_old'] = $oldData['organisation_name'];
                } else {
                    $experience['organisation_name'] = $newData['organisation_name'] ?? 'unknown';
                }
        
                // designation
                if (!empty($oldData) && $oldData['designation'] != $newData['designation']) {
                    $experience['designation'] = $newData['designation'];
                    $experience['designation_old'] = $oldData['designation'];
                    $experience['designation_name'] = $newDesignationName;
                    $experience['designation_name_old'] = $oldDesignationName;
                } else {
                    $experience['designation'] = $newData['designation'] ?? 'unknown';
                    $experience['designation_name'] = $newDesignationName;
                }
        
                // reason_of_leaving
                if (!empty($oldData) && $oldData['reason_of_leaving'] != $newData['reason_of_leaving']) {
                    $experience['reason_of_leaving'] = $newData['reason_of_leaving'];
                    $experience['reason_of_leaving_old'] = $oldData['reason_of_leaving'];
                } else {
                    $experience['reason_of_leaving'] = $newData['reason_of_leaving'] ?? 'unknown';
                }

        
                // document
                $experience['documents'] = DISPLAY_CANDIDATE_ACADEMIC_DOCUMENTS_PATH . ($newData['documents'] ?? '');
        
                $data['experience'][] = $experience;
            }
        } else {
            $data['experience'] = [];
        }
        
        
        //other documents
        $data['identification'] = DISPLAY_CANDIDATE_DOCUMENTS_PATH . $selectedCandidateData->identification;
        $data['portfolio'] = $selectedCandidateData->portfolio;
        
        $certificateData = Certificate::where('candidate_id', $candidateId)->first();
        $data['certificate'] = DISPLAY_CANDIDATE_CERTIFICATE_PATH . $certificateData->certificates;
        
        //preferences
        
        
        $data['preference_data'] = json_decode($selectedCandidateData->preference_data, true);
        
        // $data['preferred_work_location'] = $selectedCandidateData->preferred_work_location;
        // $data['relocation_status'] = $selectedCandidateData->relocation_status;
        // $data['preferred_skills'] = $selectedCandidateData->preferred_skills;
        // $data['preferred_developing_skills'] = $selectedCandidateData->preferred_developing_skills;
        // $data['workplace_preference'] = $selectedCandidateData->workplace_preference;
        // $data['work_travel_status'] = $selectedCandidateData->work_travel_status;
        // $data['special_requirements'] = $selectedCandidateData->special_requirements;
        // $data['additional_information'] = $selectedCandidateData->additional_information;

        
        return Response(['response' => $data, 'message' => 'success', 'status' => 200], 200);
        
        
    }
    
    // public function setup_preferences_setting(Request $request){
    //     $employerId = $request->employer_id;
        
    //     $validator = Validator::make($request->all(), [
    //         // 'preferred_work_location' => 'required',
    //         // 'relocation_status' => 'required',
    //         // 'preferred_skills' => 'required',
    //         // 'preferred_developing_skills' => 'required',
    //         // 'workplace_preference' => 'required',
    //         // 'work_travel_status' => 'required',
    //         // 'special_requirements' => 'required',
    //         // 'additional_information' => 'required'
    //     ]);

    //     if($validator->fails()){
    //         return Response(['response' => $validator->errors(), 'status' => 500], 200);
    //     } else {
            
    //         $savePreferences = Preference::insert([
    //             'employer_id' => $employerId,
    //             'question' => $request->question,
    //             'values' => $request->value_type,
    //             'options' => $request->options,
    //         ]);
            
    //         return Response(['response' => '', 'message' => 'Preference Details Saved Successfully', 'status' => 200], 200);
    //     }
        
    // }
    
    
    // public function setup_preferences_setting(Request $request)
    // {
    //     $employerId = $request->employer_id;
    
    //     $validator = Validator::make($request->all(), [
    //         // Validation rules for your fields
    //         // Uncomment and adjust as needed
    //         // 'preferred_work_location' => 'required',
    //         // 'relocation_status' => 'required',
    //         // 'preferred_skills' => 'required',
    //         // 'preferred_developing_skills' => 'required',
    //         // 'workplace_preference' => 'required',
    //         // 'work_travel_status' => 'required',
    //         // 'special_requirements' => 'required',
    //         // 'additional_information' => 'required'
    //     ]);
    
    //     if ($validator->fails()) {
    //         return Response(['response' => $validator->errors(), 'status' => 500], 200);
    //     } else {
    //         $preferences = $request->input('preferences');
    //         $data = [];
            
    //         foreach ($preferences as $preference) {
    //             $data[] = [
    //                 'employer_id' => $employerId,
    //                 'question' => $preference['question'] ?? null, 
    //                 'values' => $preference['value_type'] ?? null, 
    //                 'options' => $preference['options'] ?? null, 
    //             ];
    //         }
    
    //         Preference::insert($data);
    
    //         return Response(['response' => '', 'message' => 'Preference Details Saved Successfully', 'status' => 200], 200);
    //     }
    // }
    
    
    // public function setup_preferences_setting(Request $request)
    // {
    //     $employerId = $request->employer_id;
    
    //     $validator = Validator::make($request->all(), [
    //         // 'preferences' => 'required|array',
    //         // 'preferences.*.question' => 'required|string',
    //         // 'preferences.*.value_type' => 'required|string',
    //         // 'preferences.*.options' => 'required|array',
    //     ]);
    
    //     if ($validator->fails()) {
    //         return response(['response' => $validator->errors(), 'status' => 500], 200);
    //     }
    
    //     $preferences = $request->input('preferences');
    //     $data = [];
    
    //     foreach ($preferences as $preference) {
    //         $data[] = [
    //             'employer_id' => $employerId,
    //             'question' => $preference['question'],
    //             'values' => $preference['value_type'],
    //             'options' => json_encode($preference['options']),
    //         ];
    //     }
    
    //     Preference::insert($data);
    
    //     return response(['response' => '', 'message' => 'Preference Details Saved Successfully', 'status' => 200], 200);
    // }
    
    
    // public function setup_preferences_setting(Request $request)
    // {
    //     $employerId = $request->employer_id;
    
    //     // Validation for input data
    //     $validator = Validator::make($request->all(), [
    //         // 'preferences' => 'sometimes|array',
    //         // 'preferences.*.question' => 'required_with:preferences|string',
    //         // 'preferences.*.value_type' => 'required_with:preferences|string',
    //         // 'preferences.*.options' => 'required_with:preferences|array',
    //     ]);
    
    //     if ($validator->fails()) {
    //         return response(['response' => $validator->errors(), 'status' => 500], 200);
    //     }
    
    //     // Save new preferences if provided
    //     if ($request->has('preferences')) {
    //         $preferences = $request->input('preferences');
    //         $data = [];
    
    //         foreach ($preferences as $preference) {
    //             $data[] = [
    //                 'employer_id' => $employerId,
    //                 'question' => $preference['question'],
    //                 'values' => $preference['value_type'],
    //                 'options' => json_encode($preference['options']),
    //                 'created_at' => now(),
    //                 'updated_at' => now(),
    //             ];
    //         }
    
    //         // Insert new preferences in bulk
    //         Preference::insert($data);
    //     }
    
    //     // Fetch existing preferences for the employer
    //     $existingPreferences = Preference::where('employer_id', $employerId)
    //         ->get(['id', 'question', 'values as value_type', 'options'])
    //         ->map(function ($preference) {
    //             // Decode options back to an array for response
    //             $preference->options = json_decode($preference->options, true);
    //             return $preference;
    //         });
    
    //     return response([
    //         'response' => [
    //             'existing_preferences' => $existingPreferences,
    //         ],
    //         'message' => 'Preferences processed successfully.',
    //         'status' => 200,
    //     ], 200);
    // }
    
    
    public function setup_preferences_setting(Request $request)
    {
        $employerId = $request->employer_id;
    
        // Validation for input data
        $validator = Validator::make($request->all(), [
            // 'preferences' => 'sometimes|array',
            // 'preferences.*.id' => 'nullable|integer|exists:tbl_preferences,id',
            // 'preferences.*.question' => 'required_with:preferences|string',
            // 'preferences.*.value_type' => 'required_with:preferences|string',
            // 'preferences.*.options' => 'required_with:preferences|array',
        ]);
    
        if ($validator->fails()) {
            return response(['response' => $validator->errors(), 'status' => 500], 200);
        }
    
        // Handle preferences input
        if ($request->has('preferences')) {
            $preferences = $request->input('preferences');
    
            foreach ($preferences as $preference) {
                if (isset($preference['id'])) {
                    // Update existing preference
                    Preference::where('id', $preference['id'])
                        ->update([
                            'question' => $preference['question'],
                            'values' => $preference['value_type'],
                            'options' => json_encode($preference['options']),
                        ]);
                } else {
                    // Insert new preference
                    Preference::create([
                        'employer_id' => $employerId,
                        'question' => $preference['question'],
                        'values' => $preference['value_type'],
                        'options' => json_encode($preference['options']),
                    ]);
                }
            }
        }
    
        // Fetch updated preferences for the employer
        $existingPreferences = Preference::where('employer_id', $employerId)
            ->get(['id', 'question', 'values as value_type', 'options'])
            ->map(function ($preference) {
                // Decode options back to an array for response
                $preference->options = json_decode($preference->options, true);
                return $preference;
            });
    
        return response([
            'response' => [
                'existing_preferences' => $existingPreferences,
            ],
            'message' => 'Preferences processed successfully.',
            'status' => 200,
        ], 200);
    }
    
    
    public function remove_preference_section(Request $request)
    {
        $employerId = $request->employer_id;
        $id = $request->id;
    
        $preference = Preference::where('employer_id', $employerId)->where('id', $id)->first();
    
        if ($preference) {
            $preference->delete();
            return response([
                'response' => '',
                'message' => 'Preference section removed successfully.',
                'status' => 200,
            ], 200);
        }
    
        return response([
            'response' => '',
            'message' => 'Preference not found or already removed.',
            'status' => 500,
        ], 200);
    }







    

}