<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\CandidateEducation;
use App\Models\CandidateExperience;
use App\Models\CandidateInterviewResponse;
use App\Models\CandidateInterviewSchedule;
use App\Models\CandidateInterviewStatus;
use App\Models\CandidateJobApply;
use App\Models\CandidateFeedback;
use App\Models\Job;
use App\Models\Process;
use App\Models\Employer;
use App\Models\Staff;
use App\Models\Skill;
use App\Models\Qualification;
use App\Models\StatusAttributes;
use App\Models\Notification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Mail;
use App\Models\EmailTemplate;
use App\Mail\SendMail;
use DateTime;





class InterviewController extends Controller
{
    //

    // public function interviewSchedule (Request $request) {

    //     $validator = Validator::make($request->all(), [
    //         'candidate_id' => 'required',
    //         'job_id' => 'required',
    //         'process_id' => 'required',
    //         'interview_type' => 'required',
    //         'user_assigned' => 'required',
    //         'interview_date' => 'required',
    //         'start_time' => 'required',
    //         'duration' => 'required',
    //         'comment' => 'required',
            
    //     ]);
        
    //     $validator->setAttributeNames([
    //         'candidate_id' => 'Candidate ID',
    //         'job_id' => 'Job ID',
    //         'process_id' => 'Process ID',
    //         'interview_type' => 'Interview Type',
    //         'user_assigned' => 'User Assigned',
    //         'interview_date' => 'Interview Date',
    //         'start_time' => 'Start Time',
    //         'duration' => 'Duration',
    //         'comment' => 'Comment',
    //     ]);

    //     if ($validator->fails()) {
    //         $msg = $this->validatersErrorString($validator->errors());
    //         return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
    //     } else {

    //         $interview = new CandidateInterviewResponse();
    //         $interview->candidate_id = $request->candidate_id;
    //         $interview->job_id = $request->job_id;
    //         $interview->process_id = $request->process_id;
    //         $interview->interview_type = $request->interview_type;
    //         $interview->interviewer_id = $request->user_assigned;
    //         $interview->assigned_by = Auth::user()->id;
    //         $interview->comment = $request->comment;
    //         $interview->interview_status = $request->interview_status;
    //         // $interview->round = $request->round;
    //         $interview->start_time = $request->start_time;
    //         $interview->duration = $request->duration;
    //         $interview->interview_date = $request->interview_date;
            
    //         $interview->save();
    //     }
    //     return Response(['response' => 'Success', 'message' => '', 'status' => 200], 200);
    // }
    
    // public function getStaffAvaibility(Request $request)
    // {
    //     $ids = explode(',', $request->ids); // Convert comma-separated IDs to an array
    //     $interviewDate = $request->interview_date;
    //     $startTime = $request->start_time;
    
    //     // Fetch unavailable staff based on interview date and start time
    //     // $unavailableStaff = CandidateInterviewSchedule::whereIn('assigned_to', $ids)
    //     //     ->where('interview_date', $interviewDate)
    //     //     ->where('start_time', $startTime)
    //     //     ->pluck('assigned_to') // Get only staff IDs that are unavailable
    //     //     ->toArray();
        
    //     $unavailableStaff = CandidateInterviewSchedule::where(function ($query) use ($ids) {
    //     foreach ($ids as $id) {
    //         $query->orWhereJsonContains('assigned_to', $id);
    //     }
    // })
    // ->where('interview_date', $interviewDate)
    // ->where('start_time', $startTime)
    // ->pluck('assigned_to')
    // ->toArray();
    
    // $unavailableStaffids = implode(',' , $unavailableStaff);
    // $unavailableStaffidss = json_decode($unavailableStaffids, true);
    // return Response(['response' => $ids, 'message' => 'success', 'status' => 200], 200);
    // exit();

    
    //     if (!empty($unavailableStaffidss)) {
    //         // Fetch staff names from the users or staff table
    //         $staffNames = DB::table('staffs') // Replace 'users' with the actual staff table name
    //             ->whereIn('id', $unavailableStaffidss)
    //             ->select('first_name', 'last_name')
    //             ->get()
    //             ->map(function ($staff) {
    //                 return $staff->first_name . ' ' . $staff->last_name;
    //             });
            
            
    //         return Response(['response' => $staffNames, 'message' => 'success', 'status' => 200], 200);
    
    //         // return response()->json([
    //         //     'status' => false,
    //         //     'message' => 'The following staff members are not available:',
    //         //     'unavailable_staff' => $staffNames
    //         // ]);
    //     }
        
    //     return Response(['response' => '', 'message' => 'All staffs are available', 'status' => 200], 200);
    
    //     // return response()->json(['status' => true, 'message' => 'All staff members are available.']);
    // }
    
    
//     public function getStaffAvaibility(Request $request)
// {
//     $ids = explode(',', $request->ids); // Convert comma-separated IDs to an array
//     $interviewDate = $request->interview_date;
//     $startTime = $request->start_time;
//     $page = $request->page;

//     // Fetch unavailable staff based on interview date and start time
//     $unavailableStaff = CandidateInterviewSchedule::where(function ($query) use ($ids) {
//         foreach ($ids as $id) {
//             $query->orWhereJsonContains('assigned_to', $id);
//         }
//     })
//     ->where('interview_date', $interviewDate)
//     ->where('start_time', $startTime)
//     ->pluck('assigned_to')
//     ->toArray();

//     // Decode JSON values from assigned_to and find common IDs
//     $commonIds = [];
//     foreach ($unavailableStaff as $jsonAssignedTo) {
//     // Decode the JSON data into an array
//     $assignedToArray = json_decode($jsonAssignedTo, true);

//     // Ensure it's always an array
//     if (!is_array($assignedToArray)) {
//         $assignedToArray = [$assignedToArray]; // Convert single value to an array if necessary
//     }

//     // Merge the common IDs after finding the intersection
//     $commonIds = array_merge($commonIds, array_intersect($ids, $assignedToArray));
// }

// // At this point, $commonIds will contain the unique IDs that are common between $ids and each $assignedToArray

    
// //     $assignedToArray = json_decode($value->assigned_to, true);

// // // Ensure it's an array
// // if (!is_array($assignedToArray)) {
// //     $assignedToArray = [$assignedToArray]; // Convert single value to an array
// // }

// // $commonIds = array_merge($commonIds, array_intersect($ids, $assignedToArray));


//     if (!empty($commonIds)) {
//         // Fetch staff names from the staff table
//         $staffNames = DB::table('staffs') // Change 'staffs' if needed
//             ->whereIn('id', $commonIds)
//             ->select('first_name', 'last_name')
//             ->get()
//             ->map(function ($staff) {
//                 return $staff->first_name . ' ' . $staff->last_name;
//             });

//         return Response([
//             'response' => $staffNames,
//             'message' => 'The following staff members are not available',
//             'status' => 200
//         ], 200);
//     }

//     return Response([
//         'response' => [],
//         'message' => 'All staff members are available',
//         'status' => 200
//     ], 200);
// }

public function getStaffAvailability(Request $request)
{
    $ids = explode(',', $request->ids); // Convert comma-separated IDs to an array
    $interviewDate = $request->interview_date;
    $startTime = $request->start_time;
    $page = $request->page;
    // Use 'id' from payload if 'current_schedule_id' is not provided
    $currentScheduleId = $request->current_schedule_id ?? $request->id;

    if ($page == 'reschedule') {
        // Fetch unavailable staff excluding the current schedule being updated
        $unavailableStaff = CandidateInterviewSchedule::where(function ($query) use ($ids) {
            foreach ($ids as $id) {
                $query->orWhereJsonContains('assigned_to', $id);
            }
        })
        ->where('start_time', $startTime)
        ->when($currentScheduleId, function ($query) use ($currentScheduleId) {
            return $query->where('id', '!=', $currentScheduleId); // Exclude the current schedule
        })
        ->pluck('assigned_to')
        ->toArray();
    } else {
        // Fetch unavailable staff based on interview date and start time
        $unavailableStaff = CandidateInterviewSchedule::where(function ($query) use ($ids) {
            foreach ($ids as $id) {
                $query->orWhereJsonContains('assigned_to', $id);
            }
        })
        ->where('interview_date', $interviewDate)
        ->where('start_time', $startTime)
        ->pluck('assigned_to')
        ->toArray();
    }

    // Decode JSON values from assigned_to and find common IDs
    $commonIds = [];
    foreach ($unavailableStaff as $jsonAssignedTo) {
        $assignedToArray = json_decode($jsonAssignedTo, true);

        // Ensure it's always an array
        if (!is_array($assignedToArray)) {
            $assignedToArray = [$assignedToArray]; // Convert single value to array
        }

        // Merge the common IDs after finding the intersection
        $commonIds = array_merge($commonIds, array_intersect($ids, $assignedToArray));
    }

    // Remove duplicates from commonIds
    $commonIds = array_unique($commonIds);

    if (!empty($commonIds)) {
        // Fetch staff names from the staff table
        $staffNames = DB::table('staffs')
            ->whereIn('id', $commonIds)
            ->select('first_name', 'last_name')
            ->get()
            ->map(function ($staff) {
                return $staff->first_name . ' ' . $staff->last_name;
            });

        return response([
            'response' => $staffNames,
            'message' => 'The following staff members are not available',
            'status' => 200
        ], 200);
    }

    return response([
        'response' => [],
        'message' => 'All staff members are available',
        'status' => 200
    ], 200);
}





    
    public function interviewSchedule (Request $request, $id, $job_id) {
        
        $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($request->all())){
            $validator = Validator::make($request->all(), [
                'candidate_id' => 'required',
                'job_id' => 'required',
                'process_id' => 'required',
                'interview_type' => 'required',
                'user_assigned' => 'required',
                'interview_date' => 'required',
                'start_time' => 'required',
                'duration' => 'required',
                'comment' => 'required',
                
            ]);
            
            $validator->setAttributeNames([
                'candidate_id' => 'Candidate ID',
                'job_id' => 'Job ID',
                'process_id' => 'Process ID',
                'interview_type' => 'Interview Type',
                'user_assigned' => 'User Assigned',
                'interview_date' => 'Interview Date',
                'start_time' => 'Start Time',
                'duration' => 'Duration',
                'comment' => 'Comment',
            ]);
    
            if ($validator->fails()) {
                $msg = $this->validatersErrorString($validator->errors());
                return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
            } else {
                
                

    
                // $interview = new CandidateInterviewSchedule();
                // $interview->candidate_id = $request->candidate_id;
                // $interview->job_id = $request->job_id;
                // $interview->process_id = $request->process_id;
                // $interview->interview_type = $request->interview_type;
                // $interview->interview_type_detail = $request->interview_type_detail;
                // $interview->assigned_to = $request->user_assigned;
                // $interview->assigned_by = Auth::user()->id;
                // $interview->comment = $request->comment;
                // $interview->interview_status = $request->interview_status;
                // // $interview->round = $request->round;
                // $interview->start_time = $request->start_time;
                // $interview->duration = $request->duration;
                // $interview->interview_date = $request->interview_date;
                // $interview->interview_cancelation_status = 0;
                
                if(!empty($employerCheck)){
                    $interview = new CandidateInterviewSchedule();
                    $interview->candidate_id = $request->candidate_id;
                    $interview->job_id = $request->job_id;
                    $interview->process_id = $request->process_id;
                    $interview->interview_type = $request->interview_type;
                    $interview->interview_type_detail = $request->interview_type_detail;
                    $interview->assigned_to = json_encode(explode(',', $request->user_assigned)); // Convert to JSON array
                    $interview->assigned_by = Auth::user()->id;
                    $interview->comment = $request->comment;
                    $interview->interview_status = $request->interview_status;
                    $interview->start_time = $request->start_time;
                    $interview->duration = $request->duration;
                    $interview->interview_date = $request->interview_date;
                    $interview->interview_cancelation_status = 0;
                    $interview->save();
                    
                    $candidateEmail = CandidateJobApply::where('id', $request->candidate_id)->value('email');
                    // print_r($candidateEmail);
                    // exit();
                    $candidate = CandidateJobApply::where('id', $request->candidate_id)->select('first_name', 'last_name')->first();
                    $candidateName = $candidate ? $candidate->first_name . ' ' . $candidate->last_name : '';
                    
                    $employerCompanyName = Employer::where('id', $employerCheck)->value('company_name');
                    
                    // $interviewer = Staff::where('id', $request->user_assigned)->select('first_name', 'last_name')->first();
                    // $interviewerName = $interviewer ? $interviewer->first_name . ' ' . $interviewer->last_name : '';
                    
                    $userAssignedIds = explode(',', $request->user_assigned); // Convert to array
    
                    if (count($userAssignedIds) == 1) {
                        // If only one ID, fetch a single interviewer
                        $interviewer = Staff::where('id', trim($userAssignedIds[0]))->select('first_name', 'last_name')->first();
                        $interviewerName = $interviewer ? $interviewer->first_name . ' ' . $interviewer->last_name : '';
                    } else {
                        // If multiple IDs, fetch all names and join them with commas
                        $interviewers = Staff::whereIn('id', $userAssignedIds)->select('first_name', 'last_name')->get();
                        $interviewerName = $interviewers->map(function ($interviewer) {
                            return $interviewer->first_name . ' ' . $interviewer->last_name;
                        })->implode(', ');
                    }
    
                    
                    $interviewDate = Carbon::parse($request->interview_date)->format('d M Y');
    
                    
                    $interviewDuration = $request->duration;
    
                    if ($interviewDuration == 1) {
                        $formattedDuration = $interviewDuration . ' Hour';
                    } else {
                        $formattedDuration = $interviewDuration . ' Minutes';
                    }
                    
                    $startTime = $request->start_time; 
    
                    $formattedStartTime = date("g:i A", strtotime($startTime . ":00"));
                    
    
    
                    
                    
                    $emailTemplate = EmailTemplate::where('id', 3)->first();
                    
                    $toRepArray = ['[!candidate_name!]', '[!company_name!]', '[!date!]', '[!time!]', '[!mode_of_interview!]', '[!detail!]', '[!duration!]', '[!interviewer!]'];
                    $fromRepArray = [$candidateName, $employerCompanyName, 
                                    $interviewDate, $formattedStartTime, $request->interview_type, $request->interview_type_detail,
                                    $formattedDuration, $interviewerName];
                    
                    
                    $emailSubject = str_replace($toRepArray, $fromRepArray, $emailTemplate->subject);
                    $emailBody = str_replace($toRepArray, $fromRepArray, $emailTemplate->template);
                    
                    $logo = Employer::where('id', $currentUser)->value('company_logo');
                    
                    if(!empty($logo)){
                        $logoPath = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $logo;
                    } else{
                        $logoPath = LOGO_PATH;
                    }
                    
                    
                    // Send the email
                    try {
                        Mail::to($candidateEmail)->send(new SendMail($emailBody, $emailSubject, $logoPath));
                    } catch (\Exception $e) {
                        return response()->json(['error' => 'Failed to send email.', 'message' => $e->getMessage()], 500);
                    }
                    
                    
                    //email functionality for staff
                   // Convert "30, 39" into an array [30, 39]
                    $userAssignedArray = explode(',', $request->user_assigned);
                    $userAssignedArray = array_map('trim', $userAssignedArray); // Trim spaces
                    
                    // Fetch staff emails
                    $staffEmails = Staff::whereIn('id', $userAssignedArray)->pluck('email_address');
                    
                    // Fetch staff names as an associative array
                    $staffDetails = Staff::whereIn('id', $userAssignedArray)->get(['first_name', 'last_name']);
                    
                    $position = CandidateJobApply::where('id', $request->candidate_id)->value('job_form_id');
                    $positionName = Job::where('id', $position)->value('title');
                    
                    $staffEmailTemplate = EmailTemplate::where('id', 9)->first();
                    
                    try {
                        foreach ($staffDetails as $index => $staff) {
                            $staffName = trim($staff->first_name . ' ' . $staff->last_name); // Combine first & last name
                            
                            $toArray = ['[!staff_name!]', '[!candidate_name!]', '[!date!]', '[!position_name!]', '[!time!]', '[!duration!]', '[!mode!]', '[!detail!]'];
                            $fromArray = [$staffName, $candidateName, $interviewDate, $positionName, $formattedStartTime, $formattedDuration, $request->interview_type, $request->interview_type_detail];
                    
                            // Replace placeholders with actual values
                            $staffSubject = str_replace($toArray, $fromArray, $staffEmailTemplate->subject);
                            $staffBody = str_replace($toArray, $fromArray, $staffEmailTemplate->template);
                    
                            // Send email
                            Mail::to($staffEmails[$index])->send(new SendMail($staffBody, $staffSubject, $logoPath));
                        }
                    } catch (\Exception $e) {
                        return response()->json(['error' => 'Failed to send emails.', 'message' => $e->getMessage()], 500);
                    }
                    
                    $processName = Process::where('id', $request->process_id)->value('process_name');
                    
                    $assignedUserIds = explode(',', $request->user_assigned);
                    
                    foreach ($assignedUserIds as $UserId) {
                        Notification::create([
                            'user_id' => trim($UserId),
                            'user_type' => 'staff',
                            'notification_title' => 'Interview Scheduled',
                            'notification_text' => 'You have been assigned to conduct' . ' ' . $processName . ' ' . 'for' . ' ' . $candidateName . ' ' . 'on' . ' ' . $interviewDate . '.',
                            'mark_as_read' => '0',
                        ]);
                    }
                    
                } else{
                    $interview = new CandidateInterviewSchedule();
                    $interview->candidate_id = $request->candidate_id;
                    $interview->job_id = $request->job_id;
                    $interview->process_id = $request->process_id;
                    $interview->interview_type = $request->interview_type;
                    $interview->interview_type_detail = $request->interview_type_detail;
                    $interview->assigned_to = json_encode(explode(',', $request->user_assigned)); // Convert to JSON array
                    $interview->assigned_by = $staffCheck->employer_id;
                    $interview->assigned_by_staff = Auth::user()->id;
                    $interview->comment = $request->comment;
                    $interview->interview_status = $request->interview_status;
                    $interview->start_time = $request->start_time;
                    $interview->duration = $request->duration;
                    $interview->interview_date = $request->interview_date;
                    $interview->interview_cancelation_status = 0;
                    $interview->save();
                    
                    $candidateEmail = CandidateJobApply::where('id', $request->candidate_id)->value('email');
                    // print_r($candidateEmail);
                    // exit();
                    $candidate = CandidateJobApply::where('id', $request->candidate_id)->select('first_name', 'last_name')->first();
                    $candidateName = $candidate ? $candidate->first_name . ' ' . $candidate->last_name : '';
                    
                    $employerCompanyName = Employer::where('id', $staffCheck->employer_id)->value('company_name');
                    
                    // $interviewer = Staff::where('id', $request->user_assigned)->select('first_name', 'last_name')->first();
                    // $interviewerName = $interviewer ? $interviewer->first_name . ' ' . $interviewer->last_name : '';
                    
                    $userAssignedIds = explode(',', $request->user_assigned); // Convert to array
    
                    if (count($userAssignedIds) == 1) {
                        // If only one ID, fetch a single interviewer
                        $interviewer = Staff::where('id', trim($userAssignedIds[0]))->select('first_name', 'last_name')->first();
                        $interviewerName = $interviewer ? $interviewer->first_name . ' ' . $interviewer->last_name : '';
                    } else {
                        // If multiple IDs, fetch all names and join them with commas
                        $interviewers = Staff::whereIn('id', $userAssignedIds)->select('first_name', 'last_name')->get();
                        $interviewerName = $interviewers->map(function ($interviewer) {
                            return $interviewer->first_name . ' ' . $interviewer->last_name;
                        })->implode(', ');
                    }
    
                    
                    $interviewDate = Carbon::parse($request->interview_date)->format('d M Y');
    
                    
                    $interviewDuration = $request->duration;
    
                    if ($interviewDuration == 1) {
                        $formattedDuration = $interviewDuration . ' Hour';
                    } else {
                        $formattedDuration = $interviewDuration . ' Minutes';
                    }
                    
                    $startTime = $request->start_time; 
    
                    $formattedStartTime = date("g:i A", strtotime($startTime . ":00"));
                    
    
    
                    
                    
                    $emailTemplate = EmailTemplate::where('id', 3)->first();
                    
                    $toRepArray = ['[!candidate_name!]', '[!company_name!]', '[!date!]', '[!time!]', '[!mode_of_interview!]', '[!detail!]', '[!duration!]', '[!interviewer!]'];
                    $fromRepArray = [$candidateName, $employerCompanyName, 
                                    $interviewDate, $formattedStartTime, $request->interview_type, $request->interview_type_detail,
                                    $formattedDuration, $interviewerName];
                    
                    
                    $emailSubject = str_replace($toRepArray, $fromRepArray, $emailTemplate->subject);
                    $emailBody = str_replace($toRepArray, $fromRepArray, $emailTemplate->template);
                    
                    $logo = Employer::where('id', $staffCheck->employer_id)->value('company_logo');
                    
                    if(!empty($logo)){
                        $logoPath = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $logo;
                    } else{
                        $logoPath = LOGO_PATH;
                    }
                    
                    
                    // Send the email
                    try {
                        Mail::to($candidateEmail)->send(new SendMail($emailBody, $emailSubject, $logoPath));
                    } catch (\Exception $e) {
                        return response()->json(['error' => 'Failed to send email.', 'message' => $e->getMessage()], 500);
                    }
                    
                    
                    //email functionality for staff
                   // Convert "30, 39" into an array [30, 39]
                    $userAssignedArray = explode(',', $request->user_assigned);
                    $userAssignedArray = array_map('trim', $userAssignedArray); // Trim spaces
                    
                    // Fetch staff emails
                    $staffEmails = Staff::whereIn('id', $userAssignedArray)->pluck('email_address');
                    
                    // Fetch staff names as an associative array
                    $staffDetails = Staff::whereIn('id', $userAssignedArray)->get(['first_name', 'last_name']);
                    
                    $position = CandidateJobApply::where('id', $request->candidate_id)->value('job_form_id');
                    $positionName = Job::where('id', $position)->value('title');
                    
                    $staffEmailTemplate = EmailTemplate::where('id', 9)->first();
                    
                    try {
                        foreach ($staffDetails as $index => $staff) {
                            $staffName = trim($staff->first_name . ' ' . $staff->last_name); // Combine first & last name
                            
                            $toArray = ['[!staff_name!]', '[!candidate_name!]', '[!date!]', '[!position_name!]', '[!time!]', '[!duration!]', '[!mode!]', '[!detail!]'];
                            $fromArray = [$staffName, $candidateName, $interviewDate, $positionName, $formattedStartTime, $formattedDuration, $request->interview_type, $request->interview_type_detail];
                    
                            // Replace placeholders with actual values
                            $staffSubject = str_replace($toArray, $fromArray, $staffEmailTemplate->subject);
                            $staffBody = str_replace($toArray, $fromArray, $staffEmailTemplate->template);
                    
                            // Send email
                            Mail::to($staffEmails[$index])->send(new SendMail($staffBody, $staffSubject, $logoPath));
                        }
                    } catch (\Exception $e) {
                        return response()->json(['error' => 'Failed to send emails.', 'message' => $e->getMessage()], 500);
                    }
                    
                    $processName = Process::where('id', $request->process_id)->value('process_name');
                    
                    $assignedUserIds = explode(',', $request->user_assigned);
                    
                    foreach ($assignedUserIds as $UserId) {
                        Notification::create([
                            'user_id' => trim($UserId),
                            'user_type' => 'staff',
                            'notification_title' => 'Interview Scheduled',
                            'notification_text' => 'You have been assigned to conduct' . ' ' . $processName . ' ' . 'for' . ' ' . $candidateName . ' ' . 'on' . ' ' . $interviewDate . '.',
                            'mark_as_read' => '0',
                        ]);
                    }
                    
                }
                
                
                // for employer 
                // $interview = new CandidateInterviewSchedule();
                // $interview->candidate_id = $request->candidate_id;
                // $interview->job_id = $request->job_id;
                // $interview->process_id = $request->process_id;
                // $interview->interview_type = $request->interview_type;
                // $interview->interview_type_detail = $request->interview_type_detail;
                // $interview->assigned_to = json_encode(explode(',', $request->user_assigned)); // Convert to JSON array
                // $interview->assigned_by = Auth::user()->id;
                // $interview->comment = $request->comment;
                // $interview->interview_status = $request->interview_status;
                // $interview->start_time = $request->start_time;
                // $interview->duration = $request->duration;
                // $interview->interview_date = $request->interview_date;
                // $interview->interview_cancelation_status = 0;
                // $interview->save();

                
                // $userAssignedIds = explode(',', $request->user_assigned); // Convert "30,39" to an array [30, 39]

                // foreach ($userAssignedIds as $userId) {
                //     $interview = new CandidateInterviewSchedule();
                //     $interview->candidate_id = $request->candidate_id;
                //     $interview->job_id = $request->job_id;
                //     $interview->process_id = $request->process_id;
                //     $interview->interview_type = $request->interview_type;
                //     $interview->interview_type_detail = $request->interview_type_detail;
                //     $interview->assigned_to = trim($userId); // Assign each user separately
                //     $interview->assigned_by = Auth::user()->id;
                //     $interview->comment = $request->comment;
                //     $interview->interview_status = $request->interview_status;
                //     $interview->start_time = $request->start_time;
                //     $interview->duration = $request->duration;
                //     $interview->interview_date = $request->interview_date;
                //     $interview->interview_cancelation_status = 0;
                
                //     $interview->save(); // Save interview record for each assigned user
                // }
                
                $interview->save();
                
            }
            return Response(['response' => 'Success', 'message' => 'Interview scheduled successfully', 'status' => 200], 200);
        }else {
            
            if(!empty($adminCheck)) {
                $candidateData = CandidateJobApply::where('id', $id)->first();
                $processData = Process::where('status', 1)->get();
                $userList = Admin::where('id', '!=', 1)->get();
                
                $existingInterview = CandidateInterviewResponse::where('candidate_id', $id)->get();
            } else if(!empty($employerCheck)){
                $candidate = CandidateJobApply::where('id', $id)->first();
                $candidateData = array();
                
                $candidateData = [
                    'contact_number' => $candidate->contact_number,
                    'created_at' => $candidate->created_at,
                    'date_of_birth' => $candidate->date_of_birth,
                    'document_cv' => !empty($candidate->document_cv) ? DISPLAY_RESUME_PATH.$candidate->document_cv : "",
                    'draft_status' => $candidate->draft_status,
                    'education_details' => $candidate->education_details,
                    'email' => $candidate->email,
                    'employer_id' => $candidate->employer_id,
                    'experience_details' => $candidate->experience_details,
                    'first_name' => $candidate->first_name,
                    'gender' => $candidate->gender,
                    'id' => $candidate->id,
                    'interview_status' => $candidate->interview_status,
                    'is_interview_scheduled' => $candidate->is_interview_scheduled,
                    'job_application_status' => $candidate->job_application_status,
                    'job_form_id' => $candidate->job_form_id,
                    'last_name' => $candidate->last_name,
                    'marital_status' => $candidate->martial_status,  // Note: make sure 'marital_status' is correctly spelled in your database and code
                    'middle_name' => $candidate->middle_name,
                    'offer_letter_status' => $candidate->offer_letter_status,
                    'on_boarding_status' => $candidate->on_boarding_status,
                    'physically_challenged' => $candidate->physically_challenged,
                    'process_id' => $candidate->process_id,
                    'profile_image' => !empty($candidate->profile_img) ? DISPLAY_FULL_PROFILE_IMAGE_PATH . $candidate->profile_img : "",
                    'slug' => $candidate->slug,
                    'status' => $candidate->status,
                    'updated_at' => $candidate->updated_at,
                ];

                
                // $processData = Process::where('employer_id',  $currentUser)->where('status', 1)->get();
                $processList = DB::table('candidate_interview_journeys')
                    ->where('candidate_id', $id)
                    ->where('job_id', $job_id)
                    ->get();
                
                $processData = [];
                
                foreach ($processList as $key => $value) {
                    $processData[$key]['id'] = $value->id;
                    $processData[$key]['candidate_id'] = $value->candidate_id;
                    $processData[$key]['job_id'] = $value->job_id;
                    $processData[$key]['completion_status'] = $value->completion_status;
                    $processData[$key]['process_id'] = $value->process_id;
                
                    // Fetch process_name if process_id is present
                    if ($value->process_id) {
                        $process = process::where('id', $value->process_id)->select('process_name')->first();
                        $processData[$key]['process_name'] = $process ? $process->process_name : "Not Available";
                    } else {
                        $processData[$key]['process_name'] = "Not Available";
                    }
                
                    $processData[$key]['order_number'] = $value->order_number;
                    $processData[$key]['created_at'] = $value->created_at;
                }


                $userList = Staff::where('employer_id', $currentUser)->get();
                
                // $existingInterview = CandidateInterviewSchedule::where('candidate_id', $id)->where('job_id',$job_id)->get();
                
                // $processId = $existingInterview[0]['process_id'];
                // $candidateId = $existingInterview[0]['candidate_id'];
                // $interviewDate = $existingInterview[0]['interview_date'];
                // $startTime = $existingInterview[0]['start_time'];
                
                // $processCount = 0;
                // $candidateCount = 0;
                // $interviewDateCount = 0;
                // $startTimeCount = 0;
                
                
                // foreach($existingInterview as $key => $value){
                //     if($value->process_id == $processId){
                //         $processCount += 1;
                //     }
                //     if($value->candidate_id == $candidateId){
                //         $candidateCount += 1;
                //     }
                //     if($value->interview_date == $interviewDate){
                //         $interviewDateCount += 1;
                //     }
                //     if($value->start_time == $startTime){
                //         $startTimeCount += 1;
                //     }
                // }
                
                // if($processCount == $candidateCount == $interviewDateCount == $startTimeCount == $existingInterview.lenth){
                //     $updatedExistingInterview => [
                //         'comment' => $existingInterview[0]['comment'];
                //         'created_at' => $existingInterview[0]['created_at'];
                //         'duration' => $existingInterview[0]['duration'];
                //         'interview_date' => $existingInterview[0]['interview_date'];
                //         'interview_type' => $existingInterview[0]['interview_type'];
                //         'interview_type_detail' => $existingInterview[0]['interview_type_detail'];
                //         'process_id' => $existingInterview[0]['process_id'];
                //         'start_time' => $existingInterview[0]['start_time'];
                //         'user_assgined' => 
                //     ];
                // }
                
                
                $existingInterview = CandidateInterviewSchedule::where('candidate_id', $id)->where('job_id', $job_id)->get();
                
                // if ($existingInterview->isEmpty()) {
                //     return response()->json(['message' => 'No interview found'], 404);
                // }
                
                // // Check if all candidate_id, process_id, start_time, and interview_date values are the same
                // $allSameCandidate = $existingInterview->pluck('candidate_id')->unique()->count() === 1;
                // $allSameProcess = $existingInterview->pluck('process_id')->unique()->count() === 1;
                // $allSameInterviewDate = $existingInterview->pluck('interview_date')->unique()->count() === 1;
                // $allSameStartTime = $existingInterview->pluck('start_time')->unique()->count() === 1;
                
                // if ($allSameCandidate && $allSameProcess && $allSameInterviewDate && $allSameStartTime) {
                //     // Extract unique user_assigned IDs
                //     $userAssignedIds = $existingInterview->pluck('user_assgined')->unique()->toArray();
                
                //     // Fetch names from Staff model
                //     $userNames = Staff::whereIn('id', $userAssignedIds)->pluck('firs')->toArray();
                
                //     $updatedExistingInterview = [
                //         'comment' => $existingInterview[0]['comment'],
                //         'created_at' => $existingInterview[0]['created_at'],
                //         'duration' => $existingInterview[0]['duration'],
                //         'interview_date' => $existingInterview[0]['interview_date'],
                //         'interview_type' => $existingInterview[0]['interview_type'],
                //         'interview_type_detail' => $existingInterview[0]['interview_type_detail'],
                //         'process_id' => $existingInterview[0]['process_id'],
                //         'start_time' => $existingInterview[0]['start_time'],
                //         'user_assigned' => $userNames, // Assign names instead of IDs
                //     ];
                
                //     return response()->json($updatedExistingInterview);
                // }
                
                // return response()->json(['message' => 'Inconsistent interview data found'], 400);

                
                $email_template_id = 3;
            } else if(!empty($staffCheck)){
                
                $candidate = CandidateJobApply::where('id', $id)->first();
                $candidateData = array();
                
                $candidateData = [
                    'contact_number' => $candidate->contact_number,
                    'created_at' => $candidate->created_at,
                    'date_of_birth' => $candidate->date_of_birth,
                    'document_cv' => !empty($candidate->document_cv) ? DISPLAY_RESUME_PATH.$candidate->document_cv : "",
                    'draft_status' => $candidate->draft_status,
                    'education_details' => $candidate->education_details,
                    'email' => $candidate->email,
                    'employer_id' => $candidate->employer_id,
                    'experience_details' => $candidate->experience_details,
                    'first_name' => $candidate->first_name,
                    'gender' => $candidate->gender,
                    'id' => $candidate->id,
                    'interview_status' => $candidate->interview_status,
                    'is_interview_scheduled' => $candidate->is_interview_scheduled,
                    'job_application_status' => $candidate->job_application_status,
                    'job_form_id' => $candidate->job_form_id,
                    'last_name' => $candidate->last_name,
                    'marital_status' => $candidate->martial_status,  // Note: make sure 'marital_status' is correctly spelled in your database and code
                    'middle_name' => $candidate->middle_name,
                    'offer_letter_status' => $candidate->offer_letter_status,
                    'on_boarding_status' => $candidate->on_boarding_status,
                    'physically_challenged' => $candidate->physically_challenged,
                    'process_id' => $candidate->process_id,
                    'profile_image' => !empty($candidate->profile_img) ? DISPLAY_FULL_PROFILE_IMAGE_PATH . $candidate->profile_img : "",
                    'slug' => $candidate->slug,
                    'status' => $candidate->status,
                    'updated_at' => $candidate->updated_at,
                ];

                
                // $processData = Process::where('employer_id',  $currentUser)->where('status', 1)->get();
                $processList = DB::table('candidate_interview_journeys')
                    ->where('candidate_id', $id)
                    ->where('job_id', $job_id)
                    ->get();
                
                $processData = [];
                
                foreach ($processList as $key => $value) {
                    $processData[$key]['id'] = $value->id;
                    $processData[$key]['candidate_id'] = $value->candidate_id;
                    $processData[$key]['job_id'] = $value->job_id;
                    $processData[$key]['completion_status'] = $value->completion_status;
                    $processData[$key]['process_id'] = $value->process_id;
                
                    // Fetch process_name if process_id is present
                    if ($value->process_id) {
                        $process = process::where('id', $value->process_id)->select('process_name')->first();
                        $processData[$key]['process_name'] = $process ? $process->process_name : "Not Available";
                    } else {
                        $processData[$key]['process_name'] = "Not Available";
                    }
                
                    $processData[$key]['order_number'] = $value->order_number;
                    $processData[$key]['created_at'] = $value->created_at;
                }


                $userList = Staff::where('employer_id', $staffCheck->employer_id)->get();
                
                $existingInterview = CandidateInterviewSchedule::where('candidate_id', $id)->where('job_id', $job_id)->get();
                
                $email_template_id = 3;
                
            } else{
                $candidateData = CandidateJobApply::where('id', $id)->first();
                $processData = Process::where('status', 1)->get();
                $userList = Admin::where('id', '!=', 1)->get();
                
                $existingInterview = CandidateInterviewSchedule::where('candidate_id', $id)->get();
            }
            
            // check for same interviews
            // $existingInterview = CandidateInterviewSchedule::where('candidate_id', $id)->where('job_id', $job_id)->get();
            
            // $existingInterviewData = array();
                
            // if ($existingInterview->isEmpty()) {
            //     return response()->json(['message' => 'No interview found'], 404);
            // }
                
            // Check if all candidate_id, process_id, start_time, and interview_date values are the same
            // $allSameCandidate = $existingInterview->pluck('candidate_id')->unique()->count() === 1;
            // $allSameProcess = $existingInterview->pluck('process_id')->unique()->count() === 1;
            // $allSameInterviewDate = $existingInterview->pluck('interview_date')->unique()->count() === 1;
            // $allSameStartTime = $existingInterview->pluck('start_time')->unique()->count() === 1;
            
            // return Response(['response' => [$allSameCandidate, $allSameProcess, $allSameInterviewDate, $allSameStartTime], 'message' => '', 'status' => 200], 200);
            // exit();
                
            // if ($allSameCandidate && $allSameProcess && $allSameInterviewDate && $allSameStartTime) {
            //     // Extract unique user_assigned IDs
            //     $userAssignedIds = $existingInterview->pluck('assigned_to')->unique()->toArray();
            //     // $userAssignedIds = [22];
            //     // Fetch names from Staff model
            //     $userNames = Staff::whereIn('id', $userAssignedIds)->pluck('first_name')->toArray();
                
            //     $existingInterviewData[] = [
            //         'comment' => $existingInterview[0]['comment'],
            //         'created_at' => format_date($existingInterview[0]['created_at']),
            //         'duration' => $existingInterview[0]['duration'],
            //         'interview_date' => $existingInterview[0]['interview_date'] ? format_date($existingInterview[0]['interview_date']) : "Interview not scheduled",
            //         'interview_type' => $existingInterview[0]['interview_type'],
            //         'interview_type_detail' => $existingInterview[0]['interview_type_detail'],
            //         'process_id' => $existingInterview[0]['process_id'],
            //         'start_time' => $existingInterview[0]['start_time'],
            //         'user_assigned' => $userAssignedIds, // Assign names instead of IDs
            //     ];
                                    
            //         // return response()->json($existingInterviewData);
            // } else{
                   
            //     $existingInterviewData = $existingInterview->groupBy(function ($item) {
            //         return $item->process_id . '-' . $item->interview_date . '-' . $item->start_time;
            //     })->map(function ($group) {
            //             return [
            //                 'id' => $group->first()->id,
            //                 'process_id' => $group->first()->process_id,
            //                 'user_assigned' => $group->pluck('assigned_to')->unique()->toArray(), // Collect all unique assigned users
            //                 'interview_date' => $group->first()->interview_date ? format_date($group->first()->interview_date) : "Interview not scheduled",
            //                 'start_time' => $group->first()->start_time,
            //                 'duration' => $group->first()->duration,
            //                 'interview_type' => $group->first()->interview_type,
            //                 'interview_type_detail' => $group->first()->interview_type_detail,
            //                 'comment' => $group->first()->comment,
            //                 'created_at' => format_date($group->first()->created_at),
            //             ];
            //     })->values()->toArray(); // Reset keys

                   
            // }
            
                $existingInterview = CandidateInterviewSchedule::where('candidate_id', $id)->where('job_id', $job_id)->get();
                $existingInterviewData = array();
                
                foreach ($existingInterview as $key => $value) {
                    $existingInterviewData[$key]['id'] = $value->id;
                    $existingInterviewData[$key]['process_id'] = $value->process_id;
                    
                    $processName = Process::where('id', $value->process_id)->value('process_name');
                    
                    $existingInterviewData[$key]['process_name'] = $processName;
                    
                    // Decode the assigned_to JSON field to get user IDs
                    $userAssignedIds = json_decode($value->assigned_to, true);
                    $existingInterviewData[$key]['user_assigned'] = $userAssignedIds;
                    
                    // Fetch user names based on the IDs in assigned_to
                    $userNames = [];
                    if (!empty($userAssignedIds)) {
                        // Fetch first_name and last_name from the Staff model
                        $staffDetails = Staff::whereIn('id', $userAssignedIds)
                                             ->select('first_name', 'last_name')
                                             ->get()
                                             ->map(function ($staff) {
                                                 return $staff->first_name . ' ' . $staff->last_name; // Combine first and last name
                                             })
                                             ->toArray();
                        $userNames = $staffDetails;
                    }
                    $existingInterviewData[$key]['staff_names'] = $userNames; // Add full names to the array
                
                    $existingInterviewData[$key]['interview_date'] = $value->interview_date 
                        ? Carbon::parse($value->interview_date)->toDateString() 
                        : "Interview not scheduled";
                        
                    $existingInterviewData[$key]['formatted_date'] = $value->interview_date 
                                                                ? Carbon::parse($value->interview_date)->format('d M, Y') 
                                                                : "Interview not scheduled";
                    $existingInterviewData[$key]['start_time'] = $value->start_time;
                    
                    $existingInterviewData[$key]['formatted_time'] = date("g:i A", strtotime($value->start_time . ":00"));
                    
                    $interviewDuration = $value->duration;
                    if ($interviewDuration == 1) {
                        $existingInterviewData[$key]['duration'] = $interviewDuration . ' Hour';
                    } else {
                        $existingInterviewData[$key]['duration'] = $interviewDuration . ' Minutes';
                    }
                    
                    $existingInterviewData[$key]['interview_type'] = $value->interview_type;
                    $existingInterviewData[$key]['interview_type_detail'] = $value->interview_type_detail;
                    $existingInterviewData[$key]['comment'] = $value->comment;
                    $existingInterviewData[$key]['created_at'] = format_date($value->created_at);
                    $existingInterviewData[$key]['interview_completion_status'] = $value->interview_completion_status;
                }
            
            
            $email_template_id = 3;

            return Response(['response' => ['candidateData' => $candidateData, 'processData' => $processData, 'userList' => $userList, 'existingInterview' => $existingInterviewData, 'email_template_id' => $email_template_id],  'message' => '', 'status' => 200], 200);
        }
    }
    
    public function resendInterviewScheduleEmail(Request $request, $id){
        
        $interviewDetails = CandidateInterviewSchedule::where('id', $id)->first();
        
        
        $candidate = CandidateJobApply::where('id', $interviewDetails->candidate_id)->first();
        $candidateName = $candidate->first_name . ' ' . $candidate->last_name;
        $candidateEmail = $candidate->email;
        
        
        $employerDetail = Employer::where('id', $interviewDetails->assigned_by)->first();
        $employerCompanyName = $employerDetail->company_name;
        
        
        $interviewDate = Carbon::parse($interviewDetails->interview_date)->format('d M Y');
        
        $startTime = $interviewDetails->start_time; 

        $formattedStartTime = date("g:i A", strtotime($startTime . ":00"));
        
        $interviewDuration = $interviewDetails->duration;

        if ($interviewDuration == 1) {
            $formattedDuration = $interviewDuration . ' Hour';
        } else {
            $formattedDuration = $interviewDuration . ' Minutes';
        }
        
        
        // $userAssignedIds = explode(',', $interviewDetails->assigned_to);
        
        // if (count($userAssignedIds) == 1) {
        //     // If only one ID, fetch a single interviewer
        //     $interviewer = Staff::where('id', trim($userAssignedIds[0]))->select('first_name', 'last_name')->first();
        //     $interviewerName = $interviewer ? $interviewer->first_name . ' ' . $interviewer->last_name : '';
        // } else {
        //     // If multiple IDs, fetch all names and join them with commas
        //     $interviewers = Staff::whereIn('id', $userAssignedIds)->select('first_name', 'last_name')->get();
        //     $interviewerName = $interviewers->map(function ($interviewer) {
        //         return $interviewer->first_name . ' ' . $interviewer->last_name;
        //     })->implode(', ');
        // }
        
        $userAssignedIds = json_decode($interviewDetails->assigned_to, true);

if (!is_array($userAssignedIds)) {
    $userAssignedIds = []; // Ensure it's an array to prevent errors
}

if (count($userAssignedIds) == 1) {
    // If only one ID, fetch a single interviewer
    $interviewer = Staff::where('id', trim($userAssignedIds[0]))->select('first_name', 'last_name')->first();
    $interviewerName = $interviewer ? $interviewer->first_name . ' ' . $interviewer->last_name : '';
} else {
    // If multiple IDs, fetch all names and join them with commas
    $interviewers = Staff::whereIn('id', $userAssignedIds)->select('first_name', 'last_name')->get();
    $interviewerName = $interviewers->map(function ($interviewer) {
        return $interviewer->first_name . ' ' . $interviewer->last_name;
    })->implode(', ');
}

        
        
        $emailTemplate = EmailTemplate::where('id', 3)->first();
        
        $toRepArray = ['[!candidate_name!]', '[!company_name!]', '[!date!]', '[!time!]', '[!mode_of_interview!]', '[!detail!]', '[!duration!]', '[!interviewer!]'];
        $fromRepArray = [$candidateName, $employerCompanyName, $interviewDate, $formattedStartTime, $interviewDetails->interview_type, $interviewDetails->interview_type_detail,
                            $formattedDuration, $interviewerName];
                
                
        $emailSubject = str_replace($toRepArray, $fromRepArray, $emailTemplate->subject);
        $emailBody = str_replace($toRepArray, $fromRepArray, $emailTemplate->template);
                
        $logo = $employerDetail->company_logo;
                
        if(!empty($logo)){
            $logoPath = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $logo;
        } else{
            $logoPath = LOGO_PATH;
        }
                
                
        // Send the email
        try {
            Mail::to($candidateEmail)->send(new SendMail($emailBody, $emailSubject, $logoPath));
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to send email.', 'message' => $e->getMessage()], 500);
        }
        
        return Response(['response' => '', 'message' => 'Interview Schedule Email resend successfully', 'status' => 200], 200);
        
        
    }
    
    
    public function candidateInterviewStatus (Request $request, $id) {
        if(empty($request->all())){
            $validator = Validator::make($request->all(), [
                'candidate_id' => 'required',
                'process_id' => 'required',
                'user_assigned' => 'required',
                'round' => 'required',
                'comment' => 'required',

            ]);
            
            $validator->setAttributeNames([
                'candidate_id' => 'Candidate ID',
                'process_id' => 'Process ID',
                'user_assigned' => 'User Assigned',
                'round' => 'Round',
                'comment' => 'Comment',
            ]);
    
            if ($validator->fails()) {
                $msg = $this->validatersErrorString($validator->errors());
                return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
            }
        
        }
            
            else {
                CandidateInterviewStatus::create([
                    'candidate_id' => $request->candidate_id,
                    'user_assigned' => $request->user_id,
                    'assigned_by' => Auth::user()->id,
                    'process_id' => $request->process_id,
                    'comment' => $request->comment,
                    'feedback' => $request->feedback,
                    'status' => $request->status,
                    'round' => $request->round,
                    'interview_scheduled' => $request->interview_scheduled,
                ]);

                return Response(['response' => 'Success', 'message' => 'Your interview has been scheduled', 'status' => 200], 200);
            }
        
    }
    
    public function interviewAssignedToUser(Request $request, $id) {
        
        $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)){
            
        } else if(!empty($employerCheck)){
            $interviewAssigned = CandidateInterviewSchedule::where('assigned_by', $id)->orderBy('id','desc')->get();
    
            $interviewAssignedData = array();
            foreach ($interviewAssigned as $key => $value) {
                // $assignedUser = Staff::where('id', $value->assigned_to)->select('first_name', 'last_name')->first();
                // $interviewAssignedData[$key]['user_assigned'] = $assignedUser ? $assignedUser->first_name . ' ' . $assignedUser->last_name : '';
                
                $assignedUserIds = json_decode($value->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();
                
                    $interviewAssignedData[$key]['user_assigned'] = implode(', ', $assignedUsers);
                } else {
                    $interviewAssignedData[$key]['user_assigned'] = '';
                }


                
                $processAssigned = Process::where('id', $value->process_id)->select('process_name')->first();
                $interviewAssignedData[$key]['process_id'] = $processAssigned ? $processAssigned->process_name : '';
                
                $candidateName = CandidateJobApply::where('id', $value->candidate_id)->select('first_name', 'last_name')->first();
                $interviewAssignedData[$key]['candidate_id'] = $candidateName ? $candidateName->first_name . ' ' . $candidateName->last_name : '';
                
                $candidateDetails = CandidateJobApply::where('id', $value->candidate_id)->first();
                $candidateDetailsData = array();
        
                if ($candidateDetails) {
                    $candidateDetailsData['id'] = $candidateDetails->id;
                    $candidateDetailsData['job_form_id'] = $candidateDetails->job_form_id;
                    $candidateDetailsData['first_name'] = $candidateDetails->first_name;
                    $candidateDetailsData['middle_name'] = $candidateDetails->middle_name;
                    $candidateDetailsData['last_name'] = $candidateDetails->last_name;
                    if($candidateDetails->gender == 1){
                        $candidateDetailsData['gender'] = "Male";
                    } else if($candidateDetails->gender == 2){
                        $candidateDetailsData['gender'] = "Female";
                    }else{
                        $candidateDetailsData['gender'] = "Other";
                    }
                    
                    if(!empty($candidateDetails->profile_img)){
                        $candidateDetailsData['profile_image'] = DISPLAY_FULL_PROFILE_IMAGE_PATH . $candidateDetails->profile_img;
                    }else{
                        $candidateDetailsData['profile_image'] = "";
                    }
                    
                    if(!empty($candidateDetails->document_cv)){
                        $candidateDetailsData['cv_document'] = DISPLAY_RESUME_PATH.$candidateDetails->document_cv;
                    }else{
                        $candidateDetailsData['cv_document'] = "";
                    }
                    
                    $candidateDetailsData['email_address'] = $candidateDetails->email;
                    $candidateDetailsData['contact'] = $candidateDetails->contact_number;
                    $date = new DateTime($candidateDetails->date_of_birth);
                    $candidateDetailsData['date_of_birth'] = $date->format('d M Y');

                    if($candidateDetails->martial_status == 1){
                        $candidateDetailsData['martial_status'] = "Single";
                    } else if($candidateDetails->martial_status == 2){
                        $candidateDetailsData['martial_status'] = "Married";
                    } else if($candidateDetails->martial_status == 3){
                        $candidateDetailsData['martial_status'] = "Divorced";
                    }else{
                        $candidateDetailsData['martial_status'] = "N/A";
                    }
                    if($candidateDetails->physically_challenged == 1){
                        $candidateDetailsData['physically_challenged'] = "Yes";
                    } else if($candidateDetails->physically_challenged == 2){
                        $candidateDetailsData['physically_challenged'] = "No";
                    } else if($candidateDetails->physically_challenged == 3){
                        $candidateDetailsData['physically_challenged'] = "Prefer not to say";
                    }else{
                        $candidateDetailsData['physically_challenged'] = "N/A";
                    }
                    $candidateDetailsData['address'] = $candidateDetails->address;
        
                    // Fetch the job title
                    $job = Job::find($candidateDetails->job_form_id);
                    if ($job) {
                        $candidateDetailsData['job_name'] = $job->title;
                        $candidateDetailsData['slug'] = $job->slug;
                    } else {
                        $candidateDetailsData['job_name'] = 'Job Not Available';
                        $candidateDetailsData['slug'] = null;
                    }
                    
                    $candidateDetailsData['cover_letter_title'] = $candidateDetails->cover_letter_title;
                    $candidateDetailsData['cover_letter_description'] = $candidateDetails->cover_letter_description;
                    
                    $candidateDetailsData['additional_data'] = $candidateDetails->custom_fields_data ? json_decode($candidateDetails->custom_fields_data, true) : [];
        
                    $education = CandidateEducation::where('candidate_job_apply_id', $candidateDetails->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;
                    }
                    $candidateDetailsData['education'] = $educationData;
        
                    $experience = CandidateExperience::where('candidate_job_apply_id', $candidateDetails->id)->get();
                    $experienceData = array();
                    foreach ($experience as $expKey => $expValue) {
                        $experienceData[$expKey]['id'] = $expValue->id;
                        $experienceData[$expKey]['organisation_name'] = $expValue->organisation_name;
                        // $experienceData[$expKey]['designation'] = $expValue->designation;
                        
                        $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]['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));
                    }
                    $candidateDetailsData['experience'] = $experienceData;
                }
                
                // echo $value->candidate_id;
                $interviewDetails = CandidateInterviewSchedule::where('candidate_id',$value->candidate_id)->where('process_id', $value->process_id)->first();
                // return Response(['response' =>$interviewDetails, 'message' => '', 'status' => 200 ], 200);
                // exit();
                $interviewDetailsData = array();
                
                
                $interviewDetailsData['id'] = $interviewDetails->id;
                $interviewDetailsData['job_id'] = $interviewDetails->job_id;
                $interviewDetailsData['process_id'] = $value->process_id;
                $interviewDetailsData['process_name'] = Process::where('id',$value->process_id)->select('process_name')->first()->process_name ?? 'Not Available';
                $interviewDetailsData['interview_type'] = $interviewDetails->interview_type;
                $interviewDetailsData['interview_type_detail'] = $interviewDetails->interview_type_detail;
                $interviewDetailsData['interview_date'] = date('d M Y',strtotime($value->interview_date));
                $interviewDetailsData['duration'] = $interviewDetails->duration;
                $interviewDetailsData['round'] = $interviewDetails->round;
                $interviewDetailsData['comment'] = $interviewDetails->comment;
                $interviewDetailsData['assigned_by'] = Employer::where('id', $interviewDetails->assigned_by)
                    ->select(DB::raw("CONCAT(first_name, ' ', last_name) as full_name"))
                    ->first()
                    ->full_name;
                $interviewDetailsData['interview_completion_status'] = $interviewDetails->interview_completion_status;
                $interviewDetailsData['interview_cancelation_status'] = $interviewDetails->interview_cancelation_status;
                $interviewDetailsData['interview_cancelation_reason'] = $interviewDetails->interview_cancelation_reason;
                $interviewDetailsData['created_at'] = format_date($interviewDetails->created_at);
                
    
                
        
                $interviewAssignedData[$key]['candidateDetails'] = $candidateDetailsData;
                $interviewAssignedData[$key]['candidateInterviewDetails'] = $interviewDetailsData;
                $interviewAssignedData[$key]['id'] = $value->id;
                $interviewAssignedData[$key]['interview_date'] = $value->interview_date ? Carbon::parse($value->interview_date)->toDateString() : "Interview not scheduled";
                $interviewAssignedData[$key]['is_interview_scheduled'] = $value->interview_scheduled;
                $interviewAssignedData[$key]['start_time'] = $value->start_time;
                $interviewAssignedData[$key]['duration'] = $value->duration;
                $interviewAssignedData[$key]['interview_type'] = $value->interview_type;
                
                $interviewAssignedData[$key]['comment'] = $value->comment;
                $interviewAssignedData[$key]['created_at'] = format_date($value->created_at);
                
                
                $jobValue = Job::where('id', $interviewDetails->job_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'];
                }
                
                
                $interviewAssignedData[$key]['jobData'] = $jobData;
                
            }
            
            $interview_cancellation_email_template_id = 5;
            
        } else if(!empty($staffCheck)){

            $interviewAssigned = CandidateInterviewSchedule::whereJsonContains('assigned_to', (string) $id)
                                                            ->orderBy('id', 'desc')
                                                            ->get();
                                                            
            // return response(['response' => $interviewAssigned, 'status' => 200], 200);

    
            $interviewAssignedData = array();
            foreach ($interviewAssigned as $key => $value) {
                $assignedUser = Staff::where('id', $value->assigned_to)->select('first_name', 'last_name')->first();
                $interviewAssignedData[$key]['user_assigned'] = $assignedUser ? $assignedUser->first_name . ' ' . $assignedUser->last_name : '';
                
                $processAssigned = Process::where('id', $value->process_id)->select('process_name')->first();
                $interviewAssignedData[$key]['process_id'] = $processAssigned ? $processAssigned->process_name : '';
                
                $candidateName = CandidateJobApply::where('id', $value->candidate_id)->select('first_name', 'last_name')->first();
                $interviewAssignedData[$key]['candidate_id'] = $candidateName ? $candidateName->first_name . ' ' . $candidateName->last_name : '';
                
                $candidateDetails = CandidateJobApply::where('id', $value->candidate_id)->first();
                $candidateDetailsData = array();
        
                if ($candidateDetails) {
                    $candidateDetailsData['id'] = $candidateDetails->id;
                    $candidateDetailsData['job_form_id'] = $candidateDetails->job_form_id;
                    $candidateDetailsData['first_name'] = $candidateDetails->first_name;
                    
                    if(!empty($candidateDetails->middle_name)){
                        $candidateDetailsData['middle_name'] = $candidateDetails->middle_name;
                    } else{
                        $candidateDetailsData['middle_name'] = 'N/A';
                    }
                    
                    
                    $candidateDetailsData['last_name'] = $candidateDetails->last_name;
                    // $candidateDetailsData['gender'] = $candidateDetails->gender;
                    if($candidateDetails->gender == 1){
                        $candidateDetailsData['gender'] = "Male";
                    } else if($candidateDetails->gender == 2){
                        $candidateDetailsData['gender'] = "Female";
                    }else{
                        $candidateDetailsData['gender'] = "Other";
                    }
                    
                    if(!empty($candidateDetails->profile_img)){
                        $candidateDetailsData['profile_image'] = DISPLAY_FULL_PROFILE_IMAGE_PATH . $candidateDetails->profile_img;
                    }else{
                        $candidateDetailsData['profile_image'] = "";
                    }
                    
                    // $candidateDetailsData['profile_image'] = $candidateDetails->profile_image;
                    $candidateDetailsData['email_address'] = $candidateDetails->email;
                    $candidateDetailsData['contact'] = $candidateDetails->contact_number;
                    
                    $date = new DateTime($candidateDetails->date_of_birth);
                    $candidateDetailsData['date_of_birth'] = $date->format('d M Y');
                    
                    // $candidateDetailsData['date_of_birth'] = $candidateDetails->date_of_birth;
                    // $candidateDetailsData['martial_status'] = $candidateDetails->martial_status;
                    if($candidateDetails->martial_status == 1){
                        $candidateDetailsData['martial_status'] = "Single";
                    } else if($candidateDetails->martial_status == 2){
                        $candidateDetailsData['martial_status'] = "Married";
                    } else if($candidateDetails->martial_status == 3){
                        $candidateDetailsData['martial_status'] = "Divorced";
                    }else{
                        $candidateDetailsData['martial_status'] = "N/A";
                    }
                    // $candidateDetailsData['physically_challenged'] = $candidateDetails->physically_challenged;
                    if($candidateDetails->physically_challenged == 1){
                        $candidateDetailsData['physically_challenged'] = "Yes";
                    } else if($candidateDetails->physically_challenged == 2){
                        $candidateDetailsData['physically_challenged'] = "No";
                    } else if($candidateDetails->physically_challenged == 3){
                        $candidateDetailsData['physically_challenged'] = "Prefer not to say";
                    }else{
                        $candidateDetailsData['physically_challenged'] = "N/A";
                    }
                    
                    if(!empty($candidateDetails->document_cv)){
                        $candidateDetailsData['document_cv'] = DISPLAY_RESUME_PATH.$candidateDetails->document_cv;
                    }else{
                        $candidateDetailsData['document_cv'] = "";
                    }
                    
                    $candidateDetailsData['address'] = $candidateDetails->address;
        
                    // Fetch the job title
                    $job = Job::find($candidateDetails->job_form_id);
                    if ($job) {
                        $candidateDetailsData['job_name'] = $job->title;
                        $candidateDetailsData['slug'] = $job->slug;
                    } else {
                        $candidateDetailsData['job_name'] = 'Job Not Available';
                        $candidateDetailsData['slug'] = null;
                    }
                    
                    
                    $candidateDetailsData['cover_letter_title'] = $candidateDetails->cover_letter_title;
                    $candidateDetailsData['cover_letter_description'] = $candidateDetails->cover_letter_description;
                    
                    $candidateDetailsData['additional_data'] = $candidateDetails->custom_fields_data ? json_decode($candidateDetails->custom_fields_data, true) : [];
        
                    $education = CandidateEducation::where('candidate_job_apply_id', $candidateDetails->id)->get();
                    $educationData = array();
                    foreach ($education as $eduKey => $eduValue) {
                        $educationData[$eduKey]['id'] = $eduValue->id;
                        $educationData[$eduKey]['qualification_id'] = $eduValue->qualification_id 
                            ? Qualification::find($eduValue->qualification_id)->qualification_name ?? "Not available"
                            : "Not available";
                        $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;
                    }
                    $candidateDetailsData['education'] = $educationData;
        
                    $experience = CandidateExperience::where('candidate_job_apply_id', $candidateDetails->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));
                    }
                    $candidateDetailsData['experience'] = $experienceData;
                }
                
                // echo $value->candidate_id;
                $interviewDetails = CandidateInterviewSchedule::where('candidate_id',$value->candidate_id)->first();
                $interviewDetailsData = array();
                
                
                $interviewDetailsData['id'] = $value->id;
                $interviewDetailsData['job_id'] = $value->job_id;
                $interviewDetailsData['process_id'] = $value->process_id;
                // if(!empty($value->process_id)){
                //     $interviewDetailsData['process_name'] = Process::where('id',$value->process_id)->select('process_name')->first()->process_name;
                // } else{
                //     $interviewDetailsData['process_name'] = 'Process name not available';
                // }
                
                if (!empty($value->process_id)) {
                    $process = Process::where('id', $value->process_id)->select('process_name')->first();
                    if ($process) {
                        $interviewDetailsData['process_name'] = $process->process_name;
                    } else {
                        $interviewDetailsData['process_name'] = 'Process name not available';
                    }
                } else {
                    $interviewDetailsData['process_name'] = 'Process name not available';
                }

                $interviewDetailsData['interview_type'] = $value->interview_type;
                $interviewDetailsData['interview_type_detail'] = $value->interview_type_detail;
                $interviewDetailsData['interview_date'] = date('d M Y',strtotime($value->interview_date));
                $interviewDetailsData['start_time'] = $value->start_time;
                $interviewDetailsData['duration'] = $value->duration;
                $interviewDetailsData['round'] = $interviewDetails->round;
                $interviewDetailsData['comment'] = $value->comment;
                $interviewDetailsData['assigned_by'] = Employer::where('id', $interviewDetails->assigned_by)
                    ->select(DB::raw("CONCAT(first_name, ' ', last_name) as full_name"))
                    ->first()
                    ->full_name;
                $interviewDetailsData['interview_completion_status'] = $value->interview_completion_status;
                $interviewDetailsData['created_at'] = format_date($value->created_at);
                
                $assignedToIds = json_decode($value->assigned_to, true); // Decode JSON string to array
                if (!empty($assignedToIds)) {
                    // $staffMembers = Staff::whereIn('id', $assignedToIds)
                    //     ->select(DB::raw("CONCAT(first_name, ' ', last_name) as full_name"))
                    //     ->get();
                    
                    $staffMembers = Staff::whereIn('id', $assignedToIds)
                                    ->select(DB::raw("CONCAT(first_name, ' ', last_name) as full_name"))
                                    ->get();
                    $panelNames = $staffMembers->pluck('full_name')->implode(', ');
                    $interviewDetailsData['panelist_names'] = $panelNames ?: 'No panel members assigned';
                } else {
                    $interviewDetailsData['panelist_names'] = 'No panel members assigned';
                }
                
    
                
        
                $interviewAssignedData[$key]['candidateDetails'] = $candidateDetailsData;
                $interviewAssignedData[$key]['candidateInterviewDetails'] = $interviewDetailsData;
                // $interviewAssignedData[$key]['id'] = $value->id;
                // $interviewAssignedData[$key]['interview_date'] = $value->interview_date ? $value->interview_date : "Interview not scheduled";
                // $interviewAssignedData[$key]['is_interview_scheduled'] = $value->interview_scheduled;
                // $interviewAssignedData[$key]['start_time'] = $value->start_time;
                // $interviewAssignedData[$key]['duration'] = $value->duration;
                // $interviewAssignedData[$key]['interview_type'] = $value->interview_type;
                // $interviewAssignedData[$key]['interview_completion_status'] = $value->interview_completion_status;
                // $interviewAssignedData[$key]['comment'] = $value->comment;
                // $interviewAssignedData[$key]['created_at'] = format_date($value->created_at);
                
                
            }
             $interview_cancellation_email_template_id = 5;
            
            return Response(['response' => ['interview_cancellation_email_template_id' => $interview_cancellation_email_template_id, 'interviewAssignedData' => $interviewAssignedData], 'message' => 'Interviewer Assigned', 'status' => 200], 200);

        }
        
            $status = StatusAttributes::where(function ($query) use ($employerCheck) {
                $query->where('employer_id', $employerCheck->id)
                    ->orWhere('employer_id', 0);
            })
                ->where('status', 1)
                // ->orderBy('id', 'desc')
                ->get();
        
        $interview_cancellation_email_template_id = 5;
        return Response(['response' => ['interview_cancellation_email_template_id' => $interview_cancellation_email_template_id, 'interviewAssignedData' => $interviewAssignedData, 'statusList' => $status], 'message' => 'Interviewer Assigned', 'status' => 200], 200);
    }
    
    public function staffInterviewList(Request $request, $id){
        
        $employerId = Staff::where('id', $id)->value('employer_id');
        
        $interviewAssigned = CandidateInterviewSchedule::where('assigned_by', $employerId)->orderBy('id','desc')->get();
    
            $interviewAssignedData = array();
            foreach ($interviewAssigned as $key => $value) {
                // $assignedUser = Staff::where('id', $value->assigned_to)->select('first_name', 'last_name')->first();
                // $interviewAssignedData[$key]['user_assigned'] = $assignedUser ? $assignedUser->first_name . ' ' . $assignedUser->last_name : '';
                
                $assignedUserIds = json_decode($value->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();
                
                    $interviewAssignedData[$key]['user_assigned'] = implode(', ', $assignedUsers);
                } else {
                    $interviewAssignedData[$key]['user_assigned'] = '';
                }


                
                $processAssigned = Process::where('id', $value->process_id)->select('process_name')->first();
                $interviewAssignedData[$key]['process_id'] = $processAssigned ? $processAssigned->process_name : '';
                
                $candidateName = CandidateJobApply::where('id', $value->candidate_id)->select('first_name', 'last_name')->first();
                $interviewAssignedData[$key]['candidate_id'] = $candidateName ? $candidateName->first_name . ' ' . $candidateName->last_name : '';
                
                $candidateDetails = CandidateJobApply::where('id', $value->candidate_id)->first();
                $candidateDetailsData = array();
        
                if ($candidateDetails) {
                    $candidateDetailsData['id'] = $candidateDetails->id;
                    $candidateDetailsData['job_form_id'] = $candidateDetails->job_form_id;
                    $candidateDetailsData['first_name'] = $candidateDetails->first_name;
                    $candidateDetailsData['middle_name'] = $candidateDetails->middle_name;
                    $candidateDetailsData['last_name'] = $candidateDetails->last_name;
                    if($candidateDetails->gender == 1){
                        $candidateDetailsData['gender'] = "Male";
                    } else if($candidateDetails->gender == 2){
                        $candidateDetailsData['gender'] = "Female";
                    }else{
                        $candidateDetailsData['gender'] = "Other";
                    }
                    
                    if(!empty($candidateDetails->profile_img)){
                        $candidateDetailsData['profile_image'] = DISPLAY_FULL_PROFILE_IMAGE_PATH . $candidateDetails->profile_img;
                    }else{
                        $candidateDetailsData['profile_image'] = "";
                    }
                    
                    if(!empty($candidateDetails->document_cv)){
                        $candidateDetailsData['cv_document'] = DISPLAY_RESUME_PATH.$candidateDetails->document_cv;
                    }else{
                        $candidateDetailsData['cv_document'] = "";
                    }
                    
                    $candidateDetailsData['email_address'] = $candidateDetails->email;
                    $candidateDetailsData['contact'] = $candidateDetails->contact_number;
                    $date = new DateTime($candidateDetails->date_of_birth);
                    $candidateDetailsData['date_of_birth'] = $date->format('d M Y');

                    if($candidateDetails->martial_status == 1){
                        $candidateDetailsData['martial_status'] = "Single";
                    } else if($candidateDetails->martial_status == 2){
                        $candidateDetailsData['martial_status'] = "Married";
                    } else if($candidateDetails->martial_status == 3){
                        $candidateDetailsData['martial_status'] = "Divorced";
                    }else{
                        $candidateDetailsData['martial_status'] = "N/A";
                    }
                    if($candidateDetails->physically_challenged == 1){
                        $candidateDetailsData['physically_challenged'] = "Yes";
                    } else if($candidateDetails->physically_challenged == 2){
                        $candidateDetailsData['physically_challenged'] = "No";
                    } else if($candidateDetails->physically_challenged == 3){
                        $candidateDetailsData['physically_challenged'] = "Prefer not to say";
                    }else{
                        $candidateDetailsData['physically_challenged'] = "N/A";
                    }
                    $candidateDetailsData['address'] = $candidateDetails->address;
        
                    // Fetch the job title
                    $job = Job::find($candidateDetails->job_form_id);
                    if ($job) {
                        $candidateDetailsData['job_name'] = $job->title;
                        $candidateDetailsData['slug'] = $job->slug;
                    } else {
                        $candidateDetailsData['job_name'] = 'Job Not Available';
                        $candidateDetailsData['slug'] = null;
                    }
                    
                    $candidateDetailsData['cover_letter_title'] = $candidateDetails->cover_letter_title;
                    $candidateDetailsData['cover_letter_description'] = $candidateDetails->cover_letter_description;
                    
                    $candidateDetailsData['additional_data'] = $candidateDetails->custom_fields_data ? json_decode($candidateDetails->custom_fields_data, true) : [];
        
                    $education = CandidateEducation::where('candidate_job_apply_id', $candidateDetails->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;
                    }
                    $candidateDetailsData['education'] = $educationData;
        
                    $experience = CandidateExperience::where('candidate_job_apply_id', $candidateDetails->id)->get();
                    $experienceData = array();
                    foreach ($experience as $expKey => $expValue) {
                        $experienceData[$expKey]['id'] = $expValue->id;
                        $experienceData[$expKey]['organisation_name'] = $expValue->organisation_name;
                        // $experienceData[$expKey]['designation'] = $expValue->designation;
                        
                        $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]['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));
                    }
                    $candidateDetailsData['experience'] = $experienceData;
                }
                
                // echo $value->candidate_id;
                $interviewDetails = CandidateInterviewSchedule::where('candidate_id', $value->candidate_id)->where('process_id', $value->process_id)->first();
                // return Response(['response' =>$interviewDetails, 'message' => '', 'status' => 200 ], 200);
                // exit();
                $interviewDetailsData = array();
                
                
                $interviewDetailsData['id'] = $interviewDetails->id;
                $interviewDetailsData['job_id'] = $interviewDetails->job_id;
                $interviewDetailsData['process_id'] = $value->process_id;
                $interviewDetailsData['process_name'] = Process::where('id',$value->process_id)->select('process_name')->first()->process_name ?? 'Not Available';
                $interviewDetailsData['interview_type'] = $interviewDetails->interview_type;
                $interviewDetailsData['interview_type_detail'] = $interviewDetails->interview_type_detail;
                $interviewDetailsData['interview_date'] = date('d M Y',strtotime($value->interview_date));
                $interviewDetailsData['duration'] = $interviewDetails->duration;
                $interviewDetailsData['round'] = $interviewDetails->round;
                $interviewDetailsData['comment'] = $interviewDetails->comment;
                $interviewDetailsData['assigned_by'] = Employer::where('id', $interviewDetails->assigned_by)
                    ->select(DB::raw("CONCAT(first_name, ' ', last_name) as full_name"))
                    ->first()
                    ->full_name;
                $interviewDetailsData['interview_completion_status'] = $interviewDetails->interview_completion_status;
                $interviewDetailsData['interview_cancelation_status'] = $interviewDetails->interview_cancelation_status;
                $interviewDetailsData['interview_cancelation_reason'] = $interviewDetails->interview_cancelation_reason;
                $interviewDetailsData['created_at'] = format_date($interviewDetails->created_at);
                
    
                
        
                $interviewAssignedData[$key]['candidateDetails'] = $candidateDetailsData;
                $interviewAssignedData[$key]['candidateInterviewDetails'] = $interviewDetailsData;
                $interviewAssignedData[$key]['id'] = $value->id;
                $interviewAssignedData[$key]['interview_date'] = $value->interview_date ? Carbon::parse($value->interview_date)->toDateString() : "Interview not scheduled";
                $interviewAssignedData[$key]['is_interview_scheduled'] = $value->interview_scheduled;
                $interviewAssignedData[$key]['start_time'] = $value->start_time;
                $interviewAssignedData[$key]['duration'] = $value->duration;
                $interviewAssignedData[$key]['interview_type'] = $value->interview_type;
                
                $interviewAssignedData[$key]['comment'] = $value->comment;
                $interviewAssignedData[$key]['created_at'] = format_date($value->created_at);
                
                
                $jobValue = Job::where('id', $interviewDetails->job_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'];
                }
                
                
                $interviewAssignedData[$key]['jobData'] = $jobData;
                
            }
            
            $status = StatusAttributes::where(function ($query) use ($employerId) {
                $query->where('employer_id', $employerId)
                    ->orWhere('employer_id', 0);
            })
                ->where('status', 1)
                // ->orderBy('id', 'desc')
                ->get();
        
        $interview_cancellation_email_template_id = 5;
        return Response(['response' => ['interview_cancellation_email_template_id' => $interview_cancellation_email_template_id, 'interviewAssignedData' => $interviewAssignedData, 'statusList' => $status], 'message' => 'Interviewer Assigned', 'status' => 200], 200);
        
    }
    
    
    public function addCandidateInterviewFeedback(Request $request) {

        $validator = Validator::make($request->all(), [
            'user_assigned' => 'required',
            'candidate_id' => 'required',
            'feedback' => 'required',
        ]);

        $validator->setAttributeNames([
            'interview_id' => 'Interview Id',
            'candidate_id' => 'Candidate id',
            'feedback' => 'Feedback',
        ]);

        if ($validator->fails()) {
            $msg = $this->validatersErrorString($validator->errors());
            return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
        }else {

            $interviewFeedback = CandidateInterviewStatus::where('user_assigned', $request->user_assigned)->where('candidate_id', $request->candidate_id)->update([
                'feedback' => $request->feedback
            ]);
            return Response(['response' => $interviewFeedback, 'message' => 'Interview Feedback added successfully', 'status' => 200], 200);
        }
    }
    
    public function candidateInterviewComment(Request $request) {
        $currentUser = Auth::user()->id;
        $candidate = $request->candidate;
        $jobId = $request->job_id;
        $processId = $request->process_id;
        
        // Exclude 'candidate', 'job_id', and 'process_id'
        $requestParams = $request->except(['candidate', 'job_id', 'process_id']);

        if(!empty($requestParams)){
            $validator = Validator::make($request->all(), [
                // 'user_id' => 'required',
                // 'candidate_id' => 'required',
                // 'comment' => 'required',
            ]);
    
            $validator->setAttributeNames([
                // 'user_id' => 'User Id',
                'candidate_id' => 'Candidate id',
                'comment' => 'Comment',
            ]);
    
            if ($validator->fails()) {
                $msg = $this->validatersErrorString($validator->errors());
                return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
            }else {
    
               // Start building the data array
                $data = [
                    'user_id' => $currentUser,
                    'user_type' => $request->user_type,
                    'job_id' => $request->job_id,
                    'process_id' => $request->process_id,
                    'type' => $request->type,
                    'candidate_id' => $request->candidate_id,
                ];
                
                // Add conditional fields based on the 'type'
                if ($request->type == "feedback") {
                    $data['feedback_and_recommendations'] = $request->comment;
                } else {
                    $data['comment'] = $request->comment;
                }
                
                // Insert the data into the database
                $interviewFeedback = CandidateFeedback::insert($data);

                return Response(['response' => $interviewFeedback, 'message' => 'Interview comment added successfully', 'status' => 200], 200);
            }
        } else {
            $existingComments = CandidateFeedback::where('candidate_id', $candidate)->where('job_id', $jobId)->where('process_id', $processId)->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();
                }
            
                $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]['modified'] = $value->modified;
            }

            return Response(['response' => $existingCommentData, 'status' => 200],200);
        }

        
    }
    
    public function interviewCompletionStatus(Request $request, $id) {
        $candidate_id = $request->candidate_id;
        $job_id = $request->job_id;
        $process_id = $request->process_id;
        $staff_id = Auth::user()->id;
        
        $record = CandidateInterviewSchedule::where('id', $id)->update([
            'interview_completion_status' => 1,
            'completion_staff_id' => $staff_id,
        ]);
        
        DB::table('candidate_interview_journeys')
        ->where('candidate_id', $candidate_id)
        ->where('job_id', $job_id)
        ->where('process_id', $process_id)
        ->update([
            'completion_status' => 1,
            'completion_staff_id' => $staff_id,
        ]);
        
        $staff = Staff::where('id', $staff_id)->first();
        $staffName = $staff->first_name . ' ' . $staff->last_name;
        
        $employerId = $staff->employer_id;
        $employer = Employer::where('id', $employerId)->first();
        $employerName = $employer->first_name . ' ' . $employer->last_name;
        
        $candidateData = CandidateJobApply::where('id', $request->candidate_id)->first();
        $candidateName = $candidateData->first_name . ' ' . $candidateData->last_name;
        
        $job = Job::where('id', $request->job_id)->first();
        $jobName = $job->title;
        
        $processName = Process::where('id', $request->process_id)->value('process_name');
        
        $interviewData = CandidateInterviewSchedule::where('id', $id)->first();
        
        $interviewDate = Carbon::parse($interviewData->interview_date)->format('d M Y');
        
        $startTime = $interviewData->start_time; 

        $formattedStartTime = date("g:i A", strtotime($startTime . ":00"));
        
        $feedbackOrComment = CandidateFeedback::where('candidate_id', $request->candidate_id)->where('job_id', $request->job_id)->where('process_id', $request->process_id)->value('feedback_and_recommendations') ?? 'N/A';
        
        
        $emailTemplate = EmailTemplate::where('id', 12)->first();
        
        $toRepArray = ['[!candidate_name!]', '[!job_name!]', '[!staff_name!]', '[!employer_name!]', '[!interview_date!]', '[!process_name!]', '[!interview_time!]', '[!feedback_and_recommendation!]'];
        $fromRepArray = [$candidateName, $jobName, $staffName, $employerName, $interviewDate, $processName, $formattedStartTime, $feedbackOrComment];
        
        $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($employer->email_address, FILTER_VALIDATE_EMAIL)) {
                Mail::to($employer->email_address)->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);
        } 
        
        
        // $processName = Process::where('id', $request->process_id)->value('process_name');
                        
        Notification::create([
            'user_id' => $employerId,
            'user_type' => 'employer',
            'notification_title' => 'Interview Completed',
            'notification_text' => $staffName . ' ' . 'has completed the' . ' ' . $processName . ' ' . 'for' . ' ' . $candidateName . '.',
            'mark_as_read' => '0',
        ]);
        

        return Response(['response' => "", 'message' => 'Interview status marked as completed', 'status' => 200], 200);
    }
    
    public function interviewCancelation(Request $request){
        $candidateId = $request->candidate_id;
        $processId = $request->process_id;
        $jobId = $request->job_id;
        
        DB::table('candidate_interview_schedules')
        ->where('candidate_id', $candidateId)
        ->where('job_id', $jobId)
        ->where('process_id', $processId)
        ->update([
            'interview_cancelation_status' => 1,
            'interview_cancelation_reason' => $request->reason
        ]);
        
        $employerId = CandidateJobApply::where('id', $candidateId)->where('job_form_id', $jobId)->value('employer_id'); 
        
        $candidate = CandidateJobApply::where('id', $candidateId)->select(['first_name', 'last_name'])->first();
        $candidateName = $candidate->first_name . ' ' . $candidate->last_name;
        $candidateEmail = CandidateJobApply::where('id', $candidateId)->value('email');
        
        $interviewData = CandidateInterviewSchedule::where('candidate_id', $candidateId)->where('job_id', $jobId)->where('process_id', $processId)->first();
        
        $startTime = $interviewData->start_time; 
        $formattedStartTime = date("g:i A", strtotime($startTime . ":00"));
        
        $interviewDate = Carbon::parse($interviewData->interview_date)->format('d/m/Y');
        
        $positionName = Job::where('id', $jobId)->value('title');
        
        $companyName = Employer::where('id', $employerId)->value('company_name');
        $employerEmail = Employer::where('id', $employerId)->value('email_address');
        
        $reason = $request->reason;
        
        $emailTemplate = EmailTemplate::where('id', 5)->first();
        $toRepArray = ['[!candidate_name!]', '[!interview_date!]', '[!interview_time!]', '[!position_name!]', '[!company_name!]','[!employer_email!]', '[!reason!]'];
        $fromRepArray = [$candidateName, $interviewDate, $formattedStartTime, $positionName, $companyName, $employerEmail, $reason];
        
        $emailSubject = str_replace($toRepArray, $fromRepArray, $emailTemplate->subject);
        $emailBody = str_replace($toRepArray, $fromRepArray, $emailTemplate->template);
        
        $logo = Employer::where('id', $employerId)->value('company_logo');
                
        if(!empty($logo)){
            $logoPath = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $logo;
        } else{
            $logoPath = LOGO_PATH;
        }
    
        // Send the email
        try {
            Mail::to($candidateEmail)->send(new SendMail($emailBody, $emailSubject, $logoPath));
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to send email.', 'message' => $e->getMessage()], 500);
        }
        
        return Response(['response' => '', 'message' => 'Interview canceled successfully', 'status' => 200], 200);
    }
    
    public function getInterviewDetails(Request $request){
        $candidateId = $request->candidate_id;
        $processId =$request->process_id;
        $jobId = $request->job_id;
        $employerId = $request->employer_id;
        $staffId = $request->staff_id;
        
        $requestData = $request->except(['candidate_id', 'process_id', 'job_id', 'employer_id']);
        
        $candidateData = CandidateInterviewSchedule::where('candidate_id', $candidateId)->where('job_id', $jobId)->where('process_id', $processId)->first();
        
        $data = array();
        // return Response(['response' => $candidateData, 'message' => '', 'status' => 200], 200);
        // exit();
        
        if($candidateData->interview_cancelation_status == 1){
            
            return Response(['response' => 'Your interview has already been cancelled. It can no more be re-scheduled', 'message' => 'success', 'status' => 500], 200);
            
        } else{
            
            if($request->user_type == 'staff'){
                
                $employerID = Staff::where('id', $staffId)->value('employer_id');
                
                $candidateInterviewDetails  = CandidateInterviewSchedule::where('candidate_id', $candidateId)
                                        ->where('process_id', $processId)
                                        ->where('job_id', $jobId)
                                        ->first();
                                        
                $candidateFirstName = CandidateJobApply::where('id', $candidateId)->first();
                $candidateInterviewDetails['first_name'] = $candidateFirstName->first_name;
                $candidateInterviewDetails['middle_name'] = $candidateFirstName->middle_name ?? 'N/A';
                $candidateInterviewDetails['last_name'] = $candidateFirstName->last_name;
                
                $candidateInterviewDetails['profile_image'] = DISPLAY_FULL_PROFILE_IMAGE_PATH . $candidateFirstName->profile_img;
                
                // $staffName = Staff::where('id', $candidateInterviewDetails->assigned_to)->first();
                // $candidateInterviewDetails['staff_first_name'] = $staffName->first_name;
                // $candidateInterviewDetails['staff_last_name'] = $staffName->last_name;
                
                $candidateInterviewDetails['user_assigned'] = json_decode($candidateInterviewDetails->assigned_to, true);
                $candidateInterviewDetails['interview_type'] = $candidateInterviewDetails->interview_type;
                $candidateInterviewDetails['interview_type_detail'] = $candidateInterviewDetails->interview_type_detail;
                $candidateInterviewDetails['start_time'] = $candidateInterviewDetails->start_time;
                $candidateInterviewDetails['duration'] = $candidateInterviewDetails->duration;
                $candidateInterviewDetails['comment'] = $candidateInterviewDetails->comment;
                $candidateInterviewDetails['interview_date'] = $candidateInterviewDetails->interview_date ? Carbon::parse($candidateInterviewDetails->interview_date)->toDateString() : "Interview not scheduled";
                
                $processData = Process::where('employer_id', $employerID)->get();
                $staffData = Staff::where('employer_id', $employerID)->get();
                
                $data['candidateInterviewDetails'] = $candidateInterviewDetails;
                $data['processData'] = $processData;
                $data['staffData'] = $staffData;
                
            } else{
                
                $candidateInterviewDetails  = CandidateInterviewSchedule::where('candidate_id', $candidateId)
                                        ->where('process_id', $processId)
                                        ->where('job_id', $jobId)
                                        ->first();
                                        
                $candidateFirstName = CandidateJobApply::where('id', $candidateId)->first();
                $candidateInterviewDetails['first_name'] = $candidateFirstName->first_name;
                $candidateInterviewDetails['middle_name'] = $candidateFirstName->middle_name ?? 'N/A';
                $candidateInterviewDetails['last_name'] = $candidateFirstName->last_name;
                
                $candidateInterviewDetails['profile_image'] = DISPLAY_FULL_PROFILE_IMAGE_PATH . $candidateFirstName->profile_img;
                
                // $staffName = Staff::where('id', $candidateInterviewDetails->assigned_to)->first();
                // $candidateInterviewDetails['staff_first_name'] = $staffName->first_name;
                // $candidateInterviewDetails['staff_last_name'] = $staffName->last_name;
                
                $candidateInterviewDetails['user_assigned'] = json_decode($candidateInterviewDetails->assigned_to, true);
                $candidateInterviewDetails['interview_type'] = $candidateInterviewDetails->interview_type;
                $candidateInterviewDetails['interview_type_detail'] = $candidateInterviewDetails->interview_type_detail;
                $candidateInterviewDetails['start_time'] = $candidateInterviewDetails->start_time;
                $candidateInterviewDetails['duration'] = $candidateInterviewDetails->duration;
                $candidateInterviewDetails['comment'] = $candidateInterviewDetails->comment;
                $candidateInterviewDetails['interview_date'] = $candidateInterviewDetails->interview_date ? Carbon::parse($candidateInterviewDetails->interview_date)->toDateString() : "Interview not scheduled";
                
                $processData = Process::where('employer_id', $employerId)->get();
                $staffData = Staff::where('employer_id', $employerId)->get();
                
                $data['candidateInterviewDetails'] = $candidateInterviewDetails;
                $data['processData'] = $processData;
                $data['staffData'] = $staffData;
                
            }
                
                
            return Response(['response' => $data, 'message' => 'Data fetched successfully', 'status' => 200], 200);
        }
        
    }
    
    public function interviewRescheduled(Request $request){
        $candidateId = $request->candidate_id;
        $oldProcessId = $request->old_process_id;
        $jobId = $request->job_id;
        $employerId = $request->assigned_by;
        $staffId = $request->staff_id;
        
        $requestData = $request->except(['candidate_id', 'process_id', 'job_id', 'employer_id']);
        
        $candidateData = CandidateInterviewSchedule::where('candidate_id', $candidateId)->where('job_id', $jobId)->where('process_id', $oldProcessId)->first();
        
        
            if(!empty($requestData)){
                
                if($request->user_type == 'staff'){
                    
                    $employerID = Staff::where('id', $staffId)->value('employer_id');
                    
                    CandidateInterviewSchedule::where('candidate_id', $candidateId)->where('job_id', $jobId)
                                            ->where('process_id', $oldProcessId)
                                            ->update([
                                                'process_id' => $request->process_id,
                                                'assigned_to' => json_encode(explode(',', $request->user_assigned)),
                                                'interview_type' => $request->interview_type,
                                                'interview_date' => $request->interview_date,
                                                'interview_type_detail' => $request->interview_type_detail,
                                                'start_time' => $request->start_time,
                                                'duration' => $request->duration,
                                                'comment' => $request->comment,
                    ]);
                    
                    $candidate = CandidateJobApply::where('id', $candidateId)->first();
                    $candidateName = $candidate->first_name . ' ' . $candidate->last_name;
                    $candidateEmail = $candidate->email;
                    
                    $employer = Employer::where('id', $employerID)->first();
                    // print_r($employer);
                    // exit();
                    // $employerName = $employer->first_name . ' ' . $employer->last_name;
                    $employerEmail = $employer->email_address;
                    
                    $userAssignedIds = json_decode($request->user_assigned, true);
    
                    if (!is_array($userAssignedIds)) {
                        $userAssignedIds = []; // Ensure it's an array to prevent errors
                    }
                    
                    if (count($userAssignedIds) == 1) {
                        // If only one ID, fetch a single staff member
                        $staff = Staff::where('id', $userAssignedIds[0])->first();
                        $staffName = $staff ? $staff->first_name . ' ' . $staff->last_name : '';
                    } else {
                        // If multiple IDs, fetch all staff members and join names with commas
                        $staffMembers = Staff::whereIn('id', $userAssignedIds)->select('first_name', 'last_name')->get();
                        $staffName = $staffMembers->map(function ($staff) {
                            return $staff->first_name . ' ' . $staff->last_name;
                        })->implode(', ');
                    }
    
                    
                    $jobName = Job::where('id', $jobId)->value('title');
                    
                    $processName = Process::where('id', $request->process_id)->value('process_name');
                    
                    $interviewDuration = $request->duration;
                    
                    if ($interviewDuration == 1) {
                        $formattedDuration = $interviewDuration . ' Hour';
                    } else {
                        $formattedDuration = $interviewDuration . ' Minutes';
                    }
                    
                    $interviewDate = Carbon::parse($request->interview_date)->format('d M Y');
                    
                    $startTime = $request->start_time; 
    
                    $formattedStartTime = date("g:i A", strtotime($startTime . ":00"));
                    
                    $emailTemplate = EmailTemplate::where('id', 6)->first();
                    $toRepArray = ['[!candidate_name!]', '[!job_name!]', '[!employer_email!]', '[!interview_date!]', '[!interview_time!]', '[!duration!]',
                                    '[!interview_type!]', '[!interview_type_detail!]', '[!interviewer_name!]', '[!process_name!]'];
                    $fromRepArray = [$candidateName, $jobName, $employerEmail, $interviewDate, $formattedStartTime, $formattedDuration,
                                     $request->interview_type, $request->interview_type_detail, $staffName, $processName];
                    
                    $emailSubject = str_replace($toRepArray, $fromRepArray, $emailTemplate->subject);
                    $emailBody = str_replace($toRepArray, $fromRepArray, $emailTemplate->template);
                    $logo = Employer::where('id', $employerID)->value('company_logo');
                    
                    if(!empty($logo)){
                        $logoPath = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $logo;
                    } else{
                        $logoPath = LOGO_PATH;
                    }
                
                    // Send the email
                    try {
                        Mail::to($candidateEmail)->send(new SendMail($emailBody, $emailSubject, $logoPath));
                    } catch (\Exception $e) {
                        return response()->json(['error' => 'Failed to send email.', 'message' => $e->getMessage()], 500);
                    }
                    
                    $processName = Process::where('id', $request->process_id)->value('process_name');
                    
                    $assignedUserIds = explode(',', $request->user_assigned);
                    
                    foreach ($assignedUserIds as $UserId) {
                        Notification::create([
                            'user_id' => trim($UserId),
                            'user_type' => 'staff',
                            'notification_title' => 'Interview Scheduled',
                            'notification_text' => 'You have been assigned to conduct' . ' ' . $processName . ' ' . 'for' . ' ' . $candidateName . ' ' . 'on' . ' ' . $interviewDate . '.',
                            'mark_as_read' => '0',
                        ]);
                    }
                    
                } else{
                    
                    CandidateInterviewSchedule::where('candidate_id', $candidateId)->where('job_id', $jobId)
                                            ->where('process_id', $oldProcessId)
                                            ->update([
                                                'process_id' => $request->process_id,
                                                'assigned_to' => json_encode(explode(',', $request->user_assigned)),
                                                'interview_type' => $request->interview_type,
                                                'interview_date' => $request->interview_date,
                                                'interview_type_detail' => $request->interview_type_detail,
                                                'start_time' => $request->start_time,
                                                'duration' => $request->duration,
                                                'comment' => $request->comment,
                    ]);
                
                    $candidate = CandidateJobApply::where('id', $candidateId)->first();
                    $candidateName = $candidate->first_name . ' ' . $candidate->last_name;
                    $candidateEmail = $candidate->email;
                    
                    $employer = Employer::where('id', $employerId)->first();
                    // print_r($employer);
                    // exit();
                    // $employerName = $employer->first_name . ' ' . $employer->last_name;
                    $employerEmail = $employer->email_address;
                    
                    $userAssignedIds = json_decode($request->user_assigned, true);
    
                    if (!is_array($userAssignedIds)) {
                        $userAssignedIds = []; // Ensure it's an array to prevent errors
                    }
                    
                    if (count($userAssignedIds) == 1) {
                        // If only one ID, fetch a single staff member
                        $staff = Staff::where('id', $userAssignedIds[0])->first();
                        $staffName = $staff ? $staff->first_name . ' ' . $staff->last_name : '';
                    } else {
                        // If multiple IDs, fetch all staff members and join names with commas
                        $staffMembers = Staff::whereIn('id', $userAssignedIds)->select('first_name', 'last_name')->get();
                        $staffName = $staffMembers->map(function ($staff) {
                            return $staff->first_name . ' ' . $staff->last_name;
                        })->implode(', ');
                    }
    
                    
                    $jobName = Job::where('id', $jobId)->value('title');
                    
                    $processName = Process::where('id', $request->process_id)->value('process_name');
                    
                    $interviewDuration = $request->duration;
                    
                    if ($interviewDuration == 1) {
                        $formattedDuration = $interviewDuration . ' Hour';
                    } else {
                        $formattedDuration = $interviewDuration . ' Minutes';
                    }
                    
                    $interviewDate = Carbon::parse($request->interview_date)->format('d M Y');
                    
                    $startTime = $request->start_time; 
    
                    $formattedStartTime = date("g:i A", strtotime($startTime . ":00"));
                    
                    $emailTemplate = EmailTemplate::where('id', 6)->first();
                    $toRepArray = ['[!candidate_name!]', '[!job_name!]', '[!employer_email!]', '[!interview_date!]', '[!interview_time!]', '[!duration!]',
                                    '[!interview_type!]', '[!interview_type_detail!]', '[!interviewer_name!]', '[!process_name!]'];
                    $fromRepArray = [$candidateName, $jobName, $employerEmail, $interviewDate, $formattedStartTime, $formattedDuration,
                                     $request->interview_type, $request->interview_type_detail, $staffName, $processName];
                    
                    $emailSubject = str_replace($toRepArray, $fromRepArray, $emailTemplate->subject);
                    $emailBody = str_replace($toRepArray, $fromRepArray, $emailTemplate->template);
                    $logo = Employer::where('id', $employerId)->value('company_logo');
                    
                    if(!empty($logo)){
                        $logoPath = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $logo;
                    } else{
                        $logoPath = LOGO_PATH;
                    }
                
                    // Send the email
                    try {
                        Mail::to($candidateEmail)->send(new SendMail($emailBody, $emailSubject, $logoPath));
                    } catch (\Exception $e) {
                        return response()->json(['error' => 'Failed to send email.', 'message' => $e->getMessage()], 500);
                    }
                    
                    $processName = Process::where('id', $request->process_id)->value('process_name');
                        
                    $assignedUserIds = explode(',', $request->user_assigned);
                        
                    foreach ($assignedUserIds as $UserId) {
                        Notification::create([
                            'user_id' => trim($UserId),
                            'user_type' => 'staff',
                            'notification_title' => 'Interview Scheduled',
                            'notification_text' => 'You have been assigned to conduct' . ' ' . $processName . ' ' . 'for' . ' ' . $candidateName . ' ' . 'on' . ' ' . $interviewDate . '.',
                            'mark_as_read' => '0',
                        ]);
                    }
                    
                }
                
                
                return Response(['response' => 'Interview re-scheduled successfully', 'message' => 'success', 'status' => 200], 200);
                
            } else{
                return Response(['response' => 'No data received', 'message' => 'success', 'status' => 200], 200);
            }
        
    }
    

 
}
