<?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\Qualification;
use App\Models\StatusAttributes;
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;






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 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;
                
                $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', $currentUser)->value('company_name');
                
                $interviewer = Staff::where('id', $request->user_assigned)->select('first_name', 'last_name')->first();
                $interviewerName = $interviewer ? $interviewer->first_name . ' ' . $interviewer->last_name : '';
                
                $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);
                }
                
                $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)){
                $candidateData = CandidateJobApply::where('id', $id)->first();
                // $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 : "";
                    } else {
                        $processData[$key]['process_name'] = "";
                    }
                
                    $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();
            } 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();
            }
            
            
            $existingInterviewData = array();

            foreach($existingInterview as $key => $value) {
                $existingInterviewData[$key]['id'] = $value->id;
                $existingInterviewData[$key]['process_id'] = $value->process_id;
                $existingInterviewData[$key]['user_assigned'] = $value->assigned_to;
                $existingInterviewData[$key]['interview_date'] = $value->interview_date ? Carbon::parse($value->interview_date)->toDateString() : "Interview not scheduled";
                $existingInterviewData[$key]['start_time'] = $value->start_time;
                $existingInterviewData[$key]['duration'] = $value->duration;
                
                $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);
            }


            return Response(['response' => ['candidateData' => $candidateData, 'processData' => $processData, 'userList' => $userList, 'existingInterview' => $existingInterviewData],  'message' => '', '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 : '';
                
                $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;
                    $candidateDetailsData['date_of_birth'] = $candidateDetails->date_of_birth;
                    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;
                    }
        
                    $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;
                        $experienceData[$expKey]['reason_of_leaving'] = $expValue->reason_of_leaving;
                        $experienceData[$expKey]['start_date'] = $expValue->start_date;
                        $experienceData[$expKey]['end_date'] = $expValue->end_date;
                    }
                    $candidateDetailsData['experience'] = $experienceData;
                }
                
                // echo $value->candidate_id;
                $interviewDetails = CandidateInterviewSchedule::where('candidate_id',$value->candidate_id)->first();
                $interviewDetailsData = array();
                
                
                $interviewDetailsData['id'] = $interviewDetails->id;
                $interviewDetailsData['job_id'] = $interviewDetails->job_id;
                $interviewDetailsData['process_id'] = $interviewDetails->process_id;
                $interviewDetailsData['process_name'] = Process::where('id',$interviewDetails->process_id)->select('process_name')->first()->process_name;
                $interviewDetailsData['interview_type'] = $interviewDetails->interview_type;
                $interviewDetailsData['interview_type_detail'] = $interviewDetails->interview_type_detail;
                $interviewDetailsData['interview_date'] = $interviewDetails->interview_date ? Carbon::parse($interviewDetails->interview_date)->toDateString() : "Interview not scheduled";
                $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);
                
                
            }
        } else if(!empty($staffCheck)){
            $interviewAssigned = CandidateInterviewSchedule::where('assigned_to', $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 : '';
                
                $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;
                    // $candidateDetailsData['gender'] = $candidateDetails->gender;
                    if($candidateDetails->gender == 1){
                        $candidateDetailsData['gender'] = "Male";
                    } else if($candidateDetails->gender == 2){
                        $candidateDetailsData['gender'] = "Female";
                    }else{
                        $candidateDetailsData['gender'] = "Other";
                    }
                    $candidateDetailsData['profile_image'] = $candidateDetails->profile_image;
                    $candidateDetailsData['email_address'] = $candidateDetails->email;
                    $candidateDetailsData['contact'] = $candidateDetails->contact_number;
                    $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";
                    }
                    $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;
                    }
        
                    $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_city'] = $eduValue->school_college_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;
                        $experienceData[$expKey]['reason_of_leaving'] = $expValue->reason_of_leaving;
                        $experienceData[$expKey]['start_date'] = $expValue->start_date;
                        $experienceData[$expKey]['end_date'] = $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;
                $interviewDetailsData['process_name'] = Process::where('id',$value->process_id)->select('process_name')->first()->process_name;
                $interviewDetailsData['interview_type'] = $value->interview_type;
                $interviewDetailsData['interview_type_detail'] = $value->interview_type_detail;
                $interviewDetailsData['interview_date'] = $value->interview_date ? Carbon::parse($value->interview_date)->toDateString() : "Interview not scheduled";
                $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);
                
    
                
        
                $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);
                
                
            }
                    return Response(['response' => $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();
        
    
        return Response(['response' => ['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;
        
        $requestParams = $request->except('candidate');
        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 {
    
                $interviewFeedback = CandidateFeedback::insert([
                    'user_id' => $currentUser,
                    'user_type' => $request->user_type,
                    'candidate_id' => $request->candidate_id,
                    'comment' => $request->comment
                ]);
                return Response(['response' => $interviewFeedback, 'message' => 'Interview comment added successfully', 'status' => 200], 200);
            }
        } else {
            $existingComments = CandidateFeedback::where('candidate_id', $candidate)->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'] = $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;
        
        $record = CandidateInterviewSchedule::where('id', $id)->update([
            'interview_completion_status' => 1,
        ]);
        
        DB::table('candidate_interview_journeys')
        ->where('candidate_id', $candidate_id)
        ->where('job_id', $job_id)
        ->where('process_id', $process_id)
        ->update([
            'completion_status' => 1
        ]);

        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;
        
        $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();
        
        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{
            $data = array();
                $candidateInterviewDetails  = CandidateInterviewSchedule::where('candidate_id', $candidateId)
                                        ->where('process_id', $processId)
                                        ->where('job_id', $jobId)
                                        ->first();
                                        
                $candidateFirstName = CandidateJobApply::where('id', $candidateId)->first();
                $candidateInterviewDetails['candidate_first_name'] = $candidateFirstName->first_name;
                $candidateInterviewDetails['candidate_last_name'] = $candidateFirstName->last_name;
                
                $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'] = $candidateInterviewDetails->assigned_to;
                $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;
        
        $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)){
                CandidateInterviewSchedule::where('candidate_id', $candidateId)->where('job_id', $jobId)
                                            ->where('process_id', $oldProcessId)
                                            ->update([
                                                'process_id' => $request->process_id,
                                                'assigned_to' => $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;
                
                $staff = Staff::where('id', $request->user_assigned)->first();
                $staffName = $staff->first_name . ' ' . $staff->last_name;
                
                $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);
                }
                
                return Response(['response' => 'Interview re-scheduled successfully', 'message' => 'success', 'status' => 200], 200);
                
            } else{
                return Response(['response' => 'No data received', 'message' => 'success', 'status' => 200], 200);
            }
        
    }
    

 
}
