<?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\Support\Facades\Http;
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 App\Models\DirectApplication;
use App\Models\DirectApplicationForm;
use Illuminate\Support\Facades\Auth;
use DateTime;
use Carbon\Carbon;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Mail;
use App\Models\EmailTemplate;
use App\Mail\SendMail;
use App\Models\Candidate;
use App\Models\GeneralSetting;
use App\Models\Notification;


class JobsController extends Controller
{
    //
    
    public function listing(Request $request) {
        // $employerSession = $request->employer_id;
        
        $employerSession = $request->employer_id;
        
        $employerId = Employer::where('employer_code', $employerSession)->value('id');
        
        $jobs = Job::where('employer_id', $employerId)->where('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)) {
            
            // Code for handling multiple Activate, Deactivate and Delete
            if ($request->filled('action')) {
                $idList = $request->idList;
                if ($idList) {
                    if ($request->action == 'activate') {
                        $idList = $request->idList; // Assuming $idList is comma-separated IDs
                        Job::whereIn('id', explode(',', $idList))->update(['status' => '1']);
                    }elseif ($request->action == 'deactivate') {
                        $idList = $request->idList;
                        Job::whereIn('id', explode(',', $idList))->update(['status' => '0']);
                    } elseif ($request->action == 'delete') {
                        $idList = $request->idList;
                        Job::whereIn('id', explode(',', $idList))->delete();
                    }
                }
            }
            
            $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, 'status' => 200], 200);
            
        } else if(!empty($staffCheck)){
            
            if ($request->filled('action')) {
                $idList = $request->idList;
                if ($idList) {
                    if ($request->action == 'activate') {
                        $idList = $request->idList; // Assuming $idList is comma-separated IDs
                        Job::whereIn('id', explode(',', $idList))->update(['status' => '1']);
                    }elseif ($request->action == 'deactivate') {
                        $idList = $request->idList;
                        Job::whereIn('id', explode(',', $idList))->update(['status' => '0']);
                    } elseif ($request->action == 'delete') {
                        $idList = $request->idList;
                        Job::whereIn('id', explode(',', $idList))->delete();
                    }
                }
            }
            
            
            $jobs = Job::where('job_status', 1)->where('staff_id', $currentUser)->orderBy('id','desc')->get();
            $jobData = array();

            foreach($jobs as $key => $value) {
                
                $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";
                }
                
                $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";
                }
                
                    
                $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;
                
                $jobData[$key]['posted_by_employer'] = $value->posted_by_employer;
            }
    
            return Response(['response' => $jobData, 'status' => 200], 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);
        
        // return Response(['response' => $staffDetail->first_name, 'message' => '', 'status' => 200], 200);
        // exit();
    
        // 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();
                
                $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 = 0;
                $job->staff_id = 0;
                $job->job_status = 1;
                $job->posted_by_employer = 0;
                $job->slug = createSlug('jobs', $request->job_title);
        
                $job->save();
        
                return Response(['response' => $job, 'message' => 'Job added successfully', 'status' => 200], 200);
                
                
            } 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)
                              ->orWhere(function($query) use ($userId) {
                                  $query->where('employer_id', 0)
                                        ->whereRaw("employer_status NOT LIKE ?", ["%,$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('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();
                
                $skill = Skill::where('status', 1)
              ->where('type', 'Skill')
              ->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,%"]);
                         });
              });
              
              $designation = Skill::where('status', 1)
              ->where('type', 'Designation')
              ->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,%"]);
                         });
              });
              
              
              $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 = 0;
            $job->employer_id = !empty($employerDetail) ? $userId : 0;
            $job->staff_id = 0;
            $job->job_status = 1;
            $job->posted_by_employer = 1;
            $job->slug = createSlug('jobs', $request->job_title);
            
            $customSection = $request->input('custom_section', []);
            
            $job->custom_fields = json_encode($customSection);
            // return Response(['response' =>  $job->custom_fields, 'status' => 200], 200);
            // exit();
    
            $job->save();
            
            
    
            return Response(['response' => $job, 'message' => 'Job added successfully', 'status' => 200], 200);


                // $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();
                
                
                
                $category = Category::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();
                
                $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('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();
                
                $skill = Skill::where('status', 1)
              ->where('type', 'Skill')
              ->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,%"]);
                         });
              });
              
              $designation = Skill::where('status', 1)
              ->where('type', 'Designation')
              ->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,%"]);
                         });
              });
              
                $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 = 0;
                $job->employer_id = $staffDetail->employer_id;
                $job->staff_id = !empty($staffDetail) ? $userId : 0;
                $job->job_status = 1;
                $job->posted_by_employer = 0;
                $job->slug = createSlug('jobs', $request->job_title);
        
                $job->save();
        
                return Response(['response' => $job, 'message' => 'Job added successfully', 'status' => 200], 200);
              
              
            //   $postedByEmployer = 0;
            }
    
            // $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();
                
                
                $adminData = $staffDetail;
                
                $accessData = isset($adminData->roles) ? unserialize($adminData->roles) : [];
            
                    global $subadminAccess;
                    $accessControlArray = $subadminAccess;
            
                    if (!is_array($accessControlArray)) {
                        return response()->json(['message' => 'Access control data is missing or invalid', 'status' => 500], 500);
                    }
            
                    $accessArray = [];
                    foreach ($accessControlArray as $key => $ac) {
                        $accessArray[$key] = $ac; // Start with the original sub-array
            
                        // Override with $accessData if available
                        if (isset($accessData[$key])) {
                            foreach ($accessData[$key] as $accessKey => $accessValue) {
                                $accessArray[$key][$accessKey] = $accessValue;
                            }
                        }
                    }
                
                
                if($accessArray['0']['Add'] == 0){
                    return Response(['response' => 'You are not allowed to Add Job.', 'message' => '', 'status' => 500], 200);
                }
                
                
                
                $employerID = $staffDetail->employer_id;
                // return Response(['response' => $employerID, 'status' => 200], 200);
                // exit();
                
                $category = Category::where('status', 1)
                ->where(function($query) use ($employerID) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $employerID)
                          ->orWhere(function($query) use ($employerID) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$employerID]);
                          });
                })
                ->get();
                
                $industry = Industry::where('status', 1)
                ->where(function($query) use ($employerID) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $employerID)
                          ->orWhere(function($query) use ($employerID) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$employerID]);
                          });
                })
                ->get();
                
                $qualification = Qualification::where('status', 1)
                ->where(function($query) use ($employerID) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $employerID)
                          ->orWhere(function($query) use ($employerID) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$employerID]);
                          });
                })
                ->get();
                
                $skill = Skill::where('status', 1)->where('type', 'Skill')
                ->where(function($query) use ($employerID) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $employerID)
                          ->orWhere(function($query) use ($employerID) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$employerID]);
                          });
                })
                ->get();
                
                
                $designation = Skill::where('status', 1)->where('type', 'Designation')
                ->where(function($query) use ($employerID) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $employerID)
                          ->orWhere(function($query) use ($employerID) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$employerID]);
                          });
                })
                ->get();
                
                $processList = Process::where('employer_id', $employerID)->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 getFromAI(Request $request){
        
        $jobTitle = $request->job_title;
        
        // Hugging Face API URL
        $huggingFaceUrl = 'https://api-inference.huggingface.co/models/google/flan-t5-large';

        // Make API request
        $response = Http::withHeaders([
            'Authorization' => 'Bearer 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', // Replace with your API key
        ])->post($huggingFaceUrl, [
            
              'inputs' => "Write a detailed 200-word job description for a " . $jobTitle,
              'parameters' => [
                'max_new_tokens' => 250,
                'temperature' => 0.7,
                'top_p' => 0.9,
                'do_sample' => true
              ]
        ]);
        
        $data = $response->json();

    // Return only the first object inside the array
    return response()->json($data[0] ?? []);
        
        // return Response(['response' => $response, 'message' => 'success', 'status' => 200], 200);
        // return response()->json($response->json());
        
    }


    
    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;
}

$profilePictureName="";

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;
                
                // $customSection = $request->input('custom_fields', []);
                // $job->custom_fields = json_encode($customSection);

                $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,
                    'cover_letter_title' => $request->cover_letter_title,
                    'cover_letter_description' => $request->cover_letter_description,
                    'status' => 1,
                    'created_at' => date('Y-m-d H:i:s'),
                    'custom_fields_data' => json_encode($request->input('custom_fields', [])),
                    // 'created_by' => $request->user_id,
                    'slug' => createSlug('candidate_job_applies', $applicationNumber),

                ]);
                
                // print_r($request->educations);
                
                $employerID = Employer::where('employer_code', $request->employer_id)->first();
                
                $getCandidateDetails = Candidate::where('email', $request->email)->first();
                if(empty($getCandidateDetails)){
                    Candidate::insert([
                        'employer_id' => $employerID->id,
                        '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,
                    ]);
                }
                


                // 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',
                            ]);
                        }
                    }
                    
                }

                if (!empty($employerId)) {
                    $candidateAccountCreationStatus = Employer::where('id', $employerId)->value('allow_candidate_accounts');
                                // return Response(['response' => $candidateAccountCreationStatus, 'status' => 200], 200);

                    if ($candidateAccountCreationStatus == 1) {
                        // Generate a random password of length 10
                        $randomPassword = Str::random(10);
                        $fullName = $request->firstName . ' ' . $request->lastName;
                
                        $hashedPassword = Hash::make($randomPassword);
                        
                        // dd($hashedPassword);
                        // return Response(['response' => $hashedPassword, 'status' => 200], 200);
                        // exit();
                
                        $candidateExistingData = Candidate::where('employer_id', $request->employer_id)->where('email', $request->email)->first();
                        
                        if(empty($candidateExistingData->password)){
                            Candidate::where('employer_id', $request->employer_id)->where('email', $request->email)->update(['password' => $hashedPassword]);
                        }
                        
                        
                        // Now if the password is stored the send an email to the candidate about account creation
                        
                        try{
            
                            
                            $user = Employer::where('id', $request->employer_id)->first();
                               
                
                            if(!empty($user)) {
                                $token = Str::random(60);
                                    
                                $url = HTTP_PATH_FRONTEND.'/candidate-panel/employer/'.$request->employer_id .'/candidate-login/'.$candidateJobApplication;
                                  
                                $employerCompanyName = $user->company_name;
                                  
                                $emailTemplate = EmailTemplate::where('id', 10)->first();
                                  
                                  
                                $toRepArray = ['[!candidate_name!]', '[!company_name!]', '[!candidate_email!]', '[!password!]', '[!login_url!]'];
                                $fromRepArray = [$fullName, $employerCompanyName, $request->email, $randomPassword, $url];
                                $emailSubject = str_replace($toRepArray, $fromRepArray, $emailTemplate->subject);
                                $emailBody = str_replace($toRepArray, $fromRepArray, $emailTemplate->template);
                                    
                                $logo = $user->company_logo;
                                
                                if(!empty($logo)){
                                    $logoPath = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $logo;
                                } else{
                                    $logoPath = LOGO_PATH;
                                }
                                
                                // Send the email
                                try {
                                    Mail::to($request->email)->send(new SendMail($emailBody, $emailSubject, $logoPath));
                                } catch (\Exception $e) {
                                    return response()->json(['error' => 'Failed to send email.', 'message' => $e->getMessage()], 500);
                                }
                                return Response(['response' => 'Application submitted successfully! Your account has been created, please check your registered email for login credentials.', 'message'=> 'We have e-mailed your password reset link!', 'status' => 200], 200);
                
                            }
                             else{
                                  return Response(['response' => 'Count not send email', 'status' => 500], 200);
                            }
                
                        }
                        catch(Exception $e) {
                            return Response(['response' => $e->getMessage(), 'status' => 500], 200);
                        }
                        
                        // Email Code ends here
                    }
                }
                
                $employerID = Employer::where('employer_code', $request->employer_id)->first();
                
                $jobName = Job::where('slug', $slug)->value('title');
                
                Notification::create([
                    'user_id' => $employerID->id,
                    'user_type' => 'employer',
                    'notification_title' => 'New Job Application',
                    'notification_text' => 'A candidate has applied for' . ' ' . $jobName . '.',
                    'mark_as_read' => '0',
                ]);

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

        } else {
            
            $jobDetails = Job::where('slug',$slug)->first();
            
            if ($jobDetails) {
                $jobDetailsData = [];
                $jobDetailsData['title'] = $jobDetails->title;
                $jobDetailsData['category_id'] = $jobDetails->category_id;
                
                $categoryName = Category::where('id', $jobDetails->category_id)->value('category_name');
                $jobDetailsData['category_name'] = $categoryName;
                
                $jobDetailsData['industry'] = $jobDetails->industry;
                $industryName = Industry::where('id', $jobDetails->industry)->value('industry_name') ?? 'N/A';
                $jobDetailsData['industry_name'] = $industryName;
                
                $jobDetailsData['work_type'] = $jobDetails->work_type;
                $workTypeMapping = [
                    '1' => 'Full Time',
                    '2' => 'Part Time',
                    '3' => 'Casual',
                    '4' => 'Seasonal',
                    '5' => 'Fixed Term',
                ];
                $workTypeValue = $jobDetails->work_type;
                $workTypeString = $workTypeMapping[$workTypeValue] ?? 'Unknown';
                $jobDetailsData['work_type_name'] = $workTypeString;
                
                $jobDetailsData['qualification'] = $jobDetails->qualification;
                $jobDetailsData['qualification_name'] = Qualification::where('id', $jobDetails->qualification)->value('qualification_name');
                
                $jobDetailsData['skill'] = $jobDetails->skill;
                $jobDetailsData['skill_name'] = Skill::where('id', $jobDetails->skill)->value('skill_name');
                
                $designationName = Skill::where('type', 'Designation')->where('id', $jobDetails->designation)->value('skill_name');
                if(!empty($designationName)){
                    $jobDetailsData['designation'] = $designationName;
                } else{
                    $jobDetailsData['designation'] = $jobDetails->designation;
                }
                
                $jobDetailsData['employer_id'] = $jobDetails->employer_id;
                $jobDetailsData['employer_name'] = Employer::where('id', $jobDetails->employer_id)->select('first_name', 'last_name')->first();
                
                $applicationFormBanner = GeneralSetting::where('employer_id', $jobDetails->employer_id)->first();
                
                if(!empty($applicationFormBanner->application_form_banner)){
                    $jobDetailsData['existing_application_form_banner'] = DISPLAY_FULL_BANNER_IMAGE_PATH . $applicationFormBanner->application_form_banner;
                } else{
                    $jobDetailsData['existing_application_form_banner'] = '';
                }
                
                $jobDetailsData['max_exp'] = $jobDetails->max_exp;
                $jobDetailsData['max_salary'] = CURR.$jobDetails->max_salary;
                $jobDetailsData['min_exp'] = $jobDetails->min_exp;
                $jobDetailsData['min_salary'] = CURR.$jobDetails->min_salary;
                $jobDetailsData['location'] = $jobDetails->location;
                $jobDetailsData['description'] = $jobDetails->description;
                
                $jobDetailsData['id'] = $jobDetails->id;
                $jobDetailsData['process_order_ids'] = $jobDetails->process_order_ids;
                
                $jobDetailsData['custom_fields'] = $jobDetails->custom_fields ? json_decode($jobDetails->custom_fields, true) : [];
                
                
            } else {

                $jobDetailsData = null; 
            }
            
            $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();
            
            $qualificationList = Qualification::where('status', 1)
                ->where(function ($query) use ($employerId) {
                    $query->where('employer_id', '!=', 0)
                          ->orWhere(function ($query) use ($employerId) {
                              $query->where('employer_id', 0)
                                    ->where(function ($query) use ($employerId) {
                                        $query->whereRaw("(employer_status NOT LIKE ? OR employer_status IS NULL)", ["%,$employerId,%"]);
                                    });
                          });
                })
                ->get();


            return Response(['response' => ['jobDetails' => $jobDetailsData, 'yearList' => $yearList, 'designationList' => $designationList, 'qualificationList' => $qualificationList], 'status' => 200], 200);
        }
    }
    
    
    public function getCoverLetterDescriptionFromAI(Request $request)
    {
        $coverLetterTitle = $request->cover_letter_title;
    
        // OpenAI API URL
        $openAiUrl = 'https://api.openai.com/v1/chat/completions';
    
        // Make API request
        $response = Http::withHeaders([
            'Authorization' => 'Bearer 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', // store key in .env
            'Content-Type'  => 'application/json',
        ])->post($openAiUrl, [
            'model' => 'gpt-3.5-turbo', // or 'gpt-4' if available
            'messages' => [
                [
                    'role' => 'system',
                    'content' => 'You are an expert cover letter writer.',
                ],
                [
                    'role' => 'user',
                    'content' => "Generate a compelling cover letter for a {$coverLetterTitle}.",
                ],
            ],
            'max_tokens' => 500,
            'temperature' => 0.7,
            'top_p' => 0.9,
        ]);
    
        $data = $response->json();
    
        // Extract the cover letter text
        $coverLetter = $data['choices'][0]['message']['content'] ?? 'No response generated.';
    
        return response()->json([
            'generated_text' => $coverLetter,
        ]);
    }
    
    
    
    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();
                
                // 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,
                ]);
                
                return Response(['response' => "", 'message' => 'Job added successfully', 'status' => 200], 200);
                
                
            } 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();
                
                
                // 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);
                
                $customSection = $request->input('custom_section', []);
                
                // 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,
            
                    'custom_fields' => json_encode($customSection),
                ]);
                
                return Response(['response' => "", 'message' => 'Job added successfully', 'status' => 200], 200);
                
                
            } 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();
                
                
                // 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);
                
                 $customSection = $request->input('custom_section', []);
                // 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,
                    'custom_fields' => json_encode($customSection),
                ]);
                
                return Response(['response' => "", 'message' => 'Job added successfully', 'status' => 200], 200);
                
                
            }
            
            
            // // 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,
            // ]);
            
            // return Response(['response' => "", 'message' => 'Job added successfully', 'status' => 200], 200);

    
            // $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();
    
        } 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();
                
                $adminData = $staffDetail;
                
                $accessData = isset($adminData->roles) ? unserialize($adminData->roles) : [];
            
                    global $subadminAccess;
                    $accessControlArray = $subadminAccess;
            
                    if (!is_array($accessControlArray)) {
                        return response()->json(['message' => 'Access control data is missing or invalid', 'status' => 500], 500);
                    }
            
                    $accessArray = [];
                    foreach ($accessControlArray as $key => $ac) {
                        $accessArray[$key] = $ac; // Start with the original sub-array
            
                        // Override with $accessData if available
                        if (isset($accessData[$key])) {
                            foreach ($accessData[$key] as $accessKey => $accessValue) {
                                $accessArray[$key][$accessKey] = $accessValue;
                            }
                        }
                    }
                
                
                if($accessArray['0']['Edit'] == 0){
                    return Response(['response' => 'You are not allowed to edit this job.', 'message' => '', 'status' => 500], 200);
                }
                
                
                $employerID = $staffDetail->employer_id;
                
                $category = Category::where('status', 1)
                ->where(function($query) use ($employerID) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $employerID)
                          ->orWhere(function($query) use ($employerID) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$employerID]);
                          });
                })
                ->get();
                
                
                // $industry = Industry::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $industry = Industry::where('status', 1)
                ->where(function($query) use ($employerID) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $employerID)
                          ->orWhere(function($query) use ($employerID) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$employerID]);
                          });
                })
                ->get();
                // $qualification = Qualification::where('employer_id', $userId)->orWhere('employer_id', 0)->where('status', 1)->get();
                $qualification = Qualification::where('status', 1)
                ->where(function($query) use ($employerID) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $employerID)
                          ->orWhere(function($query) use ($employerID) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$employerID]);
                          });
                })
                ->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 ($employerID) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $employerID)
                          ->orWhere(function($query) use ($employerID) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$employerID]);
                          });
                })
                ->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 ($employerID) {
                    $query->where('employer_id', '!=', 0)
                    ->where('employer_id', $employerID)
                          ->orWhere(function($query) use ($employerID) {
                              $query->where('employer_id', 0)
                                    ->whereRaw("NOT FIND_IN_SET(?, employer_status)", [$employerID]);
                          });
                })
                ->get();
                
                $processData = Process::where('employer_id', $employerID)->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]);
            
            $customSection = $job->custom_fields; // The JSON string

            // Decode the JSON string to an array of objects
            $customFieldsArray = json_decode($customSection, true); // true for array, false for stdClass objects
            
            // If you specifically want objects, use json_decode without true
            $customFieldsObjects = json_decode($customSection); // Returns array of stdClass objects
            
            // Assign to jobData or use as needed
            $jobData['custom_section'] = $customFieldsArray; // For array of arrays
            // OR
            // $jobData['custom_fields'] = $customFieldsObjects; // For array of objects


            $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;
        $adminCheck = Admin::where('id', $currentUser)->first();
        $employerCheck = Employer::where('id', $currentUser)->first();
        $staffCheck = Staff::where('id', $currentUser)->first();
        
        // echo $currentUser;
        
        //for admin 
        if (!empty($adminCheck)) {
            //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 if(!empty($employerCheck)) {
            //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);
            }
        } else{
            //staff
            if($jobData->staff_id != 0) {
                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)->orderBy('id','desc')->get();
    
        // Initialize candidate data array
        $candidates = [];
    
        foreach ($dummyCandidateData as $candidate) {
            $formattedDate = $candidate->date_of_birth 
                ? (new DateTime($candidate->date_of_birth))->format('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->martial_status == 1) {
                $maritalStatus = 'Single';
            } elseif ($candidate->martial_status == 2) {
                $maritalStatus = 'Married';
            } elseif ($candidate->martial_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;
                
                $designationName = Skill::where('type', 'Designation')->where('id', $expValue->designation)->value('skill_name');
                if(!empty($designationName)){
                    $experienceData[$expKey]['designation'] = $designationName;
                } else{
                    $experienceData[$expKey]['designation'] = $expValue->designation;
                }
                
                // $experienceData[$expKey]['designation'] = $expValue->designation;
                $experienceData[$expKey]['reason_of_leaving'] = $expValue->reason_of_leaving;
                $experienceData[$expKey]['start_date'] = date('d M Y',strtotime($expValue->start_date));
                $experienceData[$expKey]['end_date'] = date('d M Y',strtotime($expValue->end_date));
            }

            $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' => ['candidateList' => $candidates, 'jobName' => $jobName], 'message' => 'Candidate data sent successfully', 'status' => 200], 200);
    }
    
    
    public function get_direct_application_form_data_for_candidate(Request $request)
    {
        $employerId = $request->employer_id;
    
        // Validate the employer ID
        if (!$employerId) {
            return response([
                'response' => 'Employer ID is required.',
                'status' => 500
            ], 200);
        }
        
        $employers = Employer::where('employer_code', $employerId)->first();
    
        // Fetch preferences matching the employer ID
        $preferences = DirectApplicationForm::where('employer_id', $employers->id)->orWhere('employer_id', '0')
            ->get(['id', 'label', 'value_type', 'options', 'created_at', 'updated_at'])
            ->map(function ($preference) {
                // Decode the JSON options back to an array
                $preference->options = json_decode($preference->options, true);
                return $preference;
            });
    
        // Check if preferences exist for the employer
        if ($preferences->isEmpty()) {
            return response([
                'response' => 'No preferences found for the specified employer.',
                'status' => 500
            ], 200);
        }
    
        // Return preferences
        return response([
            'response' => $preferences,
            'message' => 'Preferences retrieved successfully.',
            'status' => 200
        ], 200);
    }
    
    public function get_direct_application_form_data(Request $request)
    {
        $employerId = $request->employer_id;
    
        // Validate the employer ID
        if (!$employerId) {
            return response([
                'response' => 'Employer ID is required.',
                'status' => 500
            ], 200);
        }
    
        // Fetch preferences matching the employer ID
        $preferences = DirectApplicationForm::where('employer_id', $employerId)
            ->get(['id', 'label', 'value_type', 'options', 'created_at', 'updated_at'])
            ->map(function ($preference) {
                // Decode the JSON options back to an array
                $preference->options = json_decode($preference->options, true);
                return $preference;
            });
    
        // Check if preferences exist for the employer
        if ($preferences->isEmpty()) {
            return response([
                'response' => 'No preferences found for the specified employer.',
                'status' => 500
            ], 200);
        }
    
        // Return preferences
        return response([
            'response' => $preferences,
            'message' => 'Preferences retrieved successfully.',
            'status' => 200
        ], 200);
    }
    
    
    public function setup_direct_application_form_setting(Request $request)
    {
        $employerId = $request->employer_id;
    
        // Validation for input data
        $validator = Validator::make($request->all(), [
            // 'preferences' => 'sometimes|array',
            // 'preferences.*.id' => 'nullable|integer|exists:tbl_preferences,id',
            // 'preferences.*.question' => 'required_with:preferences|string',
            // 'preferences.*.value_type' => 'required_with:preferences|string',
            // 'preferences.*.options' => 'required_with:preferences|array',
        ]);
    
        if ($validator->fails()) {
            return response(['response' => $validator->errors(), 'status' => 500], 200);
        }
    
        // Handle preferences input
        if ($request->has('preferences')) {
            $preferences = $request->input('preferences');
    
            foreach ($preferences as $preference) {
                if (isset($preference['id'])) {
                    // Update existing preference
                    DirectApplicationForm::where('id', $preference['id'])
                        ->update([
                            'label' => $preference['label'],
                            'value_type' => $preference['value_type'],
                            'options' => json_encode($preference['options']),
                        ]);
                } else {
                    // Insert new preference
                    DirectApplicationForm::create([
                        'employer_id' => $employerId,
                        'label' => $preference['label'],
                        'value_type' => $preference['value_type'],
                        'options' => json_encode($preference['options']),
                    ]);
                }
            }
        }
    
        // Fetch updated preferences for the employer
        $existingPreferences = DirectApplicationForm::where('employer_id', $employerId)
            ->get(['id', 'label', 'value_type', 'options'])
            ->map(function ($preference) {
                // Decode options back to an array for response
                $preference->options = json_decode($preference->options, true);
                return $preference;
            });
    
        return response([
            'response' => [
                'existing_preferences' => $existingPreferences,
            ],
            'message' => 'Preferences processed successfully.',
            'status' => 200,
        ], 200);
    }
    
    
    // public function saveDirectApplicationFormData(Request $request)
    // {
    //     // Validate the incoming request data
    //     $validatedData = $request->validate([
    //         'employer_id' => 'required|exists:employers,id', // Assuming you have an employers table
    //         // Add other validation rules for the fields you expect in the request
    //     ]);
    
    //     // Encode the request data to JSON
    //     $preferenceData = json_encode($request->all());
    
    //     try {
    //         // Create a new DirectApplication record
    //         $updated = CandidateJobApply::create([
    //             'employer_id' => $validatedData['employer_id'],
    //             'first_name' => $request->input('First_Name'),
    //             'middle_name' => $request->input('Middle_Name'),
    //             'last_name' => $request->input('Last_Name'),
    //             'contact_number' => $request->input('Mobile_Number'),
    //             'email' => $request->input('Email'),
    //             'candidate_general_application_data' => $preferenceData
    //         ]);
    
    //         // Check if the record was created successfully
    //         if ($updated) {
                
    //             $emailTemplate = EmailTemplate::where('id', 11)->first();
                
    //             $first_name = $request->input('First_Name');
    //             $middle_name = $request->input('Middle_Name');
    //             $last_name = $request->input('Last_Name');
                
    //             $candidateName = $first_name . ' ' . $middle_name . ' ' . $last_name;
                
    //             $candidateEmail = $request->input('Email');
                
    //             $companyName = Employer::where('id', $validatedData['employer_id'])->value('company_name');
                
    //             $employerEmail = Employer::where('id', $validatedData['employer_id'])->value('email_address');
                
    //             $toRepArray = ['[!candidate_name!]', '[!company_name!]', '[!employer_email!]'];
    //             $fromRepArray = [$candidateName, $companyName, $employerEmail]; 
    //             $emailSubject = str_replace($toRepArray, $fromRepArray, $emailTemplate->subject);
    //             $emailBody = str_replace($toRepArray, $fromRepArray, $emailTemplate->template);
                
    //             $logo = Employer::where('id', $validatedData['employer_id'])->value('company_logo');
                        
    //             if(!empty($logo)){
    //                 $logoPath = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $logo;
    //             } else{
    //                 $logoPath = LOGO_PATH;
    //             }
            
    //             // Send the email
    //             try {
    //                 Mail::to($candidateEmail)->send(new SendMail($emailBody, $emailSubject, $logoPath));
    //             } catch (\Exception $e) {
    //                 return response()->json(['error' => 'Failed to send email.', 'message' => $e->getMessage()], 500);
    //             }
                
    //             return response()->json([
    //                 'response' => null,
    //                 'message' => 'Application submitted successfully.',
    //                 'status' => 200
    //             ]);
    //         } else {
    //             return response()->json([
    //                 'response' => null,
    //                 'message' => 'Failed to save application.',
    //                 'status' => 500
    //             ]);
    //         }
    //     } catch (\Exception $e) {
    //         // Handle any exceptions that may occur
    //         return response()->json([
    //             'response' => null,
    //             'message' => 'An error occurred: ' . $e->getMessage(),
    //             'status' => 500
    //         ]);
    //     }
    // }
    
    public function saveDirectApplicationFormData(Request $request)
{
    // Validate the incoming request data
    $validatedData = $request->validate([
        'employer_id' => 'required|exists:employers,id', // Assuming you have an employers table
        // Add other validation rules for the fields you expect in the request
    ]);

    // Prepare the preference data, excluding certain fields
    $fieldsToExclude = ['First_Name', 'Middle_Name', 'Last_Name', 'Mobile_Number', 'Email'];
    $preferenceData = json_encode($request->except($fieldsToExclude));
    
    $jobDetails = Job::where('employer_id', $validatedData['employer_id'])->where('general_job_status', '1')->first();

    try {
        // Create a new DirectApplication record
        $updated = CandidateJobApply::insertGetId([
            'employer_id' => $validatedData['employer_id'],
            'first_name' => $request->input('First_Name'),
            'middle_name' => $request->input('Middle_Name'),
            'last_name' => $request->input('Last_Name'),
            'contact_number' => $request->input('Mobile_Number'),
            'email' => $request->input('Email'),
            'candidate_general_application_data' => $preferenceData,
            'job_form_id' => $jobDetails->id,
        ]);
        
        
        
        if (!empty($jobDetails->process_order_ids)) {
                    $interviewProcessIds = explode(',', $jobDetails->process_order_ids);
                    
                    if(!empty($interviewProcessIds)){
                        foreach ($interviewProcessIds as $processId) {
                            DB::table('candidate_interview_journeys')->insert([
                                'candidate_id' => $updated,
                                'job_id' => $jobDetails->id,
                                'process_id' => $processId,
                                'completion_status' => '0',
                            ]);
                        }
                    }
                    
                }

        // Check if the record was created successfully
        if ($updated) {
            $emailTemplate = EmailTemplate::where('id', 11)->first();

            $first_name = $request->input('First_Name');
            $middle_name = $request->input('Middle_Name');
            $last_name = $request->input('Last_Name');

            $candidateName = $first_name . ' ' . $middle_name . ' ' . $last_name;

            $candidateEmail = $request->input('Email');

            $companyName = Employer::where('id', $validatedData['employer_id'])->value('company_name');

            $employerEmail = Employer::where('id', $validatedData['employer_id'])->value('email_address');

            $toRepArray = ['[!candidate_name!]', '[!company_name!]', '[!employer_email!]'];
            $fromRepArray = [$candidateName, $companyName, $employerEmail];
            $emailSubject = str_replace($toRepArray, $fromRepArray, $emailTemplate->subject);
            $emailBody = str_replace($toRepArray, $fromRepArray, $emailTemplate->template);

            $logo = Employer::where('id', $validatedData['employer_id'])->value('company_logo');

            if(!empty($logo)){
                $logoPath = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $logo;
            } else{
                $logoPath = LOGO_PATH;
            }

            // Send the email
            try {
                Mail::to($candidateEmail)->send(new SendMail($emailBody, $emailSubject, $logoPath));
            } catch (\Exception $e) {
                return response()->json(['error' => 'Failed to send email.', 'message' => $e->getMessage()], 500);
            }

            return response()->json([
                'response' => null,
                'message' => 'Application submitted successfully.',
                'status' => 200
            ]);
        } else {
            return response()->json([
                'response' => null,
                'message' => 'Failed to save application.',
                'status' => 500
            ]);
        }
    } catch (\Exception $e) {
        // Handle any exceptions that may occur
        return response()->json([
            'response' => null,
            'message' => 'An error occurred: ' . $e->getMessage(),
            'status' => 500
        ]);
    }
}



    public function removeDirectApplicationFormSection(Request $request){
        $employerId = $request->employer_id;
        $id = $request->id;
    
        $preference = DirectApplicationForm::where('employer_id', $employerId)->where('id', $id)->first();
    
        if ($preference) {
            $preference->delete();
            return response([
                'response' => '',
                'message' => 'Preference section removed successfully.',
                'status' => 200,
            ], 200);
        }
    
        return response([
            'response' => '',
            'message' => 'Preference not found or already removed.',
            'status' => 500,
        ], 200);
        
    }
}
