<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\CandidateEducation;
use App\Models\CandidateExperience;
use App\Models\CandidateJobApply;
use App\Models\Category;
use App\Models\Industry;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Models\Job;
use App\Models\Qualification;
use App\Models\Skill;
use App\Models\Admin;
use App\Models\Employer;
use App\Models\Staff;
use App\Models\Process;
use Illuminate\Support\Facades\Auth;
use DateTime;
use Carbon\Carbon;


class JobsController extends Controller
{
    //
    
    public function listing(Request $request) {
        $jobs = Job::where('job_status', 1)->orderBy('created_at', 'desc')->get();
        
        
        $jobData = array();

        foreach($jobs as $key => $value) {
            $jobData[$key]['job_id'] = $value->id;
            $jobData[$key]['job_name'] = $value->title;
            $jobData[$key]['job_description'] = $value->description;
            $jobData[$key]['job_status'] = $value->status;
            $jobData[$key]['job_created_at'] = format_date($value->created_at);
            $jobData[$key]['category'] = $value->category_id ? getCategoryName($value->category_id) : "N/A";
            // $jobData[$key]['skill'] = $this->getSkillName($value->skill_id);
            $jobData[$key]['designation'] = getDesignationName($value->designation);
            $jobData[$key]['slug'] = $value->slug;
        }

        return Response(['response' => $jobData], 200);
    }
    
    public function admin_listing(Request $request) {
        
        
        $currentUser = Auth::user()->id;
        $adminCheck = Admin::where('id', $currentUser)->first();
        $employerCheck = Employer::where('id', $currentUser)->first();
        $staffCheck = Staff::where('id', $currentUser)->first();
        
        if (!empty($adminCheck)) {
            $jobs = Job::where('job_status', 1)->orderBy('id','desc')->get();
            $jobData = array();

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

                $jobData[$key]['job_id'] = $value->id;
                $jobData[$key]['job_name'] = $value->title;
                $jobData[$key]['employer_name'] = $employerName;
                $jobData[$key]['employer_id'] = $value->employer_id;
                $jobData[$key]['staff_name'] = $staffName;
                $jobData[$key]['staff_id'] = $value->staff_id;
                $jobData[$key]['job_description'] = $value->description;
                $jobData[$key]['job_status'] = $value->status;
                $jobData[$key]['job_created_at'] = format_date($value->created);
                $jobData[$key]['category'] = getCategoryName($value->category_id);
                // $jobData[$key]['skill'] = $this->getSkillName($value->skill_id);
                $jobData[$key]['designation'] = getDesignationName($value->designation);
                $jobData[$key]['slug'] = $value->slug;
                $jobData[$key]['status'] = $value->status;
            }
    
            return Response(['response' => $jobData], 200);
        } else if(!empty($employerCheck)) {
            $jobs = Job::where('job_status', 1)->where('employer_id', $currentUser)->orderBy('id','desc')->get();
            $jobData = array();

            foreach($jobs as $key => $value) {
                
                $employerRecord = Employer::where('id', $value->employer_id)
                    ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                    ->first();
                if(!empty($employerRecord)){
                    $employerName = $employerRecord->full_name;
                }else {
                    $employerName = "Not Available";
                }
                $staffRecord = Staff::where('id', $value->staff_id)
                    ->selectRaw("CONCAT(first_name, ' ', last_name) as full_name")
                    ->first();
                    
                if(!empty($staffRecord)){
                    $staffName = $staffRecord->full_name;
                }else {
                    $staffName = "Not Available";
                }
                    
                $jobData[$key]['job_id'] = $value->id;
                $jobData[$key]['user_id'] = $value->user_id;
                $jobData[$key]['employer_name'] = $employerName;
                $jobData[$key]['employer_id'] = $value->employer_id;
                $jobData[$key]['staff_name'] = $staffName;
                $jobData[$key]['staff_id'] = $value->staff_id;
                $jobData[$key]['job_name'] = $value->title;
                $jobData[$key]['category_id'] = $value->category_id;
                $jobData[$key]['category'] = getCategoryName($value->category_id);
                
                $jobData[$key]['designation_id'] = $value->designation;
                $jobData[$key]['designation'] = getDesignationName($value->designation);
                
                $jobData[$key]['location'] = $value->location;
                $jobData[$key]['job_description'] = $value->description;
                $jobData[$key]['work_type'] = getWorkTypeName($value->work_type);
                $jobData[$key]['slug'] = $value->slug;
                $jobData[$key]['job_created_at'] = format_date($value->created_at);
                
                $jobData[$key]['job_status'] = $value->status;
                $jobData[$key]['min_salary'] = CURR." ".$value->min_salary;
                $jobData[$key]['max_salary'] = CURR." ".$value->max_salary;
                
                $jobData[$key]['min_exp'] = $value->min_exp;
                $jobData[$key]['max_exp'] = $value->max_exp;
                
                $processOrderIds = $value->process_order_ids; // The comma-separated string
                $processOrderArray = explode(',', $value->process_order_ids); // Convert the string to an array
                
                $processOrders = array_map(function ($processOrderArray) {
                    return getProcessOrderName($processOrderArray); // Call the function for each process order ID
                }, $processOrderArray);
                
                $jobData[$key]['process_order'] = implode(', ', $processOrders); // Join the results back into a string

                $skillIds = explode(',', $value->skill);
                $skillNames = array_map(function ($skillId) {
                    return getSkillName($skillId);
                }, $skillIds);
                
                $jobData[$key]['skill'] = implode(', ', $skillNames);
                $jobData[$key]['skill_id'] = $value->skill;
                
                
                $jobData[$key]['status'] = $value->status;
            }
    
            return Response(['response' => $jobData], 200);
            
        } else if(!empty($staffCheck)){
            $jobs = Job::where('job_status', 1)->where('staff_id', $currentUser)->orderBy('id','desc')->get();
            $jobData = array();

            foreach($jobs as $key => $value) {
                $jobData[$key]['job_id'] = $value->id;
                $jobData[$key]['job_name'] = $value->title;
                $jobData[$key]['employer_name'] = $employerName;
                $jobData[$key]['employer_id'] = $value->employer_id;
                $jobData[$key]['staff_name'] = $staffName;
                $jobData[$key]['staff_id'] = $value->staff_id;
                $jobData[$key]['job_description'] = $value->description;
                $jobData[$key]['job_status'] = $value->status;
                $jobData[$key]['job_created_at'] = format_date($value->created);
                $jobData[$key]['category'] = getCategoryName($value->category_id);
                // $jobData[$key]['skill'] = $this->getSkillName($value->skill_id);
                $jobData[$key]['designation'] = getDesignationName($value->designation);
                $jobData[$key]['slug'] = $value->slug;
            }
    
            return Response(['response' => $jobData], 200);
            
        }
        $jobData = array();

        foreach($jobs as $key => $value) {
            $jobData[$key]['job_id'] = $value->id;
            $jobData[$key]['job_name'] = $value->title;
            $jobData[$key]['job_description'] = $value->description;
            $jobData[$key]['job_status'] = $value->status;
            $jobData[$key]['job_created_at'] = format_date($value->created);
            $jobData[$key]['category'] = getCategoryName($value->category_id);
            // $jobData[$key]['skill'] = $this->getSkillName($value->skill_id);
            $jobData[$key]['designation'] = getDesignationName($value->designation);
            $jobData[$key]['slug'] = $value->slug;
        }

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

    public function jobDescription($slug) {
        
        
        $job = Job::where('slug', $slug)->first();

        if($job == null) {
            return Response(['response' => 'Job not found', 'status' => 500], 200);
        }
            // Format the job_created_at field
        $job->created = format_date($job->created);
        $job->work_type = getWorkTypeName($job->work_type);
        $job->category_id = getCategoryName($job->category_id);
        $job->skill = getSkillName($job->skill);
        $job->designation = getDesignationName($job->designation);
        $job->location = $job->location;
        $job->experience = $job->experience;
        $job->min_salary = CURR . $job->min_salary;
        $job->max_salary = CURR . $job->max_salary;
        $job->industry = getIndustryName($job->industry);
        $job->qualification = getQualificationName($job->qualification);
        $job->max_exp = $job->max_exp;
        return Response(['response' => $job, 'status' => 200], 200);
    }
    
    
    public function admin_postJob(Request $request) {
        $user = Auth::user();
        $userId = $user->id;
        
        $adminDetail = Admin::find($userId);
        $employerDetail = Employer::find($userId);
        $staffDetail = Staff::find($userId);
    
        // Initialize variables
        $category = [];
        $industry = [];
        $qualification = [];
        $skill = [];
        $designation = [];
    
        $worktypeData = $GLOBALS['worktype'];
        $experience = $GLOBALS['experienceArray'];
        $annual_salary = $GLOBALS['salary'];
    
        if (!empty($request->all())) {
            $validator = Validator::make($request->all(), [
                'job_title' => 'required',
                'job_description' => 'required',
                'category' => 'required',
                'designation' => 'required',
                // 'skill' => 'required',
                'work_type' => 'required',
            ]);
    
            if ($validator->fails()) {
                return Response(['response' => $validator->errors(), 'status' => 500], 200);
            }
    
            if (!empty($adminDetail)) {
                $category = Category::where('status', 1)->get();
                $industry = Industry::where('status', 1)->get();
                $qualification = Qualification::where('status', 1)->get();
                $skill = Skill::where('status', 1)->where('type', 'Skill')->get();
                $designation = Skill::where('status', 1)->where('type', 'Designation')->get();
            } else if (!empty($employerDetail)) {
                $category = Category::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                // $industry = Industry::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                // $industry = Industry::where('status', 1)
                // ->where(function($query) use ($userId) {
                //     $query->where('employer_id', '!=', 0)
                //         ->orWhere(function($query) use ($userId) {
                //             $query->where('employer_id', 0)
                //                   ->whereRaw("FIND_IN_SET(? employer_status)", [$userId]);
                //         });
                // })
                // ->get();
                
                $industry = Industry::where('status', 1)
                    ->where(function($query) use ($userId) {
                        $query->where('employer_id', '!=', 0)
                              ->orWhere(function($query) use ($userId) {
                                  $query->where('employer_id', 0)
                                        ->whereRaw("employer_status NOT LIKE ?", ["%,$userId,%"]);
                              });
                    })
                    ->get();

                $qualification = Qualification::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $skill = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Skill')->get();
                $designation = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Designation')->get();
            } elseif (!empty($staffDetail)) {
                $category = Category::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $industry = Industry::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $qualification = Qualification::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $skill = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Skill')->get();
                $designation = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Designation')->get();
            }
    
            $job = new Job();
            $job->title = $request->job_title;
            $job->category_id = $request->category;
            $job->description = $request->job_description;
            $job->industry = $request->industry;
            $job->work_type = $request->work_type;
            $job->location = $request->location;

            // $job->experience = $request->experience;
            
            $experienceRange = $request->experience;
            list($minExp,$maxExp) = explode('-', $experienceRange);
            $job->min_exp = $minExp;
            $job->max_exp = $maxExp;
            $job->qualification = $request->qualification;
            // $job->annual_salary = $request->annual_salary;
            
            $salaryRange = $request->annual_salary; 
            list($minSalary, $maxSalary) = explode('-', $salaryRange); 
            $job->min_salary = $minSalary;
            $job->max_salary = $maxSalary;
            
            $job->skill = $request->skill;
            
            $job->designation = $request->designation;
            $job->process_order_ids = is_array($request->process_order_ids) 
                ? implode(',', $request->process_order_ids) 
                : (string) $request->process_order_ids;

            $job->status = 1;
            $job->user_id = $userId;
            $job->admin_id = !empty($adminDetail) ? $userId : 0;
            $job->employer_id = !empty($employerDetail) ? $userId : 0;
            $job->staff_id = !empty($staffDetail) ? $userId : 0;
            $job->job_status = 1;
            $job->slug = createSlug('jobs', $request->job_title);
    
            $job->save();
    
            return Response(['response' => $job, 'message' => 'Job added successfully', 'status' => 200], 200);
        } else {
            // Populate data when the page is loaded
            if (!empty($adminDetail)) {
                $category = Category::where('status', 1)->get();
                $industry = Industry::where('status', 1)->get();
                $qualification = Qualification::where('status', 1)->get();
                $skill = Skill::where('status', 1)->where('type', 'Skill')->get();
                $designation = Skill::where('status', 1)->where('type', 'Designation')->get();
            } else if (!empty($employerDetail)) {
                // $category = Category::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $category = Category::where('status', 1)
                ->where(function($query) use ($userId) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $userId)
                          ->orWhere(function($query) use ($userId) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$userId]);
                          });
                })
                ->get();
                
                
                // $industry = Industry::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $industry = Industry::where('status', 1)
                ->where(function($query) use ($userId) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $userId)
                          ->orWhere(function($query) use ($userId) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$userId]);
                          });
                })
                ->get();
                // $qualification = Qualification::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $qualification = Qualification::where('status', 1)
                ->where(function($query) use ($userId) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $userId)
                          ->orWhere(function($query) use ($userId) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$userId]);
                          });
                })
                ->get();
                // $skill = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Skill')->get();
                $skill = Skill::where('status', 1)->where('type', 'Skill')
                ->where(function($query) use ($userId) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $userId)
                          ->orWhere(function($query) use ($userId) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$userId]);
                          });
                })
                ->get();
                // $designation = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Designation')->get();
                $designation = Skill::where('status', 1)->where('type', 'Designation')
                ->where(function($query) use ($userId) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $userId)
                          ->orWhere(function($query) use ($userId) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$userId]);
                          });
                })
                ->get();
                
                $processList = Process::where('employer_id', $userId)->get();
            } elseif (!empty($staffDetail)) {
                $category = Category::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $industry = Industry::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $qualification = Qualification::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $skill = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Skill')->get();
                $designation = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Designation')->get();
            }
    
            $data = array();
            $data['category'] = $category;
            $data['industry'] = $industry;
            $data['worktype'] = $worktypeData;
            $data['experience'] = $experience;
            $data['qualification'] = $qualification;
            $data['annual_salary'] = $annual_salary;
            $data['skill'] = $skill;
            $data['designation'] = $designation;
            $data['process_list'] = $processList;
    
            return Response(['response' => $data, 'status' => 200], 200);
        }
    }


    
    public function jobApply(Request $request, $slug) {

        $requestData = $request->all();
        $employerId = $requestData['employer_id'] ?? null;

        // Remove 'employer_id' from the request data
        unset($requestData['employer_id']);
        
        // Check if the request data is not empty (after removing 'employer_id')
        if (!empty($requestData)) {
        
            // Proceed with validation
            $validator = Validator::make($requestData, [
                'firstName' => 'required',
                'lastName' => 'required',
                'email' => 'required',
                'contactNumber' => 'required',
                'gender' => 'required',
                'martialStatus' => 'required',
                'physicalDisability' => 'required',
                'educations' => 'required',
                'experience' => 'required',
            ]);


            $validator->setAttributeNames([
                // 'job_id' => 'Job Id',
                'firstName' => 'First Name',
                'lastName' => 'Last Name',
                'email' => 'Email',
                'contactNumber' => 'Contact Number',
                'dateOfBirth' => 'Date Of Birth',
                'gender' => 'Gender',
                'martialStatus' => 'Martial Status',
                'physicalDisability' => 'Physical Disability',
                'educations' => 'Education',
                'experience' => 'Experience',
                // 'cv' => 'Cv',
                // 'profilePicture' => 'Profile Picture',
            ]);

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

                // Generate a random 5-digit number
                $randomNumber = mt_rand(10000, 99999);

                // Construct the application number
                $applicationNumber = "RMS-" . $request->firstName . $request->lastName . $randomNumber;
                // if ($request->hasFile('cv')) {
                //     $cvPath = $request->file('cv')->store('uploads/cvs', 'public');
                // }
                
                // if ($request->hasFile('profilePicture')) {
                //     $profilePicturePath = $request->file('profilePicture')->store('uploads/profile_pictures', 'public');
                // }
                
                if ($request->hasFile('cv')) {
    // Store the CV in storage and get the path
    $cvPath = $request->file('cv')->store('uploads/cvs', 'public');
    // Extract only the file name from the path
    $cvName = basename($cvPath);
    // Save $cvName to the database
    // $yourModel->cv = $cvName;
}

if ($request->hasFile('profilePicture')) {
    // Store the profile picture in storage and get the path
    $profilePicturePath = $request->file('profilePicture')->store('uploads/profile_pictures', 'public');
    // Extract only the file name from the path
    $profilePictureName = basename($profilePicturePath);
    // Save $profilePictureName to the database
    // $yourModel->profile_picture = $profilePictureName;
}

// Save the model
// $yourModel->save();

                    
                // Serialize education details into JSON
                $educationDetails = !empty($request->educations) ? json_encode($request->educations) : null;
                
                // Serialize experience details into JSON
                $experienceDetails = !empty($request->experience) ? json_encode($request->experience) : null;
                
                

                $candidateJobApplication = CandidateJobApply::insertGetId([
                    'job_form_id' => Job::where('slug', $request->slug)->first()->id,
                    'employer_id' => Job::where('slug', $request->slug)->first()->employer_id,
                    'application_number' => $applicationNumber,
                    'first_name' => $request->firstName,
                    'middle_name' => $request->middleName,
                    'last_name' => $request->lastName,
                    'email' => $request->email,
                    'contact_number' => $request->contactNumber,
                    'date_Of_birth' => $request->dateOfBirth,
                    'gender' => $request->gender,
                    'martial_status' => $request->martialStatus,
                    'physically_challenged' => $request->physicalDisability,
                    'document_cv' => $cvName,
                    'profile_img' => $profilePictureName,
                    'education_details' => $educationDetails,
                    'experience_details' => $experienceDetails,
                    'status' => 1,
                    'created_at' => date('Y-m-d H:i:s'),
                    // 'created_by' => $request->user_id,
                    'slug' => createSlug('candidate_job_applies', $applicationNumber),

                ]);
                
                // print_r($request->educations);
                
                
                


                // Insert education records
                if (!empty($request->educations)) {
                    foreach ($request->educations as $education) {
                        CandidateEducation::insert([
                            'candidate_job_apply_id' => $candidateJobApplication,
                            'qualification_id' => $education['qualification_id'],
                            'course' => $education['course'],
                            'school_college' => $education['school_college'],
                            'city' => $education['city'],
                            'university_board' => $education['university_board'],
                            'passing_year' => $education['passing_year'],
                            'created_at' => date('Y-m-d H:i:s'),
                        ]);
                    }
                }
                
                

                // Insert experience records
                if (!empty($request->experience)) {
                    foreach ($request->experience as $experience) {
                        
                        CandidateExperience::insert([
                            'candidate_job_apply_id' => $candidateJobApplication,
                            'organisation_name' => $experience['organisation_name'],
                            'designation' => $experience['designation'],
                            'start_date' => $experience['startDate'],
                            'end_date' => $experience['endDate'],
                            'reason_of_leaving' => $experience['reason_of_leaving'],
                            'created_at' => date('Y-m-d H:i:s'),
                        ]);
                    }
                }
                
                if (!empty($request->process_order_ids)) {
                    $interviewProcessIds = explode(',', $request->process_order_ids);
                    
                    if(!empty($interviewProcessIds)){
                        foreach ($interviewProcessIds as $processId) {
                            DB::table('candidate_interview_journeys')->insert([
                                'candidate_id' => $candidateJobApplication,
                                'job_id' => $request->jobId,
                                'process_id' => $processId,
                                'completion_status' => '0',
                            ]);
                        }
                    }
                    
                }

                
                

                return Response(['response' => 'Application submitted successfully', 'status' => 200], 200);
            }

        } else {
            
            $jobDetails = Job::where('slug',$slug)->first();
            $yearList = $GLOBALS['yearsArray'];
            $designationList = Skill::where('employer_id', $employerId)->where('status', 1)->where('type', 'Designation')->get();
            $qualificationList = Qualification::where('employer_id', $employerId)->where('status', 1)->get();

            return Response(['response' => ['jobDetails' => $jobDetails, 'yearList' => $yearList, 'designationList' => $designationList, 'qualificationList' => $qualificationList], 'status' => 200], 200);
        }
    }
    
    public function admin_editJob(Request $request, $slug) {
        
        
        
        $user = Auth::user();
        $userId = $user->id;
        
        $adminDetail = Admin::find($userId);
        $employerDetail = Employer::find($userId);
        $staffDetail = Staff::find($userId);
    
        // Initialize variables
        $category = [];
        $industry = [];
        $qualification = [];
        $skill = [];
        $designation = [];
        // $processData = [];
    
        $worktypeData = $GLOBALS['worktype'];
        $experience = $GLOBALS['experienceArray'];
        $annual_salary = $GLOBALS['salary'];
        $jobData = Job::where('slug', $slug)->first();
        if (!empty($request->all())) {
            
            $validator = Validator::make($request->all(), [
                'job_title' => 'required',
                'job_description' => 'required',
                'category' => 'required',
                'designation' => 'required',
                // 'skill' => 'required',
                'work_type' => 'required',
            ]);
    
            if ($validator->fails()) {
                return Response(['response' => $validator->errors(), 'status' => 500], 200);
            }
    
            if (!empty($adminDetail)) {
                $category = Category::where('status', 1)->get();
                $industry = Industry::where('status', 1)->get();
                $qualification = Qualification::where('status', 1)->get();
                $skill = Skill::where('status', 1)->where('type', 'Skill')->get();
                $designation = Skill::where('status', 1)->where('type', 'Designation')->get();
            } else if (!empty($employerDetail)) {
                $category = Category::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $processData = Process::where('employer_id', $userId)->get();
                // $industry = Industry::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                // $industry = Industry::where('status', 1)
                // ->where(function($query) use ($userId) {
                //     $query->where('employer_id', '!=', 0)
                //         ->orWhere(function($query) use ($userId) {
                //             $query->where('employer_id', 0)
                //                   ->whereRaw("FIND_IN_SET(? employer_status)", [$userId]);
                //         });
                // })
                // ->get();
                
                $industry = Industry::where('status', 1)
                    ->where(function($query) use ($userId) {
                        $query->where('employer_id', '!=', 0)
                              ->orWhere(function($query) use ($userId) {
                                  $query->where('employer_id', 0)
                                        ->whereRaw("employer_status NOT LIKE ?", ["%,$userId,%"]);
                              });
                    })
                    ->get();

                $qualification = Qualification::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $skill = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Skill')->get();
                $designation = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Designation')->get();
            } elseif (!empty($staffDetail)) {
                $category = Category::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $industry = Industry::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $qualification = Qualification::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $skill = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Skill')->get();
                $designation = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Designation')->get();
            }
            
            // Job::where('slug', $slug)->update([
            //     'title' => $request->job_title,
            //     'category_id' => $request->category,
            //     'description' => $request->job_description,
            //     'industry' => $request->industry,
            //     'work_type' => $request->work_type,
            //     'experience' => $request->experience,
            //     'qualification' => $request->qualification,
            //     'annual_salary' => $request->annual_salary,
            //     'skill' => $request->skill,
            //     'designation' => $request->designation,
            //     'slug' => createSlug('jobs', $request->job_title),
            //     'process_order_ids' => $request->process_order_ids,
            // ]);
            // Extract and validate experience range
            $experienceRange = $request->experience;
            list($minExp, $maxExp) = explode('-', $experienceRange);
            $minExp = trim($minExp);
            $maxExp = trim($maxExp);
            
            // Extract and validate salary range
            $salaryRange = $request->annual_salary;
            list($minSalary, $maxSalary) = explode('-', $salaryRange);
            $minSalary = trim($minSalary);
            $maxSalary = trim($maxSalary);
            
            // Update the job record
            Job::where('slug', $slug)->update([
                'title' => $request->job_title,
                'category_id' => $request->category,
                'description' => $request->job_description,
                'industry' => $request->industry,
                'work_type' => $request->work_type,
                'min_exp' => $minExp,
                'max_exp' => $maxExp,
                'qualification' => $request->qualification,
                'min_salary' => $minSalary,
                'max_salary' => $maxSalary,
                'location' => $request->location,
                'skill' => $request->skill,
                'designation' => $request->designation,
                'slug' => createSlug('jobs', $request->job_title),
                'process_order_ids' => $request->process_order_ids,
            ]);

    
            // $job = new Job();
            // $job->title = $request->job_title;
            // $job->category_id = $request->category;
            // $job->description = $request->job_description;
            // $job->industry = $request->industry;
            // $job->work_type = $request->work_type;
            // $job->experience = $request->experience;
            // $job->qualification = $request->qualification;
            // $job->annual_salary = $request->annual_salary;
            // $job->skill = $request->skill;
            // $job->designation = $request->designation;
            // $job->status = 1;
            // $job->user_id = $userId;
            // $job->admin_id = !empty($adminDetail) ? $userId : 0;
            // $job->employer_id = !empty($employerDetail) ? $userId : 0;
            // $job->staff_id = !empty($staffDetail) ? $userId : 0;
            // $job->job_status = 1;
            // $job->slug = createSlug('jobs', $request->job_title);
    
            // $job->save();
    
            return Response(['response' => "", 'message' => 'Job added successfully', 'status' => 200], 200);
        } else {
            // Populate data when the page is loaded
            if (!empty($adminDetail)) {
                $category = Category::where('status', 1)->get();
                $industry = Industry::where('status', 1)->get();
                $qualification = Qualification::where('status', 1)->get();
                $skill = Skill::where('status', 1)->where('type', 'Skill')->get();
                $designation = Skill::where('status', 1)->where('type', 'Designation')->get();
            } else if (!empty($employerDetail)) {
                // $category = Category::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $category = Category::where('status', 1)
                ->where(function($query) use ($userId) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $userId)
                          ->orWhere(function($query) use ($userId) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$userId]);
                          });
                })
                ->get();
                
                
                // $industry = Industry::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $industry = Industry::where('status', 1)
                ->where(function($query) use ($userId) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $userId)
                          ->orWhere(function($query) use ($userId) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$userId]);
                          });
                })
                ->get();
                // $qualification = Qualification::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $qualification = Qualification::where('status', 1)
                ->where(function($query) use ($userId) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $userId)
                          ->orWhere(function($query) use ($userId) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$userId]);
                          });
                })
                ->get();
                // $skill = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Skill')->get();
                $skill = Skill::where('status', 1)->where('type', 'Skill')
                ->where(function($query) use ($userId) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $userId)
                          ->orWhere(function($query) use ($userId) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$userId]);
                          });
                })
                ->get();
                // $designation = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Designation')->get();
                $designation = Skill::where('status', 1)->where('type', 'Designation')
                ->where(function($query) use ($userId) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $userId)
                          ->orWhere(function($query) use ($userId) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$userId]);
                          });
                })
                ->get();
                
                $processData = Process::where('employer_id', $userId)->get();

            } elseif (!empty($staffDetail)) {
                $category = Category::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $industry = Industry::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $qualification = Qualification::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $skill = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Skill')->get();
                $designation = Skill::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->where('type', 'Designation')->get();
            }
            
            $job = Job::where('slug', $slug)->first();

            if (!$job) {
                return Response(['response' => "", 'message' => "Job not found", 'status' => 404], 200);
            }
            
            $jobData = array();
            $jobData['id'] = $job->id;
            $jobData['job_title'] = $job->title;
            $jobData['category'] = $job->category_id;
            $jobData['job_description'] = $job->description;
            $jobData['industry'] = $job->industry;
            $jobData['work_type'] = $job->work_type;
            $jobData['location'] = $job->location;
            $minExp = $job->min_exp;
            $maxExp = $job->max_exp;
            $jobData['experience'] = implode("-", [$minExp, $maxExp]);
            $jobData['qualification'] = $job->qualification;
            $minSalary = $job->min_salary;
            $maxSalary = $job->max_salary;
            $jobData['annual_salary'] = implode("-", [$minSalary, $maxSalary]);


            $jobData['skill'] = $job->skill;
            $jobData['designation'] = $job->designation;
            $jobData['process_order_ids'] = $job->process_order_ids;
            // $jobData['physically_challenged'] = $job->physically_challenged;
            // $jobData['address'] = $job->address;
            
            $data = array();
            $data['category'] = $category;
            $data['job'] = $jobData;
            $data['industry'] = $industry;
            $data['worktype'] = $worktypeData;
            $data['experience'] = $experience;
            $data['qualification'] = $qualification;
            $data['annual_salary'] = $annual_salary;
            $data['skill'] = $skill;
            $data['designation'] = $designation;
            $data['process_list'] = $processData;
            $data['jobs_details'] = $jobData;
            
            return Response(['response' => $data, 'status' => 200], 200);

        }
    }

    
    public function admin_deleteJob($slug){
        $jobData = Job::where('slug', $slug)->first();

        $currentUser = Auth::user()->id;
        $currentUserCheck = Admin::where('id', $currentUser)->first();
        // echo $currentUser;
        if (!empty($currentUserCheck)) {
            //admin
            if (!empty($jobData)) {
                Job::where('slug', $slug)->delete();
                $msgString = 'Job deleted successfully';
                return Response(['response' => $msgString, 'message' => $msgString, 'status' => 200], 200);
            } else {

                $msgString = 'No record deleted';
                return Response(['response' => $msgString, 'message' => $msgString, 'status' => 500], 200);
            }
        } else {
            //employer
            if ($jobData->employer_id != 0) {
                // echo "hi";
                Job::where('slug', $slug)->delete();
                $msgString = 'Job deleted successfully';
                return Response(['response' => $msgString, 'message' => $msgString, 'status' => 200], 200);
            } else {
                return Response(['response' => "", 'message' => "This is a system generated qualification and cannot be deleted", 'status' => 500], 200);
            }
        }
    }
    
    public function activateJob($slug) {
        
        $currentUser = Auth::user()->id;
        $currentUserCheck = Admin::where('id', $currentUser)->first();
        // echo $currentUser;
        if (!empty($currentUserCheck)) {
            $jobData = Job::where('slug', $slug)->first();
            if (!empty($jobData)) {
                Job::where('slug', $slug)->update([
                    'status' => 1
                ]);
                return Response(['response' => "", 'message' => 'Job activated successfully', 'status' => 200], 200);
            }
        } else {
            // Employer login
            $job = Job::where('slug', $slug)->first();
            if (!empty($job)) {
            $employerId = $job->employer_id;
                if($employerId == 0){
                    $employerStatus = $job->employer_status;
    
                    // Convert the comma-separated string into an array
                    $employerStatusArray = explode(',', $employerStatus);
    
                    // Check if the user ID is in the array
                    if (($key = array_search($currentUser, $employerStatusArray)) !== false) {
                        // Remove the user ID from the array
                        unset($employerStatusArray[$key]);
    
                        // Convert the array back to a comma-separated string
                        $updatedEmployerStatus = implode(',', $employerStatusArray);
    
                        // Update the qualification's employer status
                        $job->employer_status = $updatedEmployerStatus;
    
                        // Save the changes to the database
                        $job->save();
                    }
                } else{
                    Job::where('slug', $slug)->update([
                        'status' => 1
                    ]);
                }
            }
        }

        return Response(['response' => '', 'message' => "Job activated successfully", 'status' => 200], 200);
    }
    
    public function deactivateJob($slug) {
        $currentUser = Auth::user()->id;
        $currentUserCheck = Admin::where('id', $currentUser)->first();
    
        if (!empty($currentUserCheck)) {
            // If the current user is an admin
            $jobData = Job::where('slug', $slug)->first();
            if (!empty($jobData)) {
                Job::where('slug', $slug)->update([
                    'status' => 0
                ]);
                return Response(['response' => "", 'message' => 'Job deactivated successfully', 'status' => 200], 200);
            }
        } else {
            // If the current user is an employer
            $job = Job::where('slug', $slug)->first();
            if (!empty($job)) {
                $employerId = $job->employer_id;
                if($employerId == 0) {
                    $employerStatus = $job->employer_status;
    
                    // Convert the comma-separated string into an array
                    $employerStatusArray = explode(',', $employerStatus);
        
                    // Check if the user ID is in the array
                    if (!in_array($currentUser, $employerStatusArray)) {
                        // Add the user ID to the array
                        $employerStatusArray[] = $currentUser;
        
                        // Convert the array back to a comma-separated string
                        $updatedEmployerStatus = implode(',', $employerStatusArray);
        
                        // Update the job's employer status
                        $job->employer_status = $updatedEmployerStatus;
        
                        // Save the changes to the database
                        $job->save();
                    }
                } else{
                    Job::where('slug', $slug)->update([
                        'status' => 0
                    ]);
                }
                
            }
        }
    
        return Response(['response' => '', 'message' => "Job deactivated successfully", 'status' => 200], 200);
    }
    
    public function getAppliedCandidateListforJob($slug) {
        $jobId = $slug;
        
        $candidateList = CandidateJobApply::where('job_form_id', $jobId)->get();
        
        return Response(['response' => $candidateList, 'status' => 200],200);
    }
    
    // public function appliedCandidateListForJob(Request $request) {
    //     $jobId = $request->job_id;
    //     $employerId = Auth::user()->id;
    //     $jobName = Job::where('id', $jobId)->value('title');
        
        
    //     $dumyCandiateData = CandidateJobApply::where('job_form_id', $jobId)->get();
        
    //     //employer name
    //     $employerData = Employer::where('id', $employerId)->select(['first_name', 'last_name'])->first();
    //     $employerName = $employerData->first_name . ' ' . $employerData->last_name;
        
    //     //update date of birth
    //     $dob = $dumyCandiateData->date_of_birth;
    //     $dateTime = new DateTime($dob);
    //     $formattedDate = $dateTime->format('D, d M Y');
        
    //     //add path in profile img, document 
    //     $profileImg = DISPLAY_FULL_PROFILE_IMAGE_PATH . $dumyCandiateData->profile_img;
    //     $documentsCvs = DISPLAY_RESUME_PATH . $dumyCandiateData->document_cv;
        
        
    //     $candidateData['job_name'] = $jobName;
    //     $candidateData['employer_name'] = $employerName;
    //     $candidateData['date_of_birth'] = $formattedDate;
    //     $candidateData['profile_img'] = $profileImg;
    //     $candidateData['document_cv'] = $documentsCvs;
        
    //     //gender, marital status, physically challenged
        
    //     if($dumyCandiateData->gender == 1){
    //         $candidateData['gender'] = "Male";
    //     } else if($dumyCandiateData->gender == 2){
    //         $candidateData['gender'] = "Female";
    //     }else{
    //         $candidateData['gender'] = "Other";
    //     }
        
    //     if($dumyCandiateData->martial_status == 1){
    //         $candidateData['martial_status'] = "Single";
    //     } else if($dumyCandiateData->martial_status == 2){
    //         $candidateData['martial_status'] = "Married";
    //     } else if($dumyCandiateData->martial_status == 3){
    //         $candidateData['martial_status'] = "Divorced";
    //     }else{
    //         $candidateData['martial_status'] = "N/A";
    //     }
        
        
    //     if($dumyCandiateData->physically_challenged == 1){
    //         $candidateData['physically_challenged'] = "Yes";
    //     } else if($dumyCandiateData->physically_challenged == 2){
    //         $candidateData['physically_challenged'] = "No";
    //     } else if($dumyCandiateData->physically_challenged == 3){
    //         $candidateData['physically_challenged'] = "Prefer not to say";
    //     }else{
    //         $candidateData['physically_challenged'] = "N/A";
    //     }
        
    //     return Response(['response' => $candidateData, 'message' => 'Candidate data send successfully', 'status' => 200], 200);
    // }
    
    
    public function appliedCandidateListForJob(Request $request) {
        $jobId = $request->job_id;
        $employerId = Auth::user()->id;
    
        // Get job name
        $jobName = Job::where('id', $jobId)->value('title');
        if (!$jobName) {
            return Response(['response' => '', 'message' => 'Job not found', 'status' => 500], 200);
        }
    
        // Get employer data
        $employerData = Employer::where('id', $employerId)->select(['first_name', 'last_name'])->first();
        if (!$employerData) {
            return Response(['response' => '', 'message' => 'Employer not found', 'status' => 500], 200);
        }
        $employerName = "{$employerData->first_name} {$employerData->last_name}";
    
        // Get candidates who applied for the job
        $dummyCandidateData = CandidateJobApply::where('job_form_id', $jobId)->get();
    
        // Initialize candidate data array
        $candidates = [];
    
        foreach ($dummyCandidateData as $candidate) {
            $formattedDate = $candidate->date_of_birth 
                ? (new DateTime($candidate->date_of_birth))->format('D, d M Y') 
                : 'N/A';
    
            $profileImg = $candidate->profile_img 
                ? DISPLAY_FULL_PROFILE_IMAGE_PATH . $candidate->profile_img 
                : null;
    
            $documentsCvs = $candidate->document_cv 
                ? DISPLAY_RESUME_PATH . $candidate->document_cv 
                : null;
    
            if ($candidate->gender == 1) {
                $gender = 'Male';
            } elseif ($candidate->gender == 2) {
                $gender = 'Female';
            } else{
                $gender = 'Other';
            }
            
            if ($candidate->marital_status == 1) {
                $maritalStatus = 'Single';
            } elseif ($candidate->marital_status == 2) {
                $maritalStatus = 'Married';
            } elseif ($candidate->marital_status == 3){
                $maritalStatus = 'Divorced';
            } else{
                $maritalStatus = 'N/A';
            }
            
            if ($candidate->physically_challenged == 1) {
                $physicallyChallenged = 'Yes';
            } elseif ($candidate->physically_challenged == 2) {
                $physicallyChallenged = 'No';
            } elseif ($candidate->physically_challenged == 3){
                $physicallyChallenged = 'Prefer not to say';
            } else{
                $physicallyChallenged = 'N/A';
            }
            
            $education = CandidateEducation::where('candidate_job_apply_id', $candidate->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;
            }
            
            
            $experience = CandidateExperience::where('candidate_job_apply_id', $candidate->id)->get();
            $experienceData = array();
            foreach ($experience as $expKey => $expValue) {
                $experienceData[$expKey]['id'] = $expValue->id;
                $experienceData[$expKey]['organisation_name'] = $expValue->organisation_name;
                $experienceData[$expKey]['designation'] = Skill::find($expValue->designation)->skill_name;
                $experienceData[$expKey]['reason_of_leaving'] = $expValue->reason_of_leaving;
                $experienceData[$expKey]['start_date'] = $expValue->start_date;
                $experienceData[$expKey]['end_date'] = $expValue->end_date;
            }

            $candidates[] = [
                'candidate_id' => $candidate->id,
                'job_id' => $candidate->job_form_id,
                'employer_id' => $candidate->employer_id,
                'application_number' => $candidate->application_number,
                'first_name' => $candidate->first_name,
                'middle_name' => $candidate->middle_name,
                'last_name' => $candidate->last_name,
                'contact_number' => $candidate->contact_number,
                'job_name' => $jobName,
                'employer_name' => $employerName,
                'date_of_birth' => $formattedDate,
                'profile_img' => $profileImg,
                'document_cv' => $documentsCvs,
                'gender' => $gender,
                'marital_status' => $maritalStatus,
                'physically_challenged' => $physicallyChallenged,
                'job_application_status' => $candidate->job_application_status,
                'email' => $candidate->email,
                'address' => $candidate->address,
                'slug' => $candidate->slug,
                'interview_status' => $candidate->interview_status,
                'interview_round' => $candidate->interview_round,
                'is_selected' => $candidate->is_selected,
                'is_rejected' => $candidate->is_rejected,
                'status' => $candidate->status,
                'process_id' => $candidate->process_id,
                'ratings' => $candidate->ratings,
                'is_interview_scheduled' => $candidate->is_interview_scheduled,
                'offer_letter_status' => $candidate->offer_letter_status,
                'on_boarding_status' => $candidate->on_boarding_status,
                'draft_status' => $candidate->draft_status,
                'job_applied_date' => date('d-m-Y', strtotime($candidate->created_at)),
                'educationData' => $educationData,
                'experienceData' => $experienceData,
            ]; 
            
            
        }
        
        
        
    
        if (empty($candidates)) {
            return Response(['response' => '','message' => 'No candidates found for this job', 'status' => 500], 200);
        }
    
        return Response(['response' => $candidates, 'message' => 'Candidate data sent successfully', 'status' => 200], 200);
    }



    
}
