<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\CandidateJobApply;
use App\Models\StatusAttributes;
use Illuminate\Http\Request;
use App\Models\Process;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Models\CandidateFeedback;
use App\Models\Staff;
use App\Models\Job;
use App\Models\Employer;
use App\Models\OfferDraftData;
use App\Models\CandidateInterviewJourney;
use App\Models\CandidateInterviewStatus;
use App\Models\CandidateInterviewSchedule;
use App\Models\CandidateEducation;
use App\Models\CandidateExperience;
use App\Models\Qualification;
use App\Models\Skill;
use App\Models\SelectedCandidate;
use App\Models\Candidate;
use App\Models\CandidateProfile;
use App\Models\Category;
use App\Models\Industry;
use App\Models\Notification;
use App\Models\SavedJob;
use Carbon\Carbon;
use Mail;
use App\Models\EmailTemplate;
use App\Mail\SendMail;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\URL;
use App\Models\PasswordReset;

class CandidatesController extends Controller
{
    
    public function candidateLogin(Request $request) {
        if (!empty($request->all())) {
            $validator = Validator::make($request->all(), [
                'email' => 'required|email',
                'password' => 'required',
            ]);
    
            if ($validator->fails()) {
                return response()->json(['response' => $validator->errors(), 'status' => 500], 200);
            }
    
            $user = Candidate::where('employer_id', $request->employer_id)->where('email', $request->email)->first();
            // return Response(['response' => $user, 'status' => 200], 200);
            // exit();
    
            if ($user && Hash::check($request->password, $user->password)) {
                $token = $user->createToken('MyApp')->plainTextToken;
                $profileImage = !empty($user->profile_img) ? DISPLAY_FULL_PROFILE_IMAGE_PATH . $user->profile_img : '';
    
                return Response([
                    'success' => true,
                    'token' => $token,
                    'user' => $user,
                    'profile_image' => $profileImage,
                    'userType' => "Candidate",
                    'message' => 'Candidate logged in successfully',
                    'status' => 200
                ], 200);
            } else {
                return Response([
                    'success' => false,
                    'message' => 'Invalid credentials',
                    'status' => 500
                ], 200);
            }
        }
    }
    
    // Direct login without employer id
    public function UserCandidateLogin(Request $request) {
        if (!empty($request->all())) {
            $validator = Validator::make($request->all(), [
                'email' => 'required|email',
                'password' => 'required',
            ]);
    
            if ($validator->fails()) {
                return response()->json(['response' => $validator->errors(), 'status' => 500], 200);
            }
    
            $user = Candidate::where('email', $request->email)->first();
            // return Response(['response' => $user, 'status' => 200], 200);
            // exit();
    
            if ($user && Hash::check($request->password, $user->password)) {
                $token = $user->createToken('MyApp')->plainTextToken;
                // $profileImage = !empty($user->profile_img) ? DISPLAY_FULL_PROFILE_IMAGE_PATH . $user->profile_img : '';
    
                return Response([
                    'success' => true,
                    'token' => $token,
                    'user' => $user,
                    // 'profile_image' => $profileImage,
                    'userType' => "Candidate",
                    'message' => 'Candidate logged in successfully',
                    'status' => 200
                ], 200);
            } else {
                return Response([
                    'success' => false,
                    'message' => 'Invalid credentials',
                    'status' => 500
                ], 200);
            }
        }
    }
    
    public function candidateRegister(Request $request)
    {
        if (!empty($request->all())) {
            $validator = Validator::make($request->all(), [
                'first_name'     => 'required|string|max:255',
                'last_name'=> 'required|string|max:255',
                'email'    => 'required|email|unique:candidates,email',
                'password' => 'required|min:6',
                'contact_number'    => 'nullable|string|max:20',
                // 'profile_img' => 'nullable|image|mimes:jpg,jpeg,png' // Optional image upload
            ]);
    
            if ($validator->fails()) {
                return Response([
                    'response' => $validator->errors()->first(),
                    'status' => 500
                ], 200);
                exit(); 
            }
    
            // Handle profile image upload
            // $profileImageName = null;
            // if ($request->hasFile('profile_img')) {
            //     $image = $request->file('profile_img');
            //     $profileImageName = time() . '_' . rand(1000, 9999) . '.' . $image->getClientOriginalExtension();
            //     $image->move(public_path('uploads/profile/'), $profileImageName);
            // }
    
            // Create candidate
            $candidate = Candidate::create([
                'first_name'     => $request->first_name,
                'last_name' => $request->last_name,
                'email'    => $request->email,
                'password' => Hash::make($request->password),
                'contact_number'    => $request->contact_number,
                // 'profile_img' => $profileImageName,
            ]);
    
            // $token = $candidate->createToken('MyApp')->plainTextToken;
            // $profileImage = !empty($candidate->profile_img) ? DISPLAY_FULL_PROFILE_IMAGE_PATH . $candidate->profile_img : '';
    
            return Response([
                'success' => true,
                // 'token' => $token,
                'user' => $candidate,
                // 'profile_image' => $profileImage,
                'userType' => 'Candidate',
                'message' => 'Candidate registered successfully',
                'status' => 200
            ], 200);
        }
    }

    
    public function candidateDashboard(Request $request){
        $currentUser = Auth::user()->id;
        $candidateRecord = Candidate::where('id', $currentUser)->first();
        
        // $candidateData = [
        //     'first_name' => $candidateRecord->first_name,
        //     'last_name' => $candidateRecord->last_name,
        //     'profile_image' => $candidateRecord->profile_img,
        //     ''
        //     ]
            
        $appliedJobs = CandidateJobApply::where('employer_id', $request->employer_id)->where('email', $candidateRecord->email)->get();
        $appliedJobsData = [];
        
        foreach ($appliedJobs as $key => $jobApply) {
            $job = Job::find($jobApply->job_form_id); // Fetch job details using job_form_id
            $employerCompanyName = Employer::where('id', $jobApply->employer_id)->value('company_name');
            $categoryName = Category::where('id', $job->category_id)->value('category_name');
            $industryName = Industry::where('id', $job->industry)->value('industry_name');
            
            // Check if job->skill is an integer (single skill ID)
            if (is_numeric($job->skill)) {
                $skillIds = [$job->skill]; // Convert single skill ID to array
            } elseif (is_string($job->skill) && str_contains($job->skill, ',')) {
                $skillIds = explode(',', $job->skill); // Convert comma-separated string to array
            } elseif (is_string($job->skill)) {
                $decodedSkills = json_decode($job->skill, true);
                $skillIds = is_array($decodedSkills) ? $decodedSkills : [$job->skill];
            } else {
                $skillIds = [];
            } 
            $skillNames = Skill::whereIn('id', $skillIds)->pluck('skill_name')->toArray();
            $qualificationName = Qualification::where('id', $job->qualification)->value('qualification_name');
            $worktypeData = $GLOBALS['worktype'];
            
            
        
            if ($job) {
                $appliedJobsData[$key]['company_name'] = $employerCompanyName;
                $appliedJobsData[$key]['job_name'] = $job->title;
                $appliedJobsData[$key]['min_exp'] = $job->min_exp;
                $appliedJobsData[$key]['max_exp'] = $job->max_exp;
                $appliedJobsData[$key]['location'] = $job->location;
                $appliedJobsData[$key]['job_created_at'] = $job->created_at->format('d-m-Y');
                
                $workTypeMapping = [
                    '1' => 'Full Time',
                    '2' => 'Part Time',
                    '3' => 'Casual',
                    '4' => 'Seasonal',
                    '5' => 'Fixed Term',
                ];
                $workTypeValue = $job->work_type;
                $workTypeString = $workTypeMapping[$workTypeValue] ?? 'Unknown';
                $appliedJobsData[$key]['work_type'] = $workTypeString;
                
                // $appliedJobsData[$key]['work_type'] = $job->work_type;
                
                $appliedJobsData[$key]['min_salary'] = CURR.$job->min_salary;
                $appliedJobsData[$key]['max_salary'] = CURR.$job->max_salary;
                $appliedJobsData[$key]['skill'] = !empty($skillNames) ? implode(', ', $skillNames) : "Not Found";
                $appliedJobsData[$key]['category'] = $categoryName ? $categoryName : "Not available";
                
                $designationName = Skill::where('type', 'Designation')->where('id', $job->designation)->value('skill_name');
                if(!empty($designationName)){
                    $appliedJobsData[$key]['designation'] = $designationName;
                } else{
                    $appliedJobsData[$key]['designation'] = $job->designation;
                }
                
                // $appliedJobsData[$key]['designation'] = $job->designation;
                $appliedJobsData[$key]['job_description'] = $job->description;
                $appliedJobsData[$key]['slug'] = $job->slug;
                $appliedJobsData[$key]['industry'] = $industryName;
                $appliedJobsData[$key]['qualification'] = $qualificationName;
                // $appliedJobsData[$key]['process_order_ids'] = $job->process_order_ids;
                
                $processOrderIds = $job->process_order_ids; // The comma-separated string
                $processOrderArray = explode(',', $job->process_order_ids); // Convert the string to an array
                
                $processOrders = array_map(function ($processOrderArray) {
                    return getProcessOrderName($processOrderArray); // Call the function for each process order ID
                }, $processOrderArray);
                
                $appliedJobsData[$key]['process_order_ids'] = implode(', ', $processOrders); // Join the results back into a string
                
            }
        }
        
        $personalDetails = Candidate::where('employer_id', $request->employer_id)
            ->where('email', $candidateRecord->email)
            ->first();
        
        if ($personalDetails) {  
            // Fixing gender mapping
            $genderText = 'Other';
            if ($personalDetails->gender == 1) {
                $genderText = 'Male';
            } else if ($personalDetails->gender == 2) {
                $genderText = 'Female';
            }
        
            // Fixing marital status mapping
            $maritalText = 'N/A';
            if ($personalDetails->martial_status == 1) {
                $maritalText = 'Single';
            } else if ($personalDetails->martial_status == 2) {
                $maritalText = 'Married';
            } else if ($personalDetails->martial_status == 3) {
                $maritalText = 'Divorced';
            }
        
            // Fixing physically challenged mapping
            $physicallyText = 'N/A';
            if ($personalDetails->physically_challenged == 1) {  // Fixed typo here
                $physicallyText = 'Yes';
            } else if ($personalDetails->physically_challenged == 2) {  // Fixed typo here
                $physicallyText = 'No';
            } else if ($personalDetails->physically_challenged == 3) {  // Fixed typo here
                $physicallyText = 'Prefer not to say';
            }
        
            // Assigning values
            $personalDetailsData = [
                'id' => $personalDetails->id,
                'first_name' => $personalDetails->first_name,
                'middle_name' => $personalDetails->middle_name ?? null, // Fixed typo
                'last_name' => $personalDetails->last_name,
                'email' => $personalDetails->email,
                'contact_number' => $personalDetails->contact_number,
                'date_of_birth' => date('d M Y', strtotime($personalDetails->date_of_birth)),
                'gender' => $genderText,
                'marital_status' => $maritalText, 
                'physically_challenged' => $physicallyText, 
                'document_cv' => DISPLAY_RESUME_PATH.$personalDetails->document_cv,
                'profile_img' => DISPLAY_FULL_PROFILE_IMAGE_PATH.$personalDetails->profile_img,
            ];
        } else {
            $personalDetailsData = []; // No record found
        }
        return Response(['response' => ['appliedJobs' => $appliedJobsData, 'personalDetailsData' => $personalDetailsData], 'message' => '', 'status' => 200], 200);
    }
    
    
    public function listing(Request $request) {
        
        $currentUser = Auth::user()->id;
        $adminCheck = Admin::where('id', $currentUser)->first();
        $employerCheck = Employer::where('id', $currentUser)->first();
        $staffCheck = Staff::where('id', $currentUser)->first();
        
        // return Response(['response' => $currentUser, 'status' => 200], 200);
        //     exit();
        
        if (!empty($adminCheck)) {
            $candidates = CandidateJobApply::all();
            $candidateData = array();

            foreach($candidates as $key => $value) {
                
                $employerName = Employer::where('id', $value->employer_id)
                    ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                    ->first();
                $staffName = Staff::where('id', $value->staff_id)
                    ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                    ->first();

                $candidateData[$key]['candidate_id'] = $value->id;
                $candidateData[$key]['job_id'] = $value->job_form_id;
                $candidateData[$key]['first_name'] = $value->first_name;
                $candidateData[$key]['last_name'] = $value->last_name;
                $candidateData[$key]['email'] = $value->email;
                $candidateData[$key]['phone'] = $value->contact_number;
                $candidateData[$key]['address'] = $value->address;
                $candidateData[$key]['gender'] = $value->gender;
                $candidateData[$key]['dateofbirth'] = date('d M Y',strtotime($value->date_of_birth));
                $candidateData[$key]['martialstatus'] = $value->martial_status;
                $candidateData[$key]['physical_challenged'] = $value->physical_challenge;
                $candidateData[$key]['created'] = date('d M Y',strtotime($value->created));
                $candidateData[$key]['status'] = $value->status;
                $candidateData[$key]['interview_status'] = $value->interview_status;
                $candidateData[$key]['interviewDetails'] = getFeedbackData($value->id);
                $candidateData[$key]['jobAppliedFor'] = Job::where('id',$value->job_form_id)->value('title');
            }
            
            $status = StatusAttributes::where('status', 1)->get();
        
            $data['candidatesData'] = $candidateData;
            $data['statusList'] = $status;
            
            
            $process = Process::where('status', 1)->get();
            $data['processList'] = $process;
    
            $user = Admin::where('id', '!=', 1)->get();
            $data['user'] = $user;
    
            return Response(['response' => $data], 200);
        } else if(!empty($employerCheck)) {
            $candidates = CandidateJobApply::where('employer_id', $currentUser)->orderBy('id', 'desc')->get();
            
            // return Response(['response' => $candidates, 'status' => 200], 200);
            // exit();
            $candidateData = array();

            foreach($candidates as $key => $value) {
                
                
                $interviewDetails = CandidateInterviewSchedule::where('candidate_id', $value->id)->orderBy('created_at', 'desc')->first();

                $processName = $interviewDetails ? Process::where('id', $interviewDetails->process_id)->value('process_name') ?? '' : '';
                $CompletionStatus = $interviewDetails->interview_completion_status ?? '';
                
                if($CompletionStatus == 1){
                    $interviewCompletionStatus = 'Completed';
                } else{
                    $interviewCompletionStatus = 'Not Completed';
                }
                
                // return response(['response' => $processName, 'message' => '', 'status' => 200], 200);
                // exit();
                
                
                $candidateData[$key]['additional_data'] = $value->custom_fields_data ? json_decode($value->custom_fields_data, true) : [];
                
                $employerRecord = Employer::where('id', $value->employer_id)
                    ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                    ->first();
                if(!empty($employerRecord)){
                    $employerName = $employerRecord->full_name;
                }else {
                    $employerName = "Not Available";
                }
                $staffRecord = Staff::where('id', $value->staff_id)
                    ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                    ->first();
                    
                if(!empty($staffRecord)){
                    $staffName = $staffRecord->full_name;
                }else {
                    $staffName = "Not Available";
                }
                    
                $candidateData[$key]['latest_interview_status'] = [
                    'process_name' => $processName,
                    'completion_status' => $interviewCompletionStatus
                ];
                $candidateData[$key]['candidate_id'] = $value->id;
                $candidateData[$key]['id'] = $value->id;
                $candidateData[$key]['job_id'] = $value->job_form_id;
                $candidateData[$key]['first_name'] = $value->first_name;
                $candidateData[$key]['middle_name'] = $value->middle_name;
                $candidateData[$key]['last_name'] = $value->last_name;
                    if($value->gender == 1){
                        $candidateData[$key]['gender'] = "Male";
                    } else if($value->gender == 2){
                        $candidateData[$key]['gender'] = "Female";
                    }else if($value->gender == 3){
                        $candidateData[$key]['gender'] = "Other";
                    } else{
                        $candidateData[$key]['gender'] = "";
                    }
                    if(!empty($value->profile_img)){
                        $candidateData[$key]['profile_image'] = DISPLAY_FULL_PROFILE_IMAGE_PATH.$value->profile_img;
                    }else{
                        $candidateData[$key]['profile_image'] = "";
                    }
                    if(!empty($value->document_cv)){
                        $candidateData[$key]['cv_document'] = DISPLAY_RESUME_PATH.$value->document_cv;
                    }else{
                        $candidateData[$key]['cv_document'] = "";
                    }
                    $candidateData[$key]['email_address'] = $value->email;
                    $candidateData[$key]['contact'] = $value->contact_number;
                    
                    if(!empty($value->date_of_birth)){
                         $candidateData[$key]['date_of_birth'] = date('d M Y',strtotime($value->date_of_birth));
                    } else{
                         $candidateData[$key]['date_of_birth'] = "";
                    }
                    
                   
                    if($value->martial_status == 1){
                        $candidateData[$key]['martial_status'] = "Single";
                    } else if($value->martial_status == 2){
                        $candidateData[$key]['martial_status'] = "Married";
                    } else if($value->martial_status == 3){
                        $candidateData[$key]['martial_status'] = "Divorced";
                    }else{
                        $candidateData[$key]['martial_status'] = "N/A";
                    }
                    if($value->physically_challenged == 1){
                        $candidateData[$key]['physically_challenged'] = "Yes";
                    } else if($value->physically_challenged == 2){
                        $candidateData[$key]['physically_challenged'] = "No";
                    } else if($value->physically_challenged == 3){
                        $candidateData[$key]['physically_challenged'] = "Prefer not to say";
                    }else{
                        $candidateData[$key]['physically_challenged'] = "N/A";
                    }
                    $candidateData[$key]['address'] = $value->address;
                    $candidateData[$key]['applied_date'] = date('d M Y',strtotime($value->created_at));
                    $candidateData[$key]['interview_status'] = $value->interview_status;
                    
                    $candidateData[$key]['cover_letter_title'] = $value->cover_letter_title ?? "N/A";
                    $candidateData[$key]['cover_letter_description'] = $value->cover_letter_description ?? "N/A";
                    $candidateData[$key]['general_application_additional_data'] = json_decode($value->candidate_general_application_data);
                    
                
                $jobName = Job::where('id',$value->job_form_id)->value('title');
                if(!empty($jobName)){
                    $candidateData[$key]['jobAppliedFor'] = $jobName;
                } else{
                    $candidateData[$key]['jobAppliedFor'] = "Job not available";
                }
                
                $education = CandidateEducation::where('candidate_job_apply_id', $value->id)->get();
                $educationData = array();
                foreach ($education as $eduKey => $eduValue) {
                    $educationData[$eduKey]['id'] = $eduValue->id;
                    // $educationData[$eduKey]['qualification_id'] = Qualification::find($eduValue->qualification_id)->qualification_name;
                        
                    $qualificationName = Qualification::where('id', $eduValue->qualification_id)->value('qualification_name');
                    if(!empty($qualificationName)){
                        $educationData[$eduKey]['qualification_id'] = $qualificationName;
                    } else{
                        $educationData[$eduKey]['qualification_id'] = $eduValue->designation;
                    }
                        
                    $educationData[$eduKey]['course'] = $eduValue->course;
                    $educationData[$eduKey]['school_college'] = $eduValue->school_college;
                    $educationData[$eduKey]['city'] = $eduValue->city;
                    $educationData[$eduKey]['university_board'] = $eduValue->university_board;
                    $educationData[$eduKey]['passing_year'] = $eduValue->passing_year;
                }
                $candidateData[$key]['education'] = $educationData;
        
                $experience = CandidateExperience::where('candidate_job_apply_id', $value->id)->get();
                $experienceData = array();
                foreach ($experience as $expKey => $expValue) {
                    $experienceData[$expKey]['id'] = $expValue->id;
                    $experienceData[$expKey]['organisation_name'] = $expValue->organisation_name;
                        
                    $designationName = Skill::where('type', 'Designation')->where('id', $expValue->designation)->value('skill_name');
                    if(!empty($designationName)){
                        $experienceData[$expKey]['designation'] = $designationName;
                    } else{
                        $experienceData[$expKey]['designation'] = $expValue->designation;
                    }
                        
                    // $experienceData[$expKey]['designation'] = $expValue->designation;
                    $experienceData[$expKey]['reason_of_leaving'] = $expValue->reason_of_leaving;
                    $experienceData[$expKey]['start_date'] = date('d M Y',strtotime($expValue->start_date));
                    $experienceData[$expKey]['end_date'] = date('d M Y',strtotime($expValue->end_date));
                }
                $candidateData[$key]['experience'] = $experienceData;
                
                $jobValue = Job::where('id', $value->job_form_id)->first();

                $jobData = [];
                
                if ($jobValue) {
                    // Fetch employer and staff details
                    $employerRecord = Employer::where('id', $jobValue->employer_id)
                        ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                        ->first();
                    $staffRecord = Staff::where('id', $jobValue->staff_id)
                        ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                        ->first();
                
                    // Assign employer and staff names
                    $employerName = $employerRecord->full_name ?? "Not Available";
                    $staffName = $staffRecord->full_name ?? "Not Available";
                
                    // Assign job data
                    $jobData = [
                        'job_id'         => $jobValue->id,
                        'user_id'        => $jobValue->user_id,
                        'employer_name'  => $employerName,
                        'employer_id'    => $jobValue->employer_id,
                        'staff_name'     => $staffName,
                        'staff_id'       => $jobValue->staff_id,
                        'job_name'       => $jobValue->title,
                        'category_id'    => $jobValue->category_id,
                        'category' => isset($jobValue->category_id) ? getCategoryName($jobValue->category_id) : "Category Not Available",
                        'designation_id' => $jobValue->designation,
                        'designation'    => getDesignationName($jobValue->designation),
                        'location'       => $jobValue->location,
                        'job_description'=> $jobValue->description,
                        'work_type'      => getWorkTypeName($jobValue->work_type),
                        'slug'           => $jobValue->slug,
                        'job_created_at' => format_date($jobValue->created_at),
                        'job_status'     => $jobValue->status,
                        'min_salary'     => CURR . " " . $jobValue->min_salary,
                        'max_salary'     => CURR . " " . $jobValue->max_salary,
                        'min_exp'        => $jobValue->min_exp,
                        'max_exp'        => $jobValue->max_exp,
                        'skill_id'       => $jobValue->skill,
                        'status'         => $jobValue->status,
                    ];
                
                    // Process orders
                    $processOrderIds = explode(',', $jobValue->process_order_ids);
                    $jobData['process_order'] = implode(', ', array_map('getProcessOrderName', $processOrderIds));
                
                    // Skills
                    $skillIds = explode(',', $jobValue->skill);
                    $jobData['skill'] = implode(', ', array_map('getSkillName', $skillIds));
                } else {
                    $jobData = ['error' => 'Job not found'];
                }
                
                $candidateData[$key]['jobData'] = $jobData;
                
                // foreach ($jobs as $jobKey => $jobValue){
                //     $jobDetails[$jobKey]['job_id'] = $jobValue->job_form_id;
                //     $jobDetails[$jobKey]
                // }
                
            }
            
            // $status = StatusAttributes::where('status', 1)->get();
            
            $status = StatusAttributes::where(function ($query) use ($employerCheck) {
                $query->where('employer_id', $employerCheck->id)
                    ->orWhere('employer_id', 0);
            })
                ->where('status', 1)
                // ->orderBy('id', 'desc')
                ->get();
        
            $data['candidatesData'] = $candidateData;
            $data['statusList'] = $status;
            
            
            $process = Process::where('employer_id', $currentUser)->orWhere('employer_id','0')->get();
            $data['processList'] = $process;
    
            $user = Staff::where('employer_id', $currentUser)->get();
            $data['user'] = $user;
    
            return Response(['response' => $data], 200);
            
        } else if(!empty($staffCheck)){
            // $candidates = CandidateJobApply::where('staff_id', $currentUser)->get();
            // $candidateData = array();

            // foreach($candidates as $key => $value) {
                
            // $candidateData[$key]['additional_data'] = $value->custom_fields_data ? json_decode($value->custom_fields_data, true) : [];
            
            // $candidateData[$key]['candidate_id'] = $value->id;
            // $candidateData[$key]['job_id'] = $value->job_form_id;
            // $candidateData[$key]['employer_id'] = $value->employer_id;
            // $candidateData[$key]['staff_id'] = $value->staff_id;
            // $candidateData[$key]['first_name'] = $value->first_name;
            // $candidateData[$key]['last_name'] = $value->last_name;
            // $candidateData[$key]['email'] = $value->email;
            // $candidateData[$key]['phone'] = $value->contact_number;
            // $candidateData[$key]['address'] = $value->address;
            // $candidateData[$key]['gender'] = $value->gender;
            // $candidateData[$key]['dateofbirth'] = date('d M Y',strtotime($value->date_of_birth));
            // $candidateData[$key]['martialstatus'] = $value->martial_status;
            // $candidateData[$key]['physical_challenged'] = $value->physical_challenge;
            // $candidateData[$key]['created'] = format_date($value->created);
            // $candidateData[$key]['status'] = $value->status;
            // $candidateData[$key]['interview_status'] = $value->interview_status;
            // $candidateData[$key]['interviewDetails'] = getFeedbackData($value->id);
            // $candidateData[$key]['jobAppliedFor'] = Job::where('id',$value->job_form_id)->value('title');

            // }
    
            // return Response(['response' => $candidateData], 200);
            
            
            $candidates = CandidateJobApply::where('employer_id', $staffCheck->employer_id)->orderBy('id', 'desc')->get();
            
            // return Response(['response' => $candidates, 'status' => 200], 200);
            // exit();
            $candidateData = array();

            foreach($candidates as $key => $value) {
                
                
                $interviewDetails = CandidateInterviewSchedule::where('candidate_id', $value->id)->orderBy('created_at', 'desc')->first();

                $processName = $interviewDetails ? Process::where('id', $interviewDetails->process_id)->value('process_name') ?? '' : '';
                $CompletionStatus = $interviewDetails->interview_completion_status ?? '';
                
                if($CompletionStatus == 1){
                    $interviewCompletionStatus = 'Completed';
                } else{
                    $interviewCompletionStatus = 'Not Completed';
                }
                
                // return response(['response' => $processName, 'message' => '', 'status' => 200], 200);
                // exit();
                
                
                $candidateData[$key]['additional_data'] = $value->custom_fields_data ? json_decode($value->custom_fields_data, true) : [];
                
                $employerRecord = Employer::where('id', $value->employer_id)
                    ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                    ->first();
                if(!empty($employerRecord)){
                    $employerName = $employerRecord->full_name;
                }else {
                    $employerName = "Not Available";
                }
                $staffRecord = Staff::where('id', $value->staff_id)
                    ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                    ->first();
                    
                if(!empty($staffRecord)){
                    $staffName = $staffRecord->full_name;
                }else {
                    $staffName = "Not Available";
                }
                    
                $candidateData[$key]['latest_interview_status'] = [
                    'process_name' => $processName,
                    'completion_status' => $interviewCompletionStatus
                ];
                $candidateData[$key]['candidate_id'] = $value->id;
                $candidateData[$key]['id'] = $value->id;
                $candidateData[$key]['job_id'] = $value->job_form_id;
                $candidateData[$key]['first_name'] = $value->first_name;
                $candidateData[$key]['middle_name'] = $value->middle_name;
                $candidateData[$key]['last_name'] = $value->last_name;
                    if($value->gender == 1){
                        $candidateData[$key]['gender'] = "Male";
                    } else if($value->gender == 2){
                        $candidateData[$key]['gender'] = "Female";
                    }else if($value->gender == 3){
                        $candidateData[$key]['gender'] = "Other";
                    } else{
                        $candidateData[$key]['gender'] = "";
                    }
                    if(!empty($value->profile_img)){
                        $candidateData[$key]['profile_image'] = DISPLAY_FULL_PROFILE_IMAGE_PATH.$value->profile_img;
                    }else{
                        $candidateData[$key]['profile_image'] = "";
                    }
                    if(!empty($value->document_cv)){
                        $candidateData[$key]['cv_document'] = DISPLAY_RESUME_PATH.$value->document_cv;
                    }else{
                        $candidateData[$key]['cv_document'] = "";
                    }
                    $candidateData[$key]['email_address'] = $value->email;
                    $candidateData[$key]['contact'] = $value->contact_number;
                    
                    if(!empty($value->date_of_birth)){
                         $candidateData[$key]['date_of_birth'] = date('d M Y',strtotime($value->date_of_birth));
                    } else{
                         $candidateData[$key]['date_of_birth'] = "";
                    }
                    
                   
                    if($value->martial_status == 1){
                        $candidateData[$key]['martial_status'] = "Single";
                    } else if($value->martial_status == 2){
                        $candidateData[$key]['martial_status'] = "Married";
                    } else if($value->martial_status == 3){
                        $candidateData[$key]['martial_status'] = "Divorced";
                    }else{
                        $candidateData[$key]['martial_status'] = "N/A";
                    }
                    if($value->physically_challenged == 1){
                        $candidateData[$key]['physically_challenged'] = "Yes";
                    } else if($value->physically_challenged == 2){
                        $candidateData[$key]['physically_challenged'] = "No";
                    } else if($value->physically_challenged == 3){
                        $candidateData[$key]['physically_challenged'] = "Prefer not to say";
                    }else{
                        $candidateData[$key]['physically_challenged'] = "N/A";
                    }
                    $candidateData[$key]['address'] = $value->address;
                    $candidateData[$key]['applied_date'] = date('d M Y',strtotime($value->created_at));
                    $candidateData[$key]['interview_status'] = $value->interview_status;
                    
                    $candidateData[$key]['cover_letter_title'] = $value->cover_letter_title ?? "N/A";
                    $candidateData[$key]['cover_letter_description'] = $value->cover_letter_description ?? "N/A";
                    $candidateData[$key]['general_application_additional_data'] = json_decode($value->candidate_general_application_data);
                    
                
                $jobName = Job::where('id',$value->job_form_id)->value('title');
                if(!empty($jobName)){
                    $candidateData[$key]['jobAppliedFor'] = $jobName;
                } else{
                    $candidateData[$key]['jobAppliedFor'] = "Job not available";
                }
                
                $education = CandidateEducation::where('candidate_job_apply_id', $value->id)->get();
                $educationData = array();
                foreach ($education as $eduKey => $eduValue) {
                    $educationData[$eduKey]['id'] = $eduValue->id;
                    // $educationData[$eduKey]['qualification_id'] = Qualification::find($eduValue->qualification_id)->qualification_name;
                        
                    $qualificationName = Qualification::where('id', $eduValue->qualification_id)->value('qualification_name');
                    if(!empty($qualificationName)){
                        $educationData[$eduKey]['qualification_id'] = $qualificationName;
                    } else{
                        $educationData[$eduKey]['qualification_id'] = $eduValue->designation;
                    }
                        
                    $educationData[$eduKey]['course'] = $eduValue->course;
                    $educationData[$eduKey]['school_college'] = $eduValue->school_college;
                    $educationData[$eduKey]['city'] = $eduValue->city;
                    $educationData[$eduKey]['university_board'] = $eduValue->university_board;
                    $educationData[$eduKey]['passing_year'] = $eduValue->passing_year;
                }
                $candidateData[$key]['education'] = $educationData;
        
                $experience = CandidateExperience::where('candidate_job_apply_id', $value->id)->get();
                $experienceData = array();
                foreach ($experience as $expKey => $expValue) {
                    $experienceData[$expKey]['id'] = $expValue->id;
                    $experienceData[$expKey]['organisation_name'] = $expValue->organisation_name;
                        
                    $designationName = Skill::where('type', 'Designation')->where('id', $expValue->designation)->value('skill_name');
                    if(!empty($designationName)){
                        $experienceData[$expKey]['designation'] = $designationName;
                    } else{
                        $experienceData[$expKey]['designation'] = $expValue->designation;
                    }
                        
                    // $experienceData[$expKey]['designation'] = $expValue->designation;
                    $experienceData[$expKey]['reason_of_leaving'] = $expValue->reason_of_leaving;
                    $experienceData[$expKey]['start_date'] = date('d M Y',strtotime($expValue->start_date));
                    $experienceData[$expKey]['end_date'] = date('d M Y',strtotime($expValue->end_date));
                }
                $candidateData[$key]['experience'] = $experienceData;
                
                $jobValue = Job::where('id', $value->job_form_id)->first();

                $jobData = [];
                
                if ($jobValue) {
                    // Fetch employer and staff details
                    $employerRecord = Employer::where('id', $jobValue->employer_id)
                        ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                        ->first();
                    $staffRecord = Staff::where('id', $jobValue->staff_id)
                        ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                        ->first();
                
                    // Assign employer and staff names
                    $employerName = $employerRecord->full_name ?? "Not Available";
                    $staffName = $staffRecord->full_name ?? "Not Available";
                
                    // Assign job data
                    $jobData = [
                        'job_id'         => $jobValue->id,
                        'user_id'        => $jobValue->user_id,
                        'employer_name'  => $employerName,
                        'employer_id'    => $jobValue->employer_id,
                        'staff_name'     => $staffName,
                        'staff_id'       => $jobValue->staff_id,
                        'job_name'       => $jobValue->title,
                        'category_id'    => $jobValue->category_id,
                        'category' => isset($jobValue->category_id) ? getCategoryName($jobValue->category_id) : "Category Not Available",
                        'designation_id' => $jobValue->designation,
                        'designation'    => getDesignationName($jobValue->designation),
                        'location'       => $jobValue->location,
                        'job_description'=> $jobValue->description,
                        'work_type'      => getWorkTypeName($jobValue->work_type),
                        'slug'           => $jobValue->slug,
                        'job_created_at' => format_date($jobValue->created_at),
                        'job_status'     => $jobValue->status,
                        'min_salary'     => CURR . " " . $jobValue->min_salary,
                        'max_salary'     => CURR . " " . $jobValue->max_salary,
                        'min_exp'        => $jobValue->min_exp,
                        'max_exp'        => $jobValue->max_exp,
                        'skill_id'       => $jobValue->skill,
                        'status'         => $jobValue->status,
                    ];
                
                    // Process orders
                    $processOrderIds = explode(',', $jobValue->process_order_ids);
                    $jobData['process_order'] = implode(', ', array_map('getProcessOrderName', $processOrderIds));
                
                    // Skills
                    $skillIds = explode(',', $jobValue->skill);
                    $jobData['skill'] = implode(', ', array_map('getSkillName', $skillIds));
                } else {
                    $jobData = ['error' => 'Job not found'];
                }
                
                $candidateData[$key]['jobData'] = $jobData;
                
                // foreach ($jobs as $jobKey => $jobValue){
                //     $jobDetails[$jobKey]['job_id'] = $jobValue->job_form_id;
                //     $jobDetails[$jobKey]
                // }
                
            }
            
            // $status = StatusAttributes::where('status', 1)->get();
            
            $employerCheck = $staffCheck->employer_id;
            
            $status = StatusAttributes::where(function ($query) use ($employerCheck) {
                $query->where('employer_id', $employerCheck)
                    ->orWhere('employer_id', 0);
            })
                ->where('status', 1)
                // ->orderBy('id', 'desc')
                ->get();
        
            $data['candidatesData'] = $candidateData;
            $data['statusList'] = $status;
            
            
            $process = Process::where('employer_id', $employerCheck)->orWhere('employer_id','0')->get();
            $data['processList'] = $process;
    
            $user = Staff::where('employer_id', $employerCheck)->get();
            $data['user'] = $user;
    
            return Response(['response' => $data], 200);
            
        }
        $candidateData = array();

        foreach($candidates as $key => $value) {
            
            $candidateData[$key]['candidate_id'] = $value->id;
             $candidateData[$key]['job_id'] = $value->job_form_id;
             $candidateData[$key]['employer_id'] = $value->employer_id;
             $candidateData[$key]['staff_id'] = $value->staff_id;
             $candidateData[$key]['first_name'] = $value->first_name;
            $candidateData[$key]['last_name'] = $value->last_name;
             $candidateData[$key]['email'] = $value->email;
             $candidateData[$key]['phone'] = $value->contact_number;
             $candidateData[$key]['address'] = $value->address;
            $candidateData[$key]['gender'] = $value->gender;
             $candidateData[$key]['dateofbirth'] = date('d M Y',strtotime($value->date_of_birth));
             $candidateData[$key]['martialstatus'] = $value->martial_status;
             $candidateData[$key]['physical_challenged'] = $value->physical_challenge;
             $candidateData[$key]['created'] = format_date($value->created);
             $candidateData[$key]['status'] = $value->status;
             $candidateData[$key]['interview_status'] = $value->interview_status;
             $candidateData[$key]['interviewDetails'] = getFeedbackData($value->id);
        }

        return Response(['response' => $candidateData], 200);
        
    
}
    // public function candidateStatusChange(Request $request, $id) {
    //     $statusId = $request->status;
    //     // $employerId = Auth::user()->id();
    //     $candidateId = $request->candidate_id;
    //     $reason = $request->reason;
             
    //     if($statusId == "9"){
    //         // $companyName = Employer::where('id', $employerId)->value('company_name');
    //         $candidateData = CandidateJobApply::where('id', $candidateId)->select('first_name', 'last_name')->first();
    //         $candidateName = $candidateData ? $candidateData->first_name . ' ' . $candidateData->last_name : '';
    //         $candidateEmail = CandidateJobApply::where('id', $candidateId)->value('email');
    //         $jobId = CandidateJobApply::where('id', $candidateId)->value('job_form_id');
    //         $jobName = Job::where('id', $jobId)->value('title');
            
    //         $emailTemplate = EmailTemplate::where('id', 4)->first();
            
    //         $toRepArray = ['[!candidate_name!]', '[!job_name!]', '[!company_name!]', '[!reason!]'];
    //         $fromRepArray = [$candidateName, $jobName, 'Keshari', $request->reason];
                
                
    //         $emailSubject = str_replace($toRepArray, $fromRepArray, $emailTemplate->subject);
    //         $emailBody = str_replace($toRepArray, $fromRepArray, $emailTemplate->template);
                
                
    //         // Send the email
    //         try {
    //             Mail::to($candidateEmail)->send(new SendMail($emailBody, $emailSubject));
    //         } catch (\Exception $e) {
    //             return response()->json(['error' => 'Failed to send email.', 'message' => $e->getMessage()], 500);
    //         }
            
    //     }
        
        
    //     $candidate = CandidateJobApply::where('id', $id)->update(['interview_status' => $statusId]);

    //     return Response(['response' => $candidate,  'message' => 'Status updated', 'status' => 200], 200);

    // }
    
    
    public function candidateStatusChange(Request $request, $id)
{
    $statusId = $request->status;
    $candidateId = $request->candidate_id;
    $reason = $request->reason;
    $sendRejectionMessage = $request->sendRejectionMessage; 

    if ($statusId == "9") {
        // Retrieve candidate details
        $candidateData = CandidateJobApply::where('id', $candidateId)->select('first_name', 'last_name', 'email')->first();
        if (!$candidateData) {
            return response()->json(['error' => 'Candidate not found'], 404);
        }
        $candidateName = $candidateData->first_name . ' ' . $candidateData->last_name;
        $candidateEmail = $candidateData->email;

        // Retrieve job details
        $jobId = $candidateData->job_form_id;
        $jobName = Job::where('id', $jobId)->value('title');
        
        //employer id
        $employerId = $candidateData->employer_id;

        // Get the email template
        $emailTemplate = EmailTemplate::where('id', 4)->first();
        if (!$emailTemplate) {
            return response()->json(['error' => 'Email template not found'], 404);
        }
        
        if($sendRejectionMessage == 'true'){
            $updateReason = $reason;
        } else{
            $updateReason = '';
        }
        
        // Replace placeholders in the email template
        $toRepArray = ['[!candidate_name!]', '[!job_name!]', '[!company_name!]', '[!reason!]'];
        $fromRepArray = [$candidateName, $jobName, 'Keshari', $updateReason];

        $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 {
            if (filter_var($candidateEmail, FILTER_VALIDATE_EMAIL)) {
                Mail::to($candidateEmail)->send(new SendMail($emailBody, $emailSubject, $logoPath));
            } else {
                return response()->json(['error' => 'Invalid email address'], 400);
            }
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to send email.', 'message' => $e->getMessage()], 500);
        }
    }

    // Update the candidate status
    $candidate = CandidateJobApply::where('id', $id)->update(['interview_status' => $statusId]);

    return Response(['response' => $candidate,  'message' => 'Status updated', 'status' => 200], 200);
}

    
    public function candidateFeedback(Request $request) {

        // $uid = Auth::user()->id;
        // echo $uid;
        $validator = Validator::make($request->all(), [
            'candidate_id' => 'required',
            'feedback' => 'required',
        ]);
        $validator->setAttributeNames([
            'candidate_id' => 'Candidate ID',
            'feedback' => 'Feedback',
        ]);
        if($validator->fails()){
            return Response(['response' => $validator->errors(), 'status' => 500], 200);
        } else {
            $feedback = CandidateFeedback::insert([
                'user_id' => Auth::user()->id,
                'candidate_id' => $request->candidate_id,
                'feedback' => $request->feedback,
            ]);
            return Response(['response' => $feedback, 'message' => 'Feedback added successfully', 'status' => 200], 200);
        }
    }
    
    public function candidateInterviewSchedule(Request $request, $id) {
        
        if(!empty($request->all())){
            
        }else {
            $candidateData = CandidateJobApply::where('id', $id)->first();
            $processData = Process::where('status', 1)->get();
            $userList = Admin::where('id', '!=', 1)->get();

            return Response(['response' => ['candidateData' => $candidateData, 'processData' => $processData, 'userList' => $userList],  'message' => '', 'status' => 200], 200);
        }
    }
    
    public function candidateInterviewStatus(Request $request) {
        $candidateId = $request->candidate_id;
        $jobId = $request->job_id;
    
        $candidateInterviewJourneyDetails = DB::table('candidate_interview_journeys')
            ->where('job_id', $jobId)
            ->where('candidate_id', $candidateId)
            ->get();
    
        $candidateInterviewJourneyData = array();
        
            // return response(['response' => $candidateInterviewJourneyDetails, 'status' => 200], 200);

    
        foreach($candidateInterviewJourneyDetails as $key => $value) {
            $candidateInterviewJourneyData[$key]['id'] = $value->id;
            $candidateInterviewJourneyData[$key]['candidate_id'] = $value->candidate_id;
            $candidateInterviewJourneyData[$key]['job_id'] = $value->job_id;
            $candidateInterviewJourneyData[$key]['process_id'] = $value->process_id;
    
            // Fetch the process name if process_id exists
            if($value->process_id) {
                $process = Process::where('id', $value->process_id)->select('process_name')->first();
                $candidateInterviewJourneyData[$key]['process_name'] = $process ? $process->process_name : "Name not available";
            } else {
                $candidateInterviewJourneyData[$key]['process_name'] = "Name not available";
            }
    
            $candidateInterviewJourneyData[$key]['order'] = $value->order_number;
            $candidateInterviewJourneyData[$key]['completion_status'] = $value->completion_status;
            $candidateInterviewJourneyData[$key]['created_at'] = $value->created_at;
            
            
            // if($value->completion_status == 1){
                // $interviewDetails = CandidateInterviewSchedule::where('candidate_id', $value->candidate_id)->where('job_id', $value->job_id)->where('process_id', $value->process_id)->first();
                
                // // $interviewDetails = [];
                // $employerName = Employer::where('id', $interviewDetails->assigned_by)->first();
                // // return response(['response' => $employerName, 'message' => '', 'status' => 200 ], 200);
                // // exit();
                
                // // $staffName = Staff::where('id', $interviewDetails->assigned_to)->first();
                // $candidateName = CandidateJobApply::where('id', $interviewDetails->candidate_id)->first();
                // $jobName = Job::where('id', $interviewDetails->job_id)->first();
                // $processName = Process::where('id', $interviewDetails->process_id)->first();
                
                // if(!empty($employerName)){
                //     $interviewDetails['employer_name'] = $employerName->first_name . ' ' . $employerName->last_name;
                // } else{
                //     $interviewDetails['employer_name'] = '';
                // }
                
                // $assignedToIds = json_decode($interviewDetails->assigned_to, true); // Decode JSON to array

                // if (!empty($assignedToIds)) {
                //     $staffMembers = Staff::whereIn('id', $assignedToIds)->get(); // Fetch all assigned staff
                
                //     // Combine staff names into a single string
                //     $staffNames = $staffMembers->map(fn($staff) => $staff->first_name . ' ' . $staff->last_name)->implode(', ');
                
                //     // Add to interview details
                //     $interviewDetails['staff_name'] = $staffNames;
                // } else {
                //     $interviewDetails['staff_name'] = 'Not Assigned';
                // }

                
                // $interviewDetails['assigned_by'] = $interviewDetails->assigned_by ?? 'N/A';
                // // $interviewDetails['staff_name'] = $staffName->first_name . ' ' . $staffName->last_name;
                // $interviewDetails['candidate_name'] = $candidateName->first_name . ' ' . $candidateName->last_name;
                // if($interviewDetails->duration == 1){
                //     $interviewDetails['duration'] = $interviewDetails->duration . ' Hours';
                // } else{
                //     $interviewDetails['duration'] = $interviewDetails->duration . ' Minutes';
                // }
                
                // $interviewDetails['interview_date'] = Carbon::parse($interviewDetails->interview_date)->format('d M Y');
                // $interviewDetails['job_name'] = $jobName->title;
                // $interviewDetails['process_name'] = $processName->process_name;
                // $interviewDetails['start_time'] = date("g:i A", strtotime($interviewDetails->start_time . ":00"));
                
                // $candidateInterviewJourneyData[$key]['interview_details'] = $interviewDetails;
                
                
                $interviewDetails = CandidateInterviewSchedule::where('candidate_id', $value->candidate_id)
    ->where('job_id', $value->job_id)
    ->where('process_id', $value->process_id)
    ->get();
    
    

$candidateInterviewJourneyData[$key]['interview_details'] = [];

if ($interviewDetails->isNotEmpty()) { // Ensure data exists
    foreach ($interviewDetails as $interview) {
        // Fetch employer details
        $employerName = Employer::where('id', $interview->assigned_by)->first();
        $candidateName = CandidateJobApply::where('id', $interview->candidate_id)->first();
        $jobName = Job::where('id', $interview->job_id)->first();
        $processName = Process::where('id', $interview->process_id)->first();
        $staffName = Staff::where('id', $interview->completion_staff_id)->first();
        
        $feedbackData = CandidateFeedback::where('candidate_id', $interview->candidate_id)
            ->where('job_id', $interview->job_id)
            ->where('process_id', $interview->process_id)
            ->where('type', 'feedback')
            ->first();
        // return response(['response' => [$value->candidate_id, $value->job_id, $value->process_id], 'status' => 200], 200);
        
        // $feedback = "";
        
        // if(!empty($feedbackData)){
        //   if($feedbackData->type == "feedback"){
        //         $feedback = $feedbackData->feedback_and_recommedations;
        //     } else{
        //         $feedback = "";
        //     } 
        // }
        
        

        $interviewData = [
            'employer_name' => $employerName ? $employerName->first_name . ' ' . $employerName->last_name : '',
            'candidate_name' => $candidateName ? $candidateName->first_name . ' ' . $candidateName->last_name : '',
            'job_name' => $jobName ? $jobName->title : '',
            'process_name' => $processName ? $processName->process_name : '',
            'interview_date' => Carbon::parse($interview->interview_date)->format('d M Y'),
            'start_time' => date("g:i A", strtotime($interview->start_time . ":00")),
            'duration' => $interview->duration == 1 ? '1 Hour' : $interview->duration . ' Minutes',
            'assigned_by' => $interview->assigned_by ?? 'N/A',
            'interview_completion_status' => $interview->interview_completion_status,
            'interview_type' => $interview->interview_type,
            'interview_type_detail' => $interview->interview_type_detail,
            'completion_staff_id' => $interview->completion_staff_id,
            'completion_staff_name' => $staffName ? $staffName->first_name . ' ' . $staffName->last_name : '',
            'feedback_and_recommendations' => $feedbackData ? ($feedbackData->feedback_and_recommendations ?? 'N/A') : 'N/A',
        ];

        // Process assigned staff
        $assignedToIds = json_decode($interview->assigned_to, true);
        if (!empty($assignedToIds)) {
            $staffMembers = Staff::whereIn('id', $assignedToIds)->get();
            $staffNames = $staffMembers->map(fn($staff) => $staff->first_name . ' ' . $staff->last_name)->implode(',');
            $interviewData['staff_name'] = $staffNames;
        } else {
            $interviewData['staff_name'] = 'Not Assigned';
        }

        $candidateInterviewJourneyData[$key]['interview_details'] = $interviewData;
    }
} else {
    // No interview details found, return an empty array
    $candidateInterviewJourneyData[$key]['interview_details'] = '';
}


                
            // }
            
        }
    
        return Response(['response' => $candidateInterviewJourneyData, 'status' => '200'], 200);
    }
    
    public function selectedCandidates(Request $request) {
        $currentUser = Auth::user()->id;
        $adminCheck = Admin::where('id', $currentUser)->first();
        $employerCheck = Employer::where('id', $currentUser)->first();
        $staffCheck = Staff::where('id', $currentUser)->first();
        
        if (!empty($adminCheck)) {
            $candidates = CandidateJobApply::all();
            $candidateData = array();

            foreach($candidates as $key => $value) {
                
                $employerName = Employer::where('id', $value->employer_id)
                    ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                    ->first();
                $staffName = Staff::where('id', $value->staff_id)
                    ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                    ->first();

                $candidateData[$key]['candidate_id'] = $value->id;
                $candidateData[$key]['job_id'] = $value->job_form_id;
                $candidateData[$key]['first_name'] = $value->first_name;
                $candidateData[$key]['last_name'] = $value->last_name;
                $candidateData[$key]['email'] = $value->email;
                $candidateData[$key]['phone'] = $value->contact_number;
                $candidateData[$key]['address'] = $value->address;
                $candidateData[$key]['gender'] = $value->gender;
                
                if(!empty($value->date_of_birth)){
                    $candidateData[$key]['dateofbirth'] = $value->date_of_birth;
                } else{
                    $candidateData[$key]['dateofbirth'] = '';
                }
                
                
                $candidateData[$key]['martialstatus'] = $value->martial_status;
                $candidateData[$key]['physical_challenged'] = $value->physical_challenge;
                $candidateData[$key]['created'] = format_date($value->created);
                $candidateData[$key]['status'] = $value->status;
                $candidateData[$key]['interview_status'] = $value->interview_status;
                $candidateData[$key]['interviewDetails'] = getFeedbackData($value->id);
                $candidateData[$key]['jobAppliedFor'] = Job::where('id',$value->job_form_id)->value('title');
            }
            
            $status = StatusAttributes::where('status', 1)->get();
        
            $data['candidatesData'] = $candidateData;
            $data['statusList'] = $status;
            
            
            $process = Process::where('status', 1)->get();
            $data['processList'] = $process;
    
            $user = Admin::where('id', '!=', 1)->get();
            $data['user'] = $user;
    
            return Response(['response' => $data], 200);
        } else if(!empty($employerCheck)) {
            $candidates = CandidateJobApply::where('employer_id', $currentUser)->where('interview_status','8')->orderBy('id', 'desc')->get();
            $candidateData = array();
            
           
            
            // draft data 
            
            

            foreach($candidates as $key => $value) {
                
                $employerRecord = Employer::where('id', $value->employer_id)
                    ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                    ->first();
                if(!empty($employerRecord)){
                    $employerName = $employerRecord->full_name;
                }else {
                    $employerName = "Not Available";
                }
                $staffRecord = Staff::where('id', $value->staff_id)
                    ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                    ->first();
                    
                if(!empty($staffRecord)){
                    $staffName = $staffRecord->full_name;
                }else {
                    $staffName = "Not Available";
                }
                    
                $candidateData[$key]['additional_data'] = $value->custom_fields_data ? json_decode($value->custom_fields_data, true) : [];
                
                $candidateData[$key]['candidate_id'] = $value->id;
                $candidateData[$key]['draft_status'] = $value->draft_status;
                $candidateData[$key]['on_boarding_completion_status'] = $value->on_boarding_completion_status;
                if ($value->draft_status == "1") {
                    $candidateDraftData = OfferDraftData::where('candidate_id', $value->id)->first();
                    if(!empty($candidateDraftData)){
                        $candidateData[$key]['draft_data'] = $candidateDraftData;
                    }else{
                        $candidateData[$key]['draft_data'] = "";
                    }
                }else{
                    $candidateData[$key]['draft_data'] = "";
                }     
               
                $candidateData[$key]['id'] = $value->id;
                $candidateData[$key]['job_id'] = $value->job_form_id;
                $candidateData[$key]['first_name'] = $value->first_name;
                $candidateData[$key]['middle_name'] = $value->middle_name;
                $candidateData[$key]['last_name'] = $value->last_name;
                    if($value->gender == 1){
                        $candidateData[$key]['gender'] = "Male";
                    } else if($value->gender == 2){
                        $candidateData[$key]['gender'] = "Female";
                    }else{
                        $candidateData[$key]['gender'] = "Other";
                    }
                    if(!empty($value->profile_img)){
                        $candidateData[$key]['profile_image'] = DISPLAY_FULL_PROFILE_IMAGE_PATH.$value->profile_img;
                    }else{
                        $candidateData[$key]['profile_image'] = "";
                    }
                    if(!empty($value->profile_img)){
                        $candidateData[$key]['cv_document'] = DISPLAY_RESUME_PATH.$value->document_cv;
                    }else{
                        $candidateData[$key]['cv_document'] = "";
                    }
                    $candidateData[$key]['email_address'] = $value->email;
                    $candidateData[$key]['contact'] = $value->contact_number;
                    
                    if(!empty($value->date_of_birth)){
                        $candidateData[$key]['date_of_birth'] = date('d M Y',strtotime($value->date_of_birth));
                    } else{
                        $candidateData[$key]['dateofbirth'] = '';
                    }
                    
                    
                    if($value->martial_status == 1){
                        $candidateData[$key]['martial_status'] = "Single";
                    } else if($value->martial_status == 2){
                        $candidateData[$key]['martial_status'] = "Married";
                    } else if($value->martial_status == 3){
                        $candidateData[$key]['martial_status'] = "Divorced";
                    }else{
                        $candidateData[$key]['martial_status'] = "N/A";
                    }
                    if($value->physically_challenged == 1){
                        $candidateData[$key]['physically_challenged'] = "Yes";
                    } else if($value->physically_challenged == 2){
                        $candidateData[$key]['physically_challenged'] = "No";
                    } else if($value->physically_challenged == 3){
                        $candidateData[$key]['physically_challenged'] = "Prefer not to say";
                    }else{
                        $candidateData[$key]['physically_challenged'] = "N/A";
                    }
                    // $candidateData[$key]['address'] = $value->address;
                    $candidateData[$key]['applied_date'] = date('d M Y',strtotime($value->created_at));
                
                
                $jobName = Job::where('id',$value->job_form_id)->value('title');
                if(!empty($jobName)){
                    $candidateData[$key]['jobAppliedFor'] = $jobName;
                } else{
                    $candidateData[$key]['jobAppliedFor'] = "Job not available";
                }
                
                $candidateData[$key]['offer_letter_status'] = $value->offer_letter_status;
                
                if($value->offer_letter_status == 1){
                    $candidateData[$key]['email_template_id'] = 2;
                } else{
                    $candidateData[$key]['email_template_id'] = 0;
                }
                
                $candidateData[$key]['on_boarding_status'] = $value->on_boarding_status;
                
                $candidateData[$key]['cover_letter_title'] = $value->cover_letter_title;
                $candidateData[$key]['cover_letter_description'] = $value->cover_letter_description;
                
                $education = CandidateEducation::where('candidate_job_apply_id', $value->id)->get();
                    $educationData = array();
                    foreach ($education as $eduKey => $eduValue) {
                        $educationData[$eduKey]['id'] = $eduValue->id;
                        $educationData[$eduKey]['qualification_id'] = Qualification::find($eduValue->qualification_id)->qualification_name;
                        $educationData[$eduKey]['course'] = $eduValue->course;
                        $educationData[$eduKey]['school_college'] = $eduValue->school_college;
                        $educationData[$eduKey]['city'] = $eduValue->city;
                        $educationData[$eduKey]['university_board'] = $eduValue->university_board;
                        $educationData[$eduKey]['passing_year'] = $eduValue->passing_year;
                    }
                    $candidateData[$key]['education'] = $educationData;
        
                    $experience = CandidateExperience::where('candidate_job_apply_id', $value->id)->get();
                    $experienceData = array();
                    foreach ($experience as $expKey => $expValue) {
                        
                        $designationName = Skill::where('type', 'Designation')->where('id', $expValue->designation)->value('skill_name');
                        if(!empty($designationName)){
                            $experienceData[$expKey]['designation'] = $designationName;
                        } else{
                            $experienceData[$expKey]['designation'] = $expValue->designation;
                        }
                        $experienceData[$expKey]['id'] = $expValue->id;
                        $experienceData[$expKey]['organisation_name'] = $expValue->organisation_name;
                        
                        $experienceData[$expKey]['reason_of_leaving'] = $expValue->reason_of_leaving;
                        $experienceData[$expKey]['start_date'] = date('d M Y',strtotime($expValue->start_date));
                        $experienceData[$expKey]['end_date'] = date('d M Y',strtotime($expValue->end_date));
                    }
                    $candidateData[$key]['experience'] = $experienceData;
                    
                    
                    $jobValue = Job::where('id', $value->job_form_id)->first();
                
                
                
                    $jobData = [];
    
                    if ($jobValue) {
                        // Fetch employer and staff details
                        $employerRecord = Employer::where('id', $jobValue->employer_id)
                            ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                            ->first();
                        $staffRecord = Staff::where('id', $jobValue->staff_id)
                            ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                            ->first();
                    
                        // Assign employer and staff names
                        $employerName = $employerRecord->full_name ?? "Not Available";
                        $staffName = $staffRecord->full_name ?? "Not Available";
                    
                        // Assign job data
                        $jobData = [
                            'job_id'         => $jobValue->id,
                            'user_id'        => $jobValue->user_id,
                            'employer_name'  => $employerName,
                            'employer_id'    => $jobValue->employer_id,
                            'staff_name'     => $staffName,
                            'staff_id'       => $jobValue->staff_id,
                            'job_name'       => $jobValue->title,
                            'category_id'    => $jobValue->category_id,
                            'category'       => isset($jobValue->category_id) ? getCategoryName($jobValue->category_id) : "Category Not Available",
                            'designation_id' => $jobValue->designation,
                            'designation'    => getDesignationName($jobValue->designation),
                            'location'       => $jobValue->location,
                            'job_description'=> $jobValue->description,
                            'work_type'      => getWorkTypeName($jobValue->work_type),
                            'slug'           => $jobValue->slug,
                            'job_created_at' => format_date($jobValue->created_at),
                            'job_status'     => $jobValue->status,
                            'min_salary'     => CURR . " " . $jobValue->min_salary,
                            'max_salary'     => CURR . " " . $jobValue->max_salary,
                            'min_exp'        => $jobValue->min_exp,
                            'max_exp'        => $jobValue->max_exp,
                            'skill_id'       => $jobValue->skill,
                            'status'         => $jobValue->status,
                        ];
                    
                        // Process orders
                        $processOrderIds = explode(',', $jobValue->process_order_ids);
                        $jobData['process_order'] = implode(', ', array_map('getProcessOrderName', $processOrderIds));
                    
                        // Skills
                        $skillIds = explode(',', $jobValue->skill);
                        $jobData['skill'] = implode(', ', array_map('getSkillName', $skillIds));
                    } else {
                        $jobData = ['error' => 'Job not found'];
                    }
                    
                    
                    
                    $candidateData[$key]['jobData'] = $jobData;
                    
                    
                    $interviewDetails = CandidateInterviewSchedule::where('candidate_id', $value->id)->get();
                    $interviewJourney = array();
                    foreach($interviewDetails as $interviewKey => $interValue) {
                        
                        $candidateNameData = CandidateJobApply::where('id', $interValue->candidate_id)->select(['first_name', 'last_name'])->first();
                        $candidateName = $candidateNameData->first_name . ' ' . $candidateNameData->last_name;
                        
                        $employerNameData = Employer::where('id', $interValue->assigned_by)->select(['first_name', 'last_name'])->first();
                        $employerName = $employerNameData->first_name . ' ' . $employerNameData->last_name;
                        
                        // $staffNameData = Staff::where('id', $interValue->assigned_to)->select(['first_name', 'last_name'])->first();
                        // $staffName = $staffNameData->first_name . ' ' . $staffNameData->last_name;
                        
                        
                        $assignedUserIds = json_decode($interValue->assigned_to, true);
                

                        // Ensure it's an array
                        if (!is_array($assignedUserIds)) {
                            // $assignedUserIds = [$assignedUserIds];
                            $assignedUserIdsArray = explode(',', $assignedUserIds);// Convert single value to an array
                        } 
                        else{
                            $assignedUserIdsArray = $assignedUserIds;
                        }
                        
                        // return Response(['response' => $assignedUserIdsArray,'message' => '', 'status' => 200], 200);
                        // exit();
                        
                        if (!empty($assignedUserIdsArray)) {
                            $assignedUsers = Staff::whereIn('id', $assignedUserIdsArray)
                                ->select('first_name', 'last_name')
                                ->get()
                                ->map(function ($staff) {
                                    return $staff->first_name . ' ' . $staff->last_name;
                                })
                                ->toArray();
                        
                            $staffName = implode(', ', $assignedUsers);
                        } else {
                            $staffName = '';
                        }
                        
                        $completionStaffName = Staff::where('id', $interValue->completion_staff_id)->first();
                        
                        
                        $feedbackData = CandidateFeedback::where('candidate_id', $interValue->candidate_id)
                                            ->where('job_id', $interValue->job_id)
                                            ->where('process_id', $interValue->process_id)
                                            ->where('type', 'feedback')
                                            ->first();
                        
                        
                        $jobName = Job::where('id', $interValue->job_id)->value('title');
                        
                        $processName = Process::where('id', $interValue->process_id)->value('process_name');
                        
                        $startTime = $interValue->start_time;

                        $formattedStartTime = date("g:i A", strtotime($startTime . ":00"));
                        
                        $interviewJourney[$interviewKey]['id'] = $interValue->id;
                        $interviewJourney[$interviewKey]['assigned_by'] = $interValue->assigned_by;
                        $interviewJourney[$interviewKey]['employer_name'] = $employerName;
                        $interviewJourney[$interviewKey]['assigned_to'] = $interValue->assigned_to;
                        $interviewJourney[$interviewKey]['staff_name'] = $staffName;
                        $interviewJourney[$interviewKey]['candidate_id'] = $interValue->candidate_id;
                        $interviewJourney[$interviewKey]['candidate_name'] = $candidateName;
                        $interviewJourney[$interviewKey]['job_id'] = $interValue->job_id;
                        $interviewJourney[$interviewKey]['job_name'] = $jobName;
                        $interviewJourney[$interviewKey]['process_id'] = $interValue->process_id;
                        $interviewJourney[$interviewKey]['process_name'] = $processName;
                        $interviewJourney[$interviewKey]['interview_type'] = $interValue->interview_type;

                        $interviewJourney[$interviewKey]['interview_type_details'] = $interValue->interview_type_details;
                        $interviewJourney[$interviewKey]['interview_date'] = date('d M Y',strtotime($interValue->interview_date));
                        $interviewJourney[$interviewKey]['start_time'] = $formattedStartTime;
                        $interviewJourney[$interviewKey]['duration'] = $interValue->duration;
                        $interviewJourney[$interviewKey]['comment'] = $interValue->comment;
                        $interviewJourney[$interviewKey]['round'] = $interValue->round;
                        $interviewJourney[$interviewKey]['interview_status'] = $interValue->interview_status;
                        $interviewJourney[$interviewKey]['interview_completion_status'] = $interValue->interview_completion_status;
                        $interviewJourney[$interviewKey]['interview_cancelation_status'] = $interValue->interview_cancelation_status;
                        $interviewJourney[$interviewKey]['interview_cancelation_reason'] = $interValue->interview_cancelation_reason;
                        
                        
                        $interviewJourney[$interviewKey]['completion_staff_id'] = $interValue->completion_staff_id;
                        $interviewJourney[$interviewKey]['completion_staff_name'] = $completionStaffName ? $completionStaffName->first_name . ' ' . $completionStaffName->last_name : '';
                        
                        $interviewJourney[$interviewKey]['feedback_and_recommendations'] = $feedbackData ? ($feedbackData->feedback_and_recommendations ?? 'N/A') : 'N/A';
                     }
                    
                    
                    
            
                    
                    $candidateData[$key]['interview_journey'] = $interviewJourney ?? [];
                    $candidateData[$key]['offer_letter_accepted'] = SelectedCandidate::where('candidate_id', $value->id)->value('offer_letter_accepted');
            }
            
            $status = StatusAttributes::where('status', 1)->get();
        
            // $data['candidatesData'] = $candidateData;
            // $data['statusList'] = $status;
            
            
            // $process = Process::where('employer_id', $currentUser)->orWhere('employer_id','0')->get();
            // $data['processList'] = $process;
    
            // $user = Staff::where('employer_id', $currentUser)->get();
            // $data['user'] = $user;
    
            return Response(['response' => $candidateData], 200);
            
        } else if(!empty($staffCheck)){
            
            
            // $currentUser = Auth::user()->id;
            // $currentUserCheck = Admin::where('id', $currentUser)->first();
            
            $staffDetail = Staff::find($currentUser);
            
            if(!empty($staffDetail)){
                
                $adminData = $staffDetail;
                    
                    $accessData = isset($adminData->roles) ? unserialize($adminData->roles) : [];
                
                        global $subadminAccess;
                        $accessControlArray = $subadminAccess;
                
                        if (!is_array($accessControlArray)) {
                            return response()->json(['message' => 'Access control data is missing or invalid', 'status' => 500], 500);
                        }
                
                        $accessArray = [];
                        foreach ($accessControlArray as $key => $ac) {
                            $accessArray[$key] = $ac; // Start with the original sub-array
                
                            // Override with $accessData if available
                            if (isset($accessData[$key])) {
                                foreach ($accessData[$key] as $accessKey => $accessValue) {
                                    $accessArray[$key][$accessKey] = $accessValue;
                                }
                            }
                        }
                    
                    
                    if($accessArray['15']['Module'] == 0){
                        return Response(['response' => 'You are not allowed to access this page.', 'message' => 'You are not allowed to access this page.', 'status' => 500], 200);
                    }
            }
            
            
            $employerId = $staffCheck->employer_id;
            
            $candidates = CandidateJobApply::where('employer_id', $employerId)->where('interview_status','8')->orderBy('id', 'desc')->get();
            $candidateData = array();
            
           
            
            // draft data 
            
            

            foreach($candidates as $key => $value) {
                
                $employerRecord = Employer::where('id', $value->employer_id)
                    ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                    ->first();
                if(!empty($employerRecord)){
                    $employerName = $employerRecord->full_name;
                }else {
                    $employerName = "Not Available";
                }
                $staffRecord = Staff::where('id', $value->staff_id)
                    ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                    ->first();
                    
                if(!empty($staffRecord)){
                    $staffName = $staffRecord->full_name;
                }else {
                    $staffName = "Not Available";
                }
                    
                $candidateData[$key]['additional_data'] = $value->custom_fields_data ? json_decode($value->custom_fields_data, true) : [];
                
                $candidateData[$key]['candidate_id'] = $value->id;
                $candidateData[$key]['draft_status'] = $value->draft_status;
                $candidateData[$key]['on_boarding_completion_status'] = $value->on_boarding_completion_status;
                if ($value->draft_status == "1") {
                    $candidateDraftData = OfferDraftData::where('candidate_id', $value->id)->first();
                    if(!empty($candidateDraftData)){
                        $candidateData[$key]['draft_data'] = $candidateDraftData;
                    }else{
                        $candidateData[$key]['draft_data'] = "";
                    }
                }else{
                    $candidateData[$key]['draft_data'] = "";
                }     
               
                $candidateData[$key]['id'] = $value->id;
                $candidateData[$key]['job_id'] = $value->job_form_id;
                $candidateData[$key]['first_name'] = $value->first_name;
                $candidateData[$key]['middle_name'] = $value->middle_name;
                $candidateData[$key]['last_name'] = $value->last_name;
                    if($value->gender == 1){
                        $candidateData[$key]['gender'] = "Male";
                    } else if($value->gender == 2){
                        $candidateData[$key]['gender'] = "Female";
                    }else{
                        $candidateData[$key]['gender'] = "Other";
                    }
                    if(!empty($value->profile_img)){
                        $candidateData[$key]['profile_image'] = DISPLAY_FULL_PROFILE_IMAGE_PATH.$value->profile_img;
                    }else{
                        $candidateData[$key]['profile_image'] = "";
                    }
                    if(!empty($value->profile_img)){
                        $candidateData[$key]['cv_document'] = DISPLAY_RESUME_PATH.$value->document_cv;
                    }else{
                        $candidateData[$key]['cv_document'] = "";
                    }
                    $candidateData[$key]['email_address'] = $value->email;
                    $candidateData[$key]['contact'] = $value->contact_number;
                    
                    if(!empty($value->date_of_birth)){
                        $candidateData[$key]['date_of_birth'] = date('d M Y',strtotime($value->date_of_birth));
                    } else{
                        $candidateData[$key]['dateofbirth'] = '';
                    }
                    
                    
                    if($value->martial_status == 1){
                        $candidateData[$key]['martial_status'] = "Single";
                    } else if($value->martial_status == 2){
                        $candidateData[$key]['martial_status'] = "Married";
                    } else if($value->martial_status == 3){
                        $candidateData[$key]['martial_status'] = "Divorced";
                    }else{
                        $candidateData[$key]['martial_status'] = "N/A";
                    }
                    if($value->physically_challenged == 1){
                        $candidateData[$key]['physically_challenged'] = "Yes";
                    } else if($value->physically_challenged == 2){
                        $candidateData[$key]['physically_challenged'] = "No";
                    } else if($value->physically_challenged == 3){
                        $candidateData[$key]['physically_challenged'] = "Prefer not to say";
                    }else{
                        $candidateData[$key]['physically_challenged'] = "N/A";
                    }
                    // $candidateData[$key]['address'] = $value->address;
                    $candidateData[$key]['applied_date'] = date('d M Y',strtotime($value->created_at));
                
                
                $jobName = Job::where('id',$value->job_form_id)->value('title');
                if(!empty($jobName)){
                    $candidateData[$key]['jobAppliedFor'] = $jobName;
                } else{
                    $candidateData[$key]['jobAppliedFor'] = "Job not available";
                }
                
                $candidateData[$key]['offer_letter_status'] = $value->offer_letter_status;
                
                if($value->offer_letter_status == 1){
                    $candidateData[$key]['email_template_id'] = 2;
                } else{
                    $candidateData[$key]['email_template_id'] = 0;
                }
                
                $candidateData[$key]['on_boarding_status'] = $value->on_boarding_status;
                
                $candidateData[$key]['cover_letter_title'] = $value->cover_letter_title;
                $candidateData[$key]['cover_letter_description'] = $value->cover_letter_description;
                
                $education = CandidateEducation::where('candidate_job_apply_id', $value->id)->get();
                    $educationData = array();
                    foreach ($education as $eduKey => $eduValue) {
                        $educationData[$eduKey]['id'] = $eduValue->id;
                        $educationData[$eduKey]['qualification_id'] = Qualification::find($eduValue->qualification_id)->qualification_name;
                        $educationData[$eduKey]['course'] = $eduValue->course;
                        $educationData[$eduKey]['school_college'] = $eduValue->school_college;
                        $educationData[$eduKey]['city'] = $eduValue->city;
                        $educationData[$eduKey]['university_board'] = $eduValue->university_board;
                        $educationData[$eduKey]['passing_year'] = $eduValue->passing_year;
                    }
                    $candidateData[$key]['education'] = $educationData;
        
                    $experience = CandidateExperience::where('candidate_job_apply_id', $value->id)->get();
                    $experienceData = array();
                    foreach ($experience as $expKey => $expValue) {
                        
                        $designationName = Skill::where('type', 'Designation')->where('id', $expValue->designation)->value('skill_name');
                        if(!empty($designationName)){
                            $experienceData[$expKey]['designation'] = $designationName;
                        } else{
                            $experienceData[$expKey]['designation'] = $expValue->designation;
                        }
                        $experienceData[$expKey]['id'] = $expValue->id;
                        $experienceData[$expKey]['organisation_name'] = $expValue->organisation_name;
                        
                        $experienceData[$expKey]['reason_of_leaving'] = $expValue->reason_of_leaving;
                        $experienceData[$expKey]['start_date'] = date('d M Y',strtotime($expValue->start_date));
                        $experienceData[$expKey]['end_date'] = date('d M Y',strtotime($expValue->end_date));
                    }
                    $candidateData[$key]['experience'] = $experienceData;
                    
                    
                    $jobValue = Job::where('id', $value->job_form_id)->first();
                
                
                
                    $jobData = [];
    
                    if ($jobValue) {
                        // Fetch employer and staff details
                        $employerRecord = Employer::where('id', $jobValue->employer_id)
                            ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                            ->first();
                        $staffRecord = Staff::where('id', $jobValue->staff_id)
                            ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                            ->first();
                    
                        // Assign employer and staff names
                        $employerName = $employerRecord->full_name ?? "Not Available";
                        $staffName = $staffRecord->full_name ?? "Not Available";
                    
                        // Assign job data
                        $jobData = [
                            'job_id'         => $jobValue->id,
                            'user_id'        => $jobValue->user_id,
                            'employer_name'  => $employerName,
                            'employer_id'    => $jobValue->employer_id,
                            'staff_name'     => $staffName,
                            'staff_id'       => $jobValue->staff_id,
                            'job_name'       => $jobValue->title,
                            'category_id'    => $jobValue->category_id,
                            'category'       => isset($jobValue->category_id) ? getCategoryName($jobValue->category_id) : "Category Not Available",
                            'designation_id' => $jobValue->designation,
                            'designation'    => getDesignationName($jobValue->designation),
                            'location'       => $jobValue->location,
                            'job_description'=> $jobValue->description,
                            'work_type'      => getWorkTypeName($jobValue->work_type),
                            'slug'           => $jobValue->slug,
                            'job_created_at' => format_date($jobValue->created_at),
                            'job_status'     => $jobValue->status,
                            'min_salary'     => CURR . " " . $jobValue->min_salary,
                            'max_salary'     => CURR . " " . $jobValue->max_salary,
                            'min_exp'        => $jobValue->min_exp,
                            'max_exp'        => $jobValue->max_exp,
                            'skill_id'       => $jobValue->skill,
                            'status'         => $jobValue->status,
                        ];
                    
                        // Process orders
                        $processOrderIds = explode(',', $jobValue->process_order_ids);
                        $jobData['process_order'] = implode(', ', array_map('getProcessOrderName', $processOrderIds));
                    
                        // Skills
                        $skillIds = explode(',', $jobValue->skill);
                        $jobData['skill'] = implode(', ', array_map('getSkillName', $skillIds));
                    } else {
                        $jobData = ['error' => 'Job not found'];
                    }
                    
                    
                    
                    $candidateData[$key]['jobData'] = $jobData;
                    
                    
                    $interviewDetails = CandidateInterviewSchedule::where('candidate_id', $value->id)->get();
                    $interviewJourney = array();
                    foreach($interviewDetails as $interviewKey => $interValue) {
                        
                        $candidateNameData = CandidateJobApply::where('id', $interValue->candidate_id)->select(['first_name', 'last_name'])->first();
                        $candidateName = $candidateNameData->first_name . ' ' . $candidateNameData->last_name;
                        
                        $employerNameData = Employer::where('id', $interValue->assigned_by)->select(['first_name', 'last_name'])->first();
                        $employerName = $employerNameData->first_name . ' ' . $employerNameData->last_name;
                        
                        // $staffNameData = Staff::where('id', $interValue->assigned_to)->select(['first_name', 'last_name'])->first();
                        // $staffName = $staffNameData->first_name . ' ' . $staffNameData->last_name;
                        
                        
                        $assignedUserIds = json_decode($interValue->assigned_to, true);
                

                        // Ensure it's an array
                        if (!is_array($assignedUserIds)) {
                            // $assignedUserIds = [$assignedUserIds];
                            $assignedUserIdsArray = explode(',', $assignedUserIds);// Convert single value to an array
                        } 
                        else{
                            $assignedUserIdsArray = $assignedUserIds;
                        }
                        
                        // return Response(['response' => $assignedUserIdsArray,'message' => '', 'status' => 200], 200);
                        // exit();
                        
                        if (!empty($assignedUserIdsArray)) {
                            $assignedUsers = Staff::whereIn('id', $assignedUserIdsArray)
                                ->select('first_name', 'last_name')
                                ->get()
                                ->map(function ($staff) {
                                    return $staff->first_name . ' ' . $staff->last_name;
                                })
                                ->toArray();
                        
                            $staffName = implode(', ', $assignedUsers);
                        } else {
                            $staffName = '';
                        }
                        
                        $completionStaffName = Staff::where('id', $interValue->completion_staff_id)->first();
                        
                        
                        $feedbackData = CandidateFeedback::where('candidate_id', $interValue->candidate_id)
                                            ->where('job_id', $interValue->job_id)
                                            ->where('process_id', $interValue->process_id)
                                            ->where('type', 'feedback')
                                            ->first();
                        
                        $jobName = Job::where('id', $interValue->job_id)->value('title');
                        
                        $processName = Process::where('id', $interValue->process_id)->value('process_name');
                        
                        $startTime = $interValue->start_time;

                        $formattedStartTime = date("g:i A", strtotime($startTime . ":00"));
                        
                        $interviewJourney[$interviewKey]['id'] = $interValue->id;
                        $interviewJourney[$interviewKey]['assigned_by'] = $interValue->assigned_by;
                        $interviewJourney[$interviewKey]['employer_name'] = $employerName;
                        $interviewJourney[$interviewKey]['assigned_to'] = $interValue->assigned_to;
                        $interviewJourney[$interviewKey]['staff_name'] = $staffName;
                        $interviewJourney[$interviewKey]['candidate_id'] = $interValue->candidate_id;
                        $interviewJourney[$interviewKey]['candidate_name'] = $candidateName;
                        $interviewJourney[$interviewKey]['job_id'] = $interValue->job_id;
                        $interviewJourney[$interviewKey]['job_name'] = $jobName;
                        $interviewJourney[$interviewKey]['process_id'] = $interValue->process_id;
                        $interviewJourney[$interviewKey]['process_name'] = $processName;
                        $interviewJourney[$interviewKey]['interview_type'] = $interValue->interview_type;

                        $interviewJourney[$interviewKey]['interview_type_details'] = $interValue->interview_type_details;
                        $interviewJourney[$interviewKey]['interview_date'] = date('d M Y',strtotime($interValue->interview_date));
                        $interviewJourney[$interviewKey]['start_time'] = $formattedStartTime;
                        $interviewJourney[$interviewKey]['duration'] = $interValue->duration;
                        $interviewJourney[$interviewKey]['comment'] = $interValue->comment;
                        $interviewJourney[$interviewKey]['round'] = $interValue->round;
                        $interviewJourney[$interviewKey]['interview_status'] = $interValue->interview_status;
                        $interviewJourney[$interviewKey]['interview_completion_status'] = $interValue->interview_completion_status;
                        $interviewJourney[$interviewKey]['interview_cancelation_status'] = $interValue->interview_cancelation_status;
                        $interviewJourney[$interviewKey]['interview_cancelation_reason'] = $interValue->interview_cancelation_reason;
                        
                        $interviewJourney[$interviewKey]['completion_staff_id'] = $interValue->completion_staff_id;
                        $interviewJourney[$interviewKey]['completion_staff_name'] = $completionStaffName ? $completionStaffName->first_name . ' ' . $completionStaffName->last_name : '';
                        
                        $interviewJourney[$interviewKey]['feedback_and_recommendations'] = $feedbackData ? ($feedbackData->feedback_and_recommendations ?? 'N/A') : 'N/A';
                    }
                    
                    
                    
            
                    
                    $candidateData[$key]['interview_journey'] = $interviewJourney ?? [];
                    $candidateData[$key]['offer_letter_accepted'] = SelectedCandidate::where('candidate_id', $value->id)->value('offer_letter_accepted');
            }
            
            $status = StatusAttributes::where('status', 1)->get();
        
            // $data['candidatesData'] = $candidateData;
            // $data['statusList'] = $status;
            
            
            // $process = Process::where('employer_id', $currentUser)->orWhere('employer_id','0')->get();
            // $data['processList'] = $process;
    
            // $user = Staff::where('employer_id', $currentUser)->get();
            // $data['user'] = $user;
    
            return Response(['response' => $candidateData, 'status' => 200], 200);
    }
    }
    
    public function addComment(Request $request) {
        $currentUser = Auth::user()->id;
        $adminCheck = Admin::where('id', $currentUser)->where('user_type',"admin")->first();
        $employerCheck = Employer::where('id', $currentUser)->where('user_type',"employer")->first();
        $staffCheck = Staff::where('id', $currentUser)->where('user_type',"staff")->first();
        $candidate = $request->candidate;
        $job_id = $request->job_id;
        
        if(!empty($adminCheck)) {
            $usertype = "admin";
        }else if(!empty($employerCheck)) {
            $usertype = "employer";
        }else if(!empty($staffCheck)){
            $usertype = "staff";
        }else{
            $usertype = "Not found";
        }
        
        $addComment = CandidateFeedback::insert([
            'job_id' => $job_id,
            'user_id' => $currentUser,
            'user_type' => $usertype,
            'candidate_id' => $request->candidate_id,
            'comment' => $request->comment,
            'type' => 'comment',
        ]);
        
        $candidateName = CandidateJobApply::where('id', $request->candidate_id)
                                            ->select(DB::raw("CONCAT(first_name, ' ', middle_name, ' ', last_name) as full_name"))
                                            ->value('full_name');
                    
                        Notification::create([
                            'user_id' => $currentUser,
                            'user_type' => $usertype,
                            'notification_title' => 'Comment for' . ' ' . $candidateName,
                            'notification_text' => $request->comment,
                            'mark_as_read' => '0',
                        ]);
                   
        

        return Response(['response' => "", 'message' => "Comment added successfully", 'status' => 200],200);
    }

    
    public function getCommentLog(Request $request, $id) {
        $currentUser = Auth::user()->id;
        $candidate = $request->candidate;
        $job_id = $request->job_id;
        $process_id = $request->process_id;
        $existingComments = [];
        if($request->comment_log_type == "all"){
            $existingComments = CandidateFeedback::where('candidate_id', $id)->where('job_id', $job_id)->orderBy('id', 'desc')->get();
            
            $existingCommentData = array();
            
            
            foreach($existingComments as $key => $value) {
                if($value->user_type == "staff") {
                    $username = Staff::where('id', $value->user_id)
                                ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                                ->first();
                } else {
                    $username = Employer::where('id', $value->user_id)
                                ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                                ->first();
                }
                if(!empty($job_id)){
                    $existingCommentData[$key]['job_id'] = $job_id;
                    $existingCommentData[$key]['job_name'] = Job::where('id', $job_id)->value('title');
                } else{
                    $existingCommentData[$key]['job_id'] = "";
                    $existingCommentData[$key]['job_name'] = "";
                }
            // $existingCommentData[$key]['job_name'] = !empty($value->job_id) ? Job::where('id', $value->job_id)->value('title') : "";

                $existingCommentData[$key]['candidate_id'] = $value->candidate_id;
                
                $existingCommentData[$key]['comment'] = $value->comment;
                $existingCommentData[$key]['id'] = $value->id;
                $existingCommentData[$key]['user_name'] = $username ? $username->full_name : 'Unknown'; // Fetch full_name or handle null case
                $existingCommentData[$key]['user_type'] = $value->user_type; // Correcting key name to 'user_type'
                // $existingCommentData[$key]['created'] = format_date($value->created);

                $existingCommentData[$key]['created'] = format_date($value->created);
                
                // Extract the time separately
                $existingCommentData[$key]['created_time'] = Carbon::parse($value->created)->format('g:i A');

                $existingCommentData[$key]['modified'] = format_date($value->modified);
                $existingCommentData[$key]['process_id'] = $value->process_id;
                $existingCommentData[$key]['process_name'] = Process::where('id', $value->process_id)->value('process_name');
            }

            return Response(['response' => $existingCommentData, 'status' => 200],200);
            
        } else{
            $existingComments = CandidateFeedback::where('candidate_id', $id)->where('job_id', $job_id)->where('process_id', $process_id)->orderBy('id', 'desc')->get();
            
            $existingCommentData = array();
            
            
            foreach($existingComments as $key => $value) {
                if($value->user_type == "staff") {
                    $username = Staff::where('id', $value->user_id)
                                ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                                ->first();
                } else {
                    $username = Employer::where('id', $value->user_id)
                                ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                                ->first();
                }
                if(!empty($job_id)){
                    $existingCommentData[$key]['job_id'] = $job_id;
                    $existingCommentData[$key]['job_name'] = Job::where('id', $job_id)->value('title');
                } else{
                    $existingCommentData[$key]['job_id'] = "";
                    $existingCommentData[$key]['job_name'] = "";
                }
            // $existingCommentData[$key]['job_name'] = !empty($value->job_id) ? Job::where('id', $value->job_id)->value('title') : "";

                $existingCommentData[$key]['candidate_id'] = $value->candidate_id;
                
                $existingCommentData[$key]['comment'] = $value->comment;
                $existingCommentData[$key]['id'] = $value->id;
                $existingCommentData[$key]['user_name'] = $username ? $username->full_name : 'Unknown'; // Fetch full_name or handle null case
                $existingCommentData[$key]['user_type'] = $value->user_type; // Correcting key name to 'user_type'
                // $existingCommentData[$key]['created'] = format_date($value->created);

                $existingCommentData[$key]['created'] = format_date($value->created);
                
                // Extract the time separately
                $existingCommentData[$key]['created_time'] = Carbon::parse($value->created)->format('g:i A');

                $existingCommentData[$key]['modified'] = format_date($value->modified);
                $existingCommentData[$key]['process_id'] = $process_id;
                $existingCommentData[$key]['process_name'] = Process::where('id', $process_id)->value('process_name');
            }

            return Response(['response' => $existingCommentData, 'status' => 200],200);
        }
        // $existingComments = CandidateFeedback::where('candidate_id', $id)->where('job_id', $job_id)->where('process_id', $process_id)->orderBy('id', 'desc')->get();
        
    }
    
    
    
    public function getUserlistForprocess(Request $request, $id) {
        // echo $id;
        $userList = DB::table('assign_users_to_processes')->where('process_id', $id)->get();      
        $userData = array();
        
        $currentUser = Auth::user()->id;
        // echo $currentUser;
        $adminCheck = Admin::where('id', $currentUser)->where('user_type',"admin")->first();
        $employerCheck = Employer::where('id', $currentUser)->where('user_type',"employer")->first();
        $staffCheck = Staff::where('id', $currentUser)->where('user_type',"staff")->first();

        foreach ($userList as $key => $value) {
            if(!empty($adminCheck)) {
                $user = Admin::find($value->user_id);
            } else if(!empty($employerCheck)) {
                $user = Staff::find($value->user_id);
            } else if(!empty($staffCheck)){
                $user = Staff::find($value->user_id);
            }
        
            // Check if user exists
            if ($user !== null) {
                $userData[$key]['id'] = $user->id;
                $userData[$key]['first_name'] = $user->first_name;
                $userData[$key]['last_name'] = $user->last_name;
            } else {
                
                // \Log::warning("User with ID {$value->user_id} not found in Admin model.");
            }
        }
        
        // Re-index the array numerically
        $userData = array_values($userData);
        return Response(['response' => $userData,  'message' => '', 'status' => 200], 200);
    }
    
    public function getProcessName(Request $request, $id) {
        $process = Process::where('id', $id)->first();
        if($process) {
            return Response(['response' => $process,  'message' => '', 'status' => 200], 200);
        }
    }

    public function getUserName(Request $request) {
        $currentUser = Auth::user()->id;
        $adminCheck = Admin::where('id', $currentUser)->where('user_type',"admin")->first();
        $employerCheck = Employer::where('id', $currentUser)->where('user_type',"employer")->first();
        $staffCheck = Staff::where('id', $currentUser)->where('user_type',"staff")->first();
        
        if(!empty($adminCheck)){
            $user = Admin::where('id', $id)->first();
            if($user) {
                return Response(['response' => $user,  'message' => '', 'status' => 200], 200);
            } else{
                return Response(['response' => "Not found",  'message' => '', 'status' => 200], 200);
            }
        } else if(!empty($employerCheck)){
            
            $ids = explode(',',$request->user_assigned); // Expecting array like [30, 20, 29]
    
            // Fetch all first names of users whose IDs match
            $users = Staff::whereIn('id', $ids)
                            ->get(['first_name', 'last_name']) // Get both columns
                            ->map(function ($user) {
                                return $user->first_name . ' ' . $user->last_name; // Concatenate first & last name
                            })
                            ->toArray();
        
            if (!empty($users)) {
                return response([
                    'response' => implode(', ', $users), // Convert array to comma-separated string
                    'message' => '',
                    'status' => 200
                ], 200);
            } else {
                return response([
                    'response' => "Not found",
                    'message' => '',
                    'status' => 200
                ], 200);
            }

            // $ids = $request->user_assigned;
            // $user = Staff::where('id', $id)->first();
            // if($user) {
            //     return Response(['response' => $user,  'message' => '', 'status' => 200], 200);
            // } else{
            //     return Response(['response' => "Not found",  'message' => '', 'status' => 200], 200);
            // }
        }else if(!empty($staffCheck)){
            $user = Staff::where('id', $id)->first();
            if($user) {
                return Response(['response' => $user,  'message' => '', 'status' => 200], 200);
            } else{
                return Response(['response' => "Not found",  'message' => '', 'status' => 200], 200);
            }
        }
        
        
    }
    
    public function saveJobsFromLinkedin(Request $request)
    {
        // Validate incoming data
        $validated = $request->validate([
            'company' => 'required|string',
            'title' => 'required|string',
            'location' => 'nullable|string',
            'posted' => 'nullable|string',
            'details' => 'nullable|string',
            'applyInfo' => 'nullable|string',
            'logo' => 'nullable|string',
            // 'jobTypes' => 'nullable|array',
            'description' => 'nullable|string',
            // 'skills' => 'nullable|array',
        ]);
    
        // Save into database
        $job = new SavedJob();
        $job->company_name       = $validated['company'];
        $job->job_title         = $validated['title'];
        $job->location      = $validated['location'] ?? null;
        $job->posted_date        = $validated['posted'] ?? null;
        $job->company_details       = $validated['details'] ?? null;
        $job->apply_info    = $validated['applyInfo'] ?? null;
        $job->logo          = $validated['logo'] ?? null;
    
        // Encode arrays before saving
        $job->job_types     = isset($validated['jobTypes']) ? json_encode($validated['jobTypes']) : null;
        $job->skills        = isset($validated['skills']) ? json_encode($validated['skills']) : null;
    
        $job->job_description   = $validated['description'] ?? null;
    
        $job->save();
    
        return Response(['response' => $job,  'message' => 'Job saved successfully', 'status' => 200], 200);

    }
    
    public function getSavedJobData(Request $request)
    {
        $job = SavedJob::all();
    
        return Response(['response' => $job,  'message' => 'Job saved successfully', 'status' => 200], 200);

    }
    
    
    public function logout(Request $request) {
        $request->user()->currentAccessToken()->delete();
        return response()->json(['message' => 'Logged out successfully', 'status' => 200], 200);
    }
    
    
    
    
            // 1. Basic Profile GET + POST
        public function getOrSaveCandidateDetails(Request $request)
        {
            $userId = Auth::id();
        
            if (!$userId) {
                return response()->json(['error' => 'Unauthenticated'], 401);
            }
        
            // GET: Return full data
            if ($request->isMethod('get')) {
                return $this->returnFullCandidateData($userId);
            }
        
            // POST: Save basic info
            if ($request->isMethod('post')) {
                $validator = Validator::make($request->all(), [
                    'first_name'    => 'required|string|max:255',
                    'last_name'     => 'required|string|max:255',
                    'email'         => 'required|email',
                    'phone'         => 'nullable|string|max:20',
                    'bio'           => 'nullable|string',
                    'location'      => 'nullable|string|max:255',
                    'profile_image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
                ]);
        
                if ($validator->fails()) {
                    return response()->json(['errors' => $validator->errors()->all()], 422);
                }
        
                // Prevent email conflict (except current user)
                $emailTaken = Candidate::where('email', $request->email)
                    ->where('id', '!=', $userId)
                    ->exists();
        
                if ($emailTaken) {
                    return response()->json(['error' => 'This email is already used by another account'], 422);
                }
        
                $candidate = Candidate::updateOrCreate(
                    ['id' => $userId],
                    [
                        'first_name'     => $request->first_name,
                        'last_name'      => $request->last_name,
                        'email'          => $request->email,
                        'contact_number' => $request->phone,
                        'bio'            => $request->bio,
                        'location'       => $request->location,
                    ]
                );
        
                // Handle image upload
                if ($request->hasFile('profile_image')) {
                    // Delete old image only if candidate already existed
                    if (!$candidate->wasRecentlyCreated && $candidate->getOriginal('profile_img')) {
                        $oldPath = public_path('uploads/profile/' . $candidate->getOriginal('profile_img'));
                        if (file_exists($oldPath)) {
                            unlink($oldPath);
                        }
                    }
        
                    $file = $request->file('profile_image');
                    $filename = time() . '_' . $file->getClientOriginalName();
                    $file->move(public_path('uploads/profile'), $filename);
        
                    $candidate->profile_img = $filename;
                    $candidate->save();
                }
        
                return $this->returnFullCandidateData($userId, 'Profile saved successfully');
            }
        
            return response()->json(['error' => 'Method not allowed'], 405);
        }
        
        // 2. Save full manual profile
        public function saveCandidateProfile(Request $request)
        {
            $data = $request->validate([
                'personal'     => 'required|array',
                'personal.email' => 'required|email',
                'education'    => 'required|array',
                'work'         => 'required|array',
                'skills'       => 'required|array',
                'projects'     => 'nullable|array',
                'achievements' => 'nullable|array',
                'summary'      => 'nullable|string',
            ]);
        
            $personal = $data['personal'];
        
            $candidate = Candidate::updateOrCreate(
                ['email' => $personal['email']],
                [
                    'first_name'     => $personal['first_name'] ?? null,
                    'last_name'      => $personal['last_name'] ?? null,
                    'contact_number' => $personal['phone'] ?? null,
                    'location'       => $personal['location'] ?? null,
                    'headline'       => $personal['headline'] ?? null,
                ]
            );
        
            CandidateProfile::updateOrCreate(
                ['candidate_id' => $candidate->id],
                [
                    'resource_type' => 'website',
                    'education'     => json_encode($data['education']),
                    'work'          => json_encode($data['work']),
                    'skills'        => json_encode($data['skills']),
                    'projects'      => json_encode($data['projects'] ?? []),       // FIXED TYPO
                    'achievements'  => json_encode($data['achievements'] ?? []),
                    'summary'       => $data['summary'] ?? null,
                ]
            );
        
            return $this->returnFullCandidateData($candidate->id, 'Profile saved successfully');
        }
        
        // 3. Save LinkedIn profile
        public function saveLinkedinProfile(Request $request)
        {
            $data = $request->validate([
                'name'       => 'required|string',
                'profileUrl' => 'required|url',
                'location'   => 'nullable|string',
                'headline'   => 'nullable|string',
                'profilePic' => 'nullable|url',
                'about'      => 'nullable|string',
                'education'  => 'nullable|array',
                'experience' => 'nullable|array',
                'skills'     => 'nullable|array',
            ]);
        
            $nameParts = explode(' ', trim($data['name']), 2);
            $firstName = $nameParts[0] ?? '';
            $lastName  = $nameParts[1] ?? '';
        
            $candidate = Candidate::updateOrCreate(
                ['linkedin_profile_url' => $data['profileUrl']],
                [
                    'first_name' => $firstName,
                    'last_name'  => $lastName,
                    'location'   => $data['location'],
                    'headline'   => $data['headline'],
                ]
            );
        
            CandidateProfile::updateOrCreate(
                ['candidate_id' => $candidate->id],
                [
                    'resource_type'     => 'linkedin',
                    'profile_image_url' => $data['profilePic'] ?? null,
                    'education'         => json_encode($data['education'] ?? []),
                    'work'              => json_encode($data['experience'] ?? []),
                    'skills'            => json_encode($data['skills'] ?? []),
                    'summary'           => $data['about'] ?? null,
                ]
            );
        
            return $this->returnFullCandidateData($candidate->id, 'LinkedIn profile imported successfully');
        }
        
        // FIXED: returnFullCandidateData (now private method)
        private function returnFullCandidateData($candidateId, $message = null)
        {
            $candidate = Candidate::with('profile')->findOrFail($candidateId);
        
            $profile = $candidate->profile;
        
            $education    = $profile?->education     ? json_decode($profile->education, true)     : [];
            $work         = $profile?->work          ? json_decode($profile->work, true)          : [];
            $skills       = $profile?->skills        ? json_decode($profile->skills, true)        : [];
            $projects     = $profile?->projects      ? json_decode($profile->projects, true)      : [];
            $achievements = $profile?->achievements ? json_decode($profile->achievements, true) : [];
        
            return response()->json([
                
                'message' => $message ?? 'Data retrieved successfully',
                'status' => 200,
                'candidate' => [
                    'id'                   => $candidate->id,
                    'first_name'           => $candidate->first_name,
                    'last_name'            => $candidate->last_name,
                    'email'                => $candidate->email ?? null,
                    'phone'                => $candidate->contact_number,
                    'bio'                  => $candidate->bio,
                    'location'             => $candidate->location,
                    'headline'             => $candidate->headline ?? null,
                    'linkedin_profile_url' => $candidate->linkedin_profile_url ?? null,
                    'profile_image'        => $candidate->profile_img
                        ? asset('uploads/profile/' . $candidate->profile_img)
                        : ($profile?->profile_image_url ?? null),
                ],
                'profile' => [
                    'resource_type' => $profile?->resource_type ?? 'website',
                    'summary'       => $profile?->summary ?? null,
                    'education'     => $education,
                    'work'          => $work,
                    'skills'        => $skills,
                    'projects'      => $projects,
                    'achievements'  => $achievements,
                ]
             
            ], 200);
        }

 // Forgot Password for Candidates
    public function candidateForgotPassword(Request $request) {
        try {
            if (empty($request->email)) {
                return Response(['response' => 'Email is required', 'status' => 500], 200);
            }

            $user = Candidate::where('email', $request->email)->get();

            if (count($user) > 0) {
                $token = Str::random(60);
                $domain = URL::to('/');
                $url = HTTP_PATH_FRONTEND . '/resetpassword/' . $token;

                $data['url'] = $url;
                $data['email'] = $request->email;
                $data['title'] = 'Reset Password';
                $data['body'] = 'Please click on the link below to reset your password';

                Mail::send('forgetpassword', ['data' => $data], function($message) use($data) {
                    $message->to($data['email']);
                    $message->subject($data['title']);
                });

                $datetime = Carbon::now()->format('Y-m-d H:i:s');

                $passwordReset = PasswordReset::firstOrNew(
                    ['email' => $request->email]
                );

                $passwordReset->email = $request->email;
                $passwordReset->token = $token;
                $passwordReset->created_at = $datetime;

                $passwordReset->save();

                return Response(['response' => 'success', 'message' => 'We have e-mailed your password reset link!', 'status' => 200], 200);
            } else {
                return Response(['response' => 'Email not registered', 'status' => 500], 200);
            }
        } catch (Exception $e) {
            return Response(['response' => $e->getMessage(), 'status' => 500], 200);
        }
    }

    // Reset Password for Candidates
    public function candidateResetPassword(Request $request) {
        $validator = Validator::make($request->all(), [
            'token' => 'required',
            'new_password' => 'required|min:8',
            'confirm_password' => 'required|same:new_password'
        ]);

        $validator->setAttributeNames([
            'token' => 'Token',
            'new_password' => 'New Password'
        ]);

        if ($validator->fails()) {
            return Response(['response' => $validator->errors(), 'status' => 500], 200);
        }

        $resetPassword = PasswordReset::where('token', $request->token)->first();

        if ($resetPassword) {
            // Find the user by email
            $user = Candidate::where('email', $resetPassword->email)->first();

            if ($user) {
                // Update the user's password
                $user->password = Hash::make($request->new_password);
                $user->save();

                // Delete the token
                PasswordReset::where('token', $request->token)->delete();

                return Response([
                    'response' => 'success',
                    'msg' => 'Your password has been reset successfully!',
                    'status' => 200
                ], 200);
            } else {
                return Response([
                    'success' => false,
                    'message' => 'User not found'
                ], 404);
            }
        } else {
            return Response([
                'success' => false,
                'message' => 'Invalid token'
            ], 401);
        }
    }

    public function listCandidateProfiles(Request $request) {
        $currentUser = Auth::user()->id;
        $profiles = CandidateProfile::where('candidate_id', $currentUser)->get();
        return Response(['response' => $profiles, 'message' => '', 'status' => 200], 200);
    }

    public function getCandidateProfile(Request $request, $id) {
        $currentUser = Auth::user()->id;
        $profile = CandidateProfile::where('id', $id)->where('candidate_id', $currentUser)->first();
        if (!$profile) {
            return Response(['response' => 'Profile not found', 'status' => 404], 404);
        }
        return Response(['response' => $profile, 'message' => '', 'status' => 200], 200);
    }
}
