<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Models\Process;
use App\Models\StatusAttributes;
use App\Models\Employer;
use App\Models\Job;
use App\Models\GeneralSetting;
use App\Models\DirectApplicationForm;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use App\Models\Staff;
use Illuminate\Support\Facades\Storage;


class AdminController extends Controller
{
    public function admin_editProfile(Request $request)
    {
        $userId = Auth::user()->id;
        $userType = $request->user_type;
        $user = "";
    
        if ($userType === 'admin') {
            $user = Admin::where('id', $userId)->where('user_type', $userType)->first();
        } elseif ($userType === 'employer') {
            $user = Employer::where('id', $userId)->where('user_type', $userType)->first();
        } else {
            $user = Staff::where('id', $userId)->where('user_type', $userType)->first();
        }
    
        if (!$user) {
            return response([
                'status' => 404,
                'message' => 'User not found',
                'response' => []
            ], 200);
        }
        
        $input = $request->except('user_type');
    
        if (!$input) {
            $profile = '';
            if ($userType === 'admin') {
                $profile = [
                    'id' => $user->id,
                    'name' => $user->username,
                    'email' => $user->email_address,
                    'profile_picture' => $user->profile_image,
                    'website_logo' => $user->company_logo,
                ];
            } elseif ($userType === 'employer') {
                $profile = [
                    'id' => $user->id,
                    'username' => $user->username,
                    'email' => $user->email_address,
                    'profile_picture' => EMPLOYER_PROFILE_PICTURE_DISPLAY_PATH . $user->profile_image,
                    'website_logo' => EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $user->company_logo,
                ];
            } else { // staff
                $profile = [
                    'id' => $user->id,
                    'username' => $user->username,
                    'email' => $user->email_address,
                    'profile_picture' => STAFF_PROFILE_PICTURE_DISPLAY_PATH . $user->profile_image,
                ];
            }
            
            return response([
                'status' => 200,
                'message' => 'Profile fetched successfully',
                'response' => $profile
            ], 200);
        }
        else{

            if ($userType === 'admin') {
                $request->validate([
                    'username' => 'sometimes|string|max:255',
                    'email' => 'sometimes|email|unique:admins,email,'.$user->id,
                    'password' => 'nullable|min:6|confirmed',
                    'profile_picture' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
                    'website_logo' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
                ]);
    
                if ($request->filled('username')) $user->username = $request->username;
                if ($request->filled('email')) $user->email = $request->email;
                if ($request->filled('password')) $user->password = bcrypt($request->password);
    
                if ($request->hasFile('profile_picture')) {
                    $path = $request->file('profile_picture')->store('profile_pics', 'public');
                    $user->profile_pic = $path;  // field name in Admins table
                }
    
                if ($request->hasFile('website_logo')) {
                    $path = $request->file('website_logo')->store('logos', 'public');
                    $user->site_logo = $path; // field name in Admins table
                }
            }
    
            elseif ($userType === 'employer') {
    $request->validate([
        'username' => 'sometimes|string|max:255',
        'email' => 'sometimes|email|unique:employers,email_address,'.$user->id,
        'password' => 'nullable|min:6|confirmed',
        'profile_picture' => [
            'nullable',
            'string',
            function ($attribute, $value, $fail) {
                if (preg_match('/^data:image\/(jpg|jpeg|png);base64,/', $value)) {
                    $base64String = explode(',', $value)[1];
                    $decoded = base64_decode($base64String, true);
                    if ($decoded === false) {
                        $fail('The profile picture is not a valid base64-encoded image.');
                    }
                    $sizeInBytes = strlen($decoded);
                    if ($sizeInBytes > 2 * 1024 * 1024) {
                        $fail('The profile picture must not exceed 2MB.');
                    }
                    $image = @imagecreatefromstring($decoded);
                    if ($image === false) {
                        $fail('The profile picture must be a valid image (jpg, jpeg, or png).');
                    }
                    imagedestroy($image);
                } else {
                    $fail('The profile picture must be a base64-encoded jpg, jpeg, or png image.');
                }
            },
        ],
        'website_logo' => [
            'nullable',
            'string',
            function ($attribute, $value, $fail) {
                if (preg_match('/^data:image\/(jpg|jpeg|png);base64,/', $value)) {
                    $base64String = explode(',', $value)[1];
                    $decoded = base64_decode($base64String, true);
                    if ($decoded === false) {
                        $fail('The website logo is not a valid base64-encoded image.');
                    }
                    $sizeInBytes = strlen($decoded);
                    if ($sizeInBytes > 2 * 1024 * 1024) {
                        $fail('The website logo must not exceed 2MB.');
                    }
                    $image = @imagecreatefromstring($decoded);
                    if ($image === false) {
                        $fail('The website logo must be a valid image (jpg, jpeg, or png).');
                    }
                    imagedestroy($image);
                } else {
                    $fail('The website logo must be a base64-encoded jpg, jpeg, or png image.');
                }
            },
        ],
    ]);

    if ($request->filled('username')) $user->username = $request->username;
    if ($request->filled('email')) $user->email_address = $request->email;
    if ($request->filled('password')) $user->password = bcrypt($request->password);

    if ($request->filled('profile_picture')) {
        $file = explode(";base64,", $request->profile_picture);
        $image_type_pieces = explode("image/", $file[0]);
        $image_type = $image_type_pieces[1];
        $originalName = 'profile_' . time() . '.' . $image_type;
        $decoded_string = base64_decode($file[1]);
        $filePath = Storage::disk('public')->put('uploads/employer/profile_picture/' . $originalName, $decoded_string);
        $user->profile_image = $originalName;
    }

    if ($request->filled('website_logo')) {
        $file = explode(";base64,", $request->website_logo);
        $image_type_pieces = explode("image/", $file[0]);
        $image_type = $image_type_pieces[1];
        $originalName = 'logo_' . time() . '.' . $image_type;
        $decoded_string = base64_decode($file[1]);
        $filePath = Storage::disk('public')->put('uploads/employer/company_logo/' . $originalName, $decoded_string);
        $user->company_logo = $originalName;
    }
}
    
            elseif ($userType === 'staff') {
                $request->validate([
                    'username' => 'sometimes|string|max:255',
                    'email' => 'sometimes|email|unique:staff,staff_email,'.$user->id,
                    'password' => 'nullable|min:6|confirmed',
                    'profile_picture' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
                ]);
    
                if ($request->filled('username')) $user->username = $request->username;
                if ($request->filled('email')) $user->email_address = $request->email;
                if ($request->filled('password')) $user->password = bcrypt($request->password);
    
                if ($request->hasFile('profile_picture')) {
                    
                    $file = explode(";base64,", $request->profile_picture);
                    $image_type_pieces = explode("image/", $file[0]);
                    $image_type = $image_type_pieces[1]; // Get the image type (e.g., png, jpeg)
                    
                    // Generate a unique filename for the logo
                    $originalName = 'logo_' . time() . '.' . $image_type;  // Using the image type to set the file extension
                    
                    // Decode the base64 string into binary data
                    $decoded_string = base64_decode($file[1]);
                    
                    // Create a temporary file to store the decoded image
                    $tempFile = tmpfile();
                    fwrite($tempFile, $decoded_string);
                    fseek($tempFile, 0);
                    
                    // Use Laravel's storage to store the file in the public disk
                    $filePath = Storage::disk('public')->put('uploads/staff/profile_picture/' . $originalName, $tempFile);
                    
                    // Get the filename after it's stored (use str_replace to clean up the path if needed)
                    $fileName = str_replace('uploads/staff/profile_picture/', '', $filePath);
                    
                    // Update the employer's profile with the new logo filename
                    $user->profile_image = $originalName;
                    
                }
                
            }
    
            $user->save();
    
            return response()->json([
                'status' => 200,
                'message' => 'Profile updated successfully',
                'response' => $user
            ], 200);
        }
    
        return response()->json([
            'status' => 405,
            'message' => 'Method not allowed',
            'response' => []
        ], 405);
    }

    
    public function admin_changeusername(Request $request) {
        $user = Auth::user();
        $userId = $user->id;
    
        $adminDetail = Admin::find($userId);
        $employerDetail = Employer::find($userId);
        $staffDetail = Staff::find($userId);
    
        $msgString = "";
    
        if(!empty($request->all())){
            if(empty($request->new_username)){
                $msgString = "Username cannot be empty";
            } elseif(
                (isset($adminDetail) && $request->new_username == $adminDetail->username) ||
                (isset($employerDetail) && $request->new_username == $employerDetail->username) ||
                (isset($staffDetail) && $request->new_username == $staffDetail->username)
            ){
                $msgString = "Username cannot be same as current username";
            }
    
            if(empty($request->confirm_username)){
                $msgString = "Confirm username cannot be empty";
            }
    
            if(trim($request->new_username) != trim($request->confirm_username)){
                $msgString = "Username does not match with confirm username";
            }
    
            if(trim($request->new_username) != trim($request->old_username)){
                $admin_count = Admin::where('username', $request->new_username)->count();
    
                if($admin_count > 0) {
                    $msgString = "Username already exists";
                }
            }
    
            if(isset($msgString) && $msgString != "") {
                return Response(['response' => "", 'message' => $msgString, 'status' => 500], 200);
            } else {
                try {
                    if(!empty($adminDetail)){
                        Admin::where('id', $userId)->update(['username' => $request->new_username]);
                    } elseif(!empty($employerDetail)){
                        Employer::where('id', $userId)->update(['username' => $request->new_username]);
                    } elseif(!empty($staffDetail)){
                        Staff::where('id', $userId)->update(['username' => $request->new_username]);
                    }
                    return Response(['response' => "Username updated successfully", 'message' => "Username changed successfully", 'status' => 200], 200);
                } catch(\Exception $e) {
                    return Response(['response' => 'There was an error while updating the details', 'message' => 'There was an error while updating the details', 'status' => 500], 200);
                }
            }
        }
    
        $data = [];
        if(!empty($adminDetail)){
            $data['username'] = $adminDetail->username;
        } elseif(!empty($employerDetail)){
            $data['username'] = $employerDetail->username;
        } elseif(!empty($staffDetail)){
            $data['username'] = $staffDetail->username;
        }
    
        return Response(['response' => $data, 'message' => '', 'status' => 200], 200);
    }

    
    
   public function admin_changepassword(Request $request)
    {
        // Extract the user ID from the request
        $userId = $request->input('userId');
        $userDetail = null;
    
        // Find the user in Admin, Employer, or Staff
        if ($adminDetail = Admin::find($userId)) {
            $userDetail = $adminDetail;
        } elseif ($employerDetail = Employer::find($userId)) {
            $userDetail = $employerDetail;
        } elseif ($staffDetail = Staff::find($userId)) {
            $userDetail = $staffDetail;
        }
    
        if (!$userDetail) {
            return response()->json(['response' => '', 'message' => 'User not found', 'status' => 404], 200);
        }
    
        $input = $request->all();
    
        if (!empty($input)) {
            // Define validation rules
            $rules = [
                'old_password' => 'required',
                'new_password' => 'required|different:old_password',
                'confirm_password' => 'required|same:new_password'
            ];
    
            $validator = Validator::make($input, $rules);
            $validator->setAttributeNames([
                'old_password' => 'Old Password',
                'new_password' => 'New Password',
                'confirm_password' => 'Confirm Password'
            ]);
    
            if ($validator->fails()) {
                $msg = $this->validatersErrorString($validator->errors());
                return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
            } else {
                // Verify old password
                if (Hash::check($request->old_password, $userDetail->password)) {
                    try {
                        // Update the password
                        $userDetail->password = Hash::make($request->new_password);
                        $userDetail->save();
    
                        return response()->json(['response' => "Password updated successfully", 'message' => "Password changed successfully", 'status' => 200], 200);
                    } catch (\Exception $e) {
                        return response()->json(['response' => 'There was an error while updating the password', 'message' => 'There was an error while updating the password', 'status' => 500], 200);
                    }
                } else {
                    return response()->json(['response' => '', 'message' => 'Old password is incorrect', 'status' => 500], 200);
                }
            }
        } else {
            return response()->json(['response' => '', 'message' => 'Invalid input', 'status' => 400], 200);
        }
    }
    

    public function admin_changeemail(Request $request) {
        // $userId = $request->userId;
        // $userId = "1";
        $userId = Auth::user()->id;
        $adminDetail = Admin::where('id', $userId)->first();
        $employerDetail = Employer::where('id', $userId)->first();
        $staffDetail = Staff::where('id', $userId)->first();

        $msgString = "";

        $input = $request->all();
        
        if(!empty($input)) {
            $rules = array(
                'old_email' => 'required | email | different:new_email',
                'new_email' => 'required | email | different:old_email',
                'confirm_email' => 'required | email | same:new_email'
            );
            $validator = Validator::make($input, $rules);

            $validator->setAttributeNames([
                'old_email' => 'Old Email',
                'new_email' => 'New Email',
                'confirm_email' => 'Confirm Email'
            ]);

            if($validator->fails()) {
                $errors = $validator->errors();

                foreach($errors->all() as $error) {
                    $msgString .= "" . $error . "\n";
                }
                return Response(['response' => '', 'message' => $validator->messages(), 'status' => 500], 200);
            }else{
                
                try {
                    if(!empty($adminDetail)){
                        Admin::where('id', $userId)->update(['email' => $request->new_email]);
                    } elseif(!empty($employerDetail)){
                        Employer::where('id', $userId)->update(['email_address' => $request->new_email]);
                    } elseif(!empty($staffDetail)){
                        Staff::where('id', $userId)->update(['email_address' => $request->new_email]);
                    }
                    return Response(['response' => "Email updated successfully", 'message' => "Email changed successfully", 'status' => 200], 200);
                } catch(\Exception $e) {
                    return Response(['response' => 'There was an error while updating the details', 'message' => 'There was an error while updating the details', 'status' => 500], 200);
                }
                
                // try {
                //     Admin::where('id',$userId) ->update([
                //         'email' => $request->new_email
                //     ]);
                //     return Response(['response' => "Email updated successfully", 'message' => "Email changed successfully", 'status' => 200], 200);
                // }catch(\Exception $e){
                //     return Response(['response' => 'There was an error while updating the details', 'message' => 'There was an error while updating the details', 'status' => 500], 200);
                // }
            }
        } 
        // $data['old_email'] = $adminDetail->email;
        // return Response(['response' => $data, 'message' => '', 'status' => 200], 200);
    

        $data = [];
        if (!empty($adminDetail)) {
            $data['old_email'] = $adminDetail->email;
        } elseif (!empty($employerDetail)) {
            $data['old_email'] = $employerDetail->email_address;
        } elseif (!empty($staffDetail)) {
            $data['old_email'] = $staffDetail->email_address;
        }

    return Response(['response' => $data, 'message' => '', 'status' => 200], 200);
        
    }
    
    public function admin_changeWebsiteLogo(Request $request) {
        $currentUser = Auth::user()->id;
        $AdminCheck = Admin::where('id', $currentUser)->first();
        $EmployerCheck = Employer::where('id', $currentUser)->first();
        $StaffCheck = Staff::where('id', $currentUser)->first();
        $oldLogo = Admin::where('id',$currentUser)->select('company_logo')->first();
        
        
        $staffDetail = Staff::find($currentUser);
        
        if(!empty($staffDetail)){
            
            $adminData = $staffDetail;
                
                $accessData = isset($adminData->roles) ? unserialize($adminData->roles) : [];
            
                    global $subadminAccess;
                    $accessControlArray = $subadminAccess;
            
                    if (!is_array($accessControlArray)) {
                        return response()->json(['message' => 'Access control data is missing or invalid', 'status' => 500], 500);
                    }
            
                    $accessArray = [];
                    foreach ($accessControlArray as $key => $ac) {
                        $accessArray[$key] = $ac; // Start with the original sub-array
            
                        // Override with $accessData if available
                        if (isset($accessData[$key])) {
                            foreach ($accessData[$key] as $accessKey => $accessValue) {
                                $accessArray[$key][$accessKey] = $accessValue;
                            }
                        }
                    }
                
                
                if($accessArray['10']['Change_Website_Logo'] == 0){
                    return Response(['response' => 'You are not allowed to access this page.', 'message' => 'You are not allowed to access this page.', 'status' => 500], 200);
                }
        }
        

        $data;
        
        if(!empty($AdminCheck)){
            if(!empty($request->all())){

                if($request->logo){
                    $file = explode( ";base64,", $request->logo);
                    $image_type_pieces = explode( "image/", $file[0] );
                    $image_type = $image_type_pieces[1];
                    $originalName = 'company-logo.png';
                    $decoded_string = base64_decode($file[1]);
                    file_put_contents(EMPLOYER_COMPANY_LOGO_UPLOAD_PATH.$originalName, $decoded_string);
    
                    $admin = Admin::find($currentUser);
                    $admin->company_logo = $originalName;
                    $admin->save();
                    
                    $data['logo_path'] = PROFILE_PICTURE_PATH;
                    $data['logo'] = '';
                }else{
                    return Response(['response' => '' , 'message'=> 'Company logo required', 'status'=>500],200);
                }
                
            }else{
                $data['logo_path'] = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH.$employerProfilePicture;
                $data['logo'] = '';
    
            }
        } else if(!empty($EmployerCheck)){
            
            $employerProfilePicture = Employer::where('id', $currentUser)->value('company_logo');
            $companyLogoStatus = Employer::where('id', $currentUser)->value('company_logo_status');
            
            if(!empty($request->all())){
                if($request->logo){
                    
                    
                    // Extract the base64-encoded image data from the request
                    $file = explode(";base64,", $request->logo);
                    $image_type_pieces = explode("image/", $file[0]);
                    $image_type = $image_type_pieces[1]; // Get the image type (e.g., png, jpeg)
                    
                    // Generate a unique filename for the logo
                    $originalName = 'logo_' . time() . '.' . $image_type;  // Using the image type to set the file extension
                    
                    // Decode the base64 string into binary data
                    $decoded_string = base64_decode($file[1]);
                    
                    // Create a temporary file to store the decoded image
                    $tempFile = tmpfile();
                    fwrite($tempFile, $decoded_string);
                    fseek($tempFile, 0);
                    
                    // Use Laravel's storage to store the file in the public disk
                    $filePath = Storage::disk('public')->put('uploads/employer/company_logo/' . $originalName, $tempFile);
                    
                    // Get the filename after it's stored (use str_replace to clean up the path if needed)
                    $fileName = str_replace('uploads/employer/company_logo/', '', $filePath);
                    
                    // Update the employer's profile with the new logo filename
                    $employer = Employer::find($currentUser);
                    $employer->company_logo = $originalName;
                    $employer->company_logo_status = $request->showOnHomepage;
                    $employer->save();
                    
                    // Prepare the response data
                    $data['logo_path'] = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $originalName;
                    $data['logo'] = $originalName;  // You can send the file name or any other relevant info
                    $data['showOnHomepage'] = $companyLogoStatus;

                }else{
                    return Response(['response' => '' , 'message'=> 'Company logo required', 'status'=>500],200);
                }
                
            }else{
                if(!empty($employerProfilePicture)){
                    $data['logo_path'] = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH.$employerProfilePicture;
                    $data['logo'] = '';
                }else{
                    $data['logo_path'] = "";
                    $data['logo'] = '';
                }
                $data['showOnHomepage'] = $companyLogoStatus;
            }
        } else if(!empty($StaffCheck)) {
            
            $employerId = Staff::where('id', $currentUser)->value('employer_id');
            
            $employerProfilePicture = Employer::where('id', $employerId)->value('company_logo');
            $companyLogoStatus = Employer::where('id', $employerId)->value('company_logo_status');
            
            if(!empty($request->all())){
                if($request->logo){
                    
                    
                    // Extract the base64-encoded image data from the request
                    $file = explode(";base64,", $request->logo);
                    $image_type_pieces = explode("image/", $file[0]);
                    $image_type = $image_type_pieces[1]; // Get the image type (e.g., png, jpeg)
                    
                    // Generate a unique filename for the logo
                    $originalName = 'logo_' . time() . '.' . $image_type;  // Using the image type to set the file extension
                    
                    // Decode the base64 string into binary data
                    $decoded_string = base64_decode($file[1]);
                    
                    // Create a temporary file to store the decoded image
                    $tempFile = tmpfile();
                    fwrite($tempFile, $decoded_string);
                    fseek($tempFile, 0);
                    
                    // Use Laravel's storage to store the file in the public disk
                    $filePath = Storage::disk('public')->put('uploads/employer/company_logo/' . $originalName, $tempFile);
                    
                    // Get the filename after it's stored (use str_replace to clean up the path if needed)
                    $fileName = str_replace('uploads/employer/company_logo/', '', $filePath);
                    
                    // Update the employer's profile with the new logo filename
                    $employer = Employer::find($employerId);
                    $employer->company_logo = $originalName;
                    $employer->company_logo_status = $request->showOnHomepage;
                    $employer->save();
                    
                    // Prepare the response data
                    $data['logo_path'] = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $originalName;
                    $data['logo'] = $originalName;  // You can send the file name or any other relevant info
                    $data['showOnHomepage'] = $companyLogoStatus;

                }else{
                    return Response(['response' => '' , 'message'=> 'Company logo required', 'status'=>500],200);
                }
                
            }else{
                if(!empty($employerProfilePicture)){
                    $data['logo_path'] = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH.$employerProfilePicture;
                    $data['logo'] = '';
                }else{
                    $data['logo_path'] = "";
                    $data['logo'] = '';
                }
                $data['showOnHomepage'] = $companyLogoStatus;
            }
            
            
            
        } else{
            return Response(['response'=>"" , 'message'=>'No user found' , 'status' => 200 ],200);
        }

        return Response(['response'=>$data , 'message'=>'success' , 'status' => 200 ],200);
    }
    
    public function admin_changeProfilePicture(Request $request) {
        
        $currentUser = Auth::user()->id;
        $AdminCheck = Admin::where('id', $currentUser)->first();
        $EmployerCheck = Employer::where('id', $currentUser)->first();
        $StaffCheck = Staff::where('id', $currentUser)->first();
        $oldLogo = Admin::where('id',$currentUser)->select('profile_picture')->first();
        $employerProfilePicture = Employer::where('id', $currentUser)->value('profile_image');
        $staffProfilePicture = STaff::where('id', $currentUser)->value('profile_image');

        $data;
        
        if(!empty($AdminCheck)){
            if(!empty($request->all())){

                if($request->logo){
                    $file = explode( ";base64,", $request->logo);
                    $image_type_pieces = explode( "image/", $file[0] );
                    $image_type = $image_type_pieces[1];
                    $originalName = 'logo.png';
                    $decoded_string = base64_decode($file[1]);
                    file_put_contents(EMPLOYER_PROFILE_PICTURE_UPLOAD_PATH.$originalName, $decoded_string);
    
                   
    
                    $admin = Admin::find($currentUser);
                    $admin->profile_picture = $originalName;
                    $admin->save();
                    
                    $data['logo_path'] = PROFILE_PICTURE_PATH;
                    $data['logo'] = '';
                }else{
                    return Response(['response' => '' , 'message'=> 'Profile picture required', 'status'=>500],200);
                }
                
            }else{
                $data['logo_path'] = EMPLOYER_PROFILE_PICTURE_DISPLAY_PATH.$employerProfilePicture;
                $data['logo'] = '';
    
            }
        } else if(!empty($EmployerCheck)){
            if(!empty($request->all())){
                if($request->logo){
                    
                    
                    // Extract the base64-encoded image data from the request
                    $file = explode(";base64,", $request->logo);
                    $image_type_pieces = explode("image/", $file[0]);
                    $image_type = $image_type_pieces[1]; // Get the image type (e.g., png, jpeg)
                    
                    // Generate a unique filename for the logo
                    $originalName = 'logo_' . time() . '.' . $image_type;  // Using the image type to set the file extension
                    
                    // Decode the base64 string into binary data
                    $decoded_string = base64_decode($file[1]);
                    
                    // Create a temporary file to store the decoded image
                    $tempFile = tmpfile();
                    fwrite($tempFile, $decoded_string);
                    fseek($tempFile, 0);
                    
                    // Use Laravel's storage to store the file in the public disk
                    $filePath = Storage::disk('public')->put('uploads/employer/profile_picture/' . $originalName, $tempFile);
                    
                    // Get the filename after it's stored (use str_replace to clean up the path if needed)
                    $fileName = str_replace('uploads/employer/profile_picture/', '', $filePath);
                    
                    // Update the employer's profile with the new logo filename
                    $employer = Employer::find($currentUser);
                    $employer->profile_image = $originalName;
                    $employer->save();
                    
                    // Prepare the response data
                    $data['logo_path'] = EMPLOYER_PROFILE_PICTURE_DISPLAY_PATH . $originalName;
                    $data['logo'] = $originalName;  // You can send the file name or any other relevant info

                }else{
                    return Response(['response' => '' , 'message'=> 'Profile picture required', 'status'=>500],200);
                }
                
            }else{
                if(!empty($employerProfilePicture)){
                    $data['logo_path'] = EMPLOYER_PROFILE_PICTURE_DISPLAY_PATH.$employerProfilePicture;
                    $data['logo'] = '';
                }else{
                    $data['logo_path'] = "";
                    $data['logo'] = '';
                }
            }
        } else if(!empty($StaffCheck)){
            if(!empty($request->all())){
                if($request->logo){
                    
                    $file = explode(";base64,", $request->logo);
                    $image_type_pieces = explode("image/", $file[0]);
                    $image_type = $image_type_pieces[1]; // Get the image type (e.g., png, jpeg)
                    
                    // Generate a unique filename for the logo
                    $originalName = 'logo_' . time() . '.' . $image_type;  // Using the image type to set the file extension
                    
                    // Decode the base64 string into binary data
                    $decoded_string = base64_decode($file[1]);
                    
                    // Create a temporary file to store the decoded image
                    $tempFile = tmpfile();
                    fwrite($tempFile, $decoded_string);
                    fseek($tempFile, 0);
                    
                    // Use Laravel's storage to store the file in the public disk
                    $filePath = Storage::disk('public')->put('uploads/staff/profile_picture/' . $originalName, $tempFile);
                    
                    // Get the filename after it's stored (use str_replace to clean up the path if needed)
                    $fileName = str_replace('uploads/staff/profile_picture/', '', $filePath);
                    
                    // Update the employer's profile with the new logo filename
                    $staff = Staff::find($currentUser);
                    $staff->profile_image = $originalName;
                    $staff->save();
                    
                    // Prepare the response data
                    $data['logo_path'] = STAFF_PROFILE_PICTURE_DISPLAY_PATH . $originalName;
                    $data['logo'] = $originalName;  // You can send the file name or any other relevant info
                }else{
                    return Response(['response' => '' , 'message'=> 'Profile picture required', 'status'=>500],200);
                }
                
            }else{
                
                if(!empty($staffProfilePicture)){
                    $data['logo_path'] = STAFF_PROFILE_PICTURE_DISPLAY_PATH.$staffProfilePicture;
                    $data['logo'] = '';
                }else{
                    $data['logo_path'] = "";
                    $data['logo'] = '';
                }
                
    
            }
        }else{
            return Response(['response'=>"" , 'message'=>'No user found' , 'status' => 200 ],200);
        }

        return Response(['response'=>$data , 'message'=>'success' , 'status' => 200 ],200);
    }
    
    public function admin_interviewProcesses(Request $request) {
        
        // $interviewProcesses = Process::orderBy('id','desc')->get();

        // $interviewProcessData = array();

        // foreach($interviewProcesses as $key => $value) {
        //     $interviewProcessData[$key]['interview_process_id'] = $value->id;
        //     $interviewProcessData[$key]['interview_process_name'] = $value->process_name;
        //     $interviewProcessData[$key]['status'] = $value->status;
        //     $interviewProcessData[$key]['slug'] = $value->slug;
        //     $interviewProcessData[$key]['position'] = $value->position;
        //     $interviewProcessData[$key]['round'] = $value->round;
        //     $interviewProcessData[$key]['created'] = format_date($value->created_at);
        // }
        // return Response(['response'=>$interviewProcessData , 'message'=>'success' , 'status' => 200 ],200);
        
        $currentUser = Auth::user()->id;
        $currentUserCheck = Admin::where('id', $currentUser)->first();
        
        
        $staffDetail = Staff::find($currentUser);
        
        if(!empty($staffDetail)){
            
            $adminData = $staffDetail;
                
                $accessData = isset($adminData->roles) ? unserialize($adminData->roles) : [];
            
                    global $subadminAccess;
                    $accessControlArray = $subadminAccess;
            
                    if (!is_array($accessControlArray)) {
                        return response()->json(['message' => 'Access control data is missing or invalid', 'status' => 500], 500);
                    }
            
                    $accessArray = [];
                    foreach ($accessControlArray as $key => $ac) {
                        $accessArray[$key] = $ac; // Start with the original sub-array
            
                        // Override with $accessData if available
                        if (isset($accessData[$key])) {
                            foreach ($accessData[$key] as $accessKey => $accessValue) {
                                $accessArray[$key][$accessKey] = $accessValue;
                            }
                        }
                    }
                
                
                if($accessArray['11']['Module'] == 0){
                    return Response(['response' => 'You are not allowed to access this page.', 'message' => 'You are not allowed to access this page.', 'status' => 500], 200);
                }
        }
        
        
        // echo $currentUser;
        if (!empty($currentUserCheck)) {
            //echo "from Admin";

            $interviewProcesses = Process::orderBy('id', 'desc')->get();

            $interviewProcessData = array();
            foreach ($interviewProcesses as $key => $value) {

                $employerName = "System Generated";
                if ($value->employer_id != 0) {
                    $employerRecord = Employer::where('id', $value->employer_id)->first();
                    if (!empty($employerRecord)) {
                        $employerName = $employerRecord->first_name . " " . $employerRecord->last_name;
                    }
                }

            $interviewProcessData[$key]['interview_process_id'] = $value->id;
            $interviewProcessData[$key]['employer_id'] = $value->employer_id;
            $interviewProcessData[$key]['interview_process_name'] = $value->process_name;
            $interviewProcessData[$key]['status'] = $value->status;
            $interviewProcessData[$key]['slug'] = $value->slug;
            $interviewProcessData[$key]['position'] = $value->position;
            $interviewProcessData[$key]['round'] = $value->round;
            $interviewProcessData[$key]['created'] = format_date($value->created_at);
            }
        } else { 
            
            $interviewProcess = '';
            
            if($request->user_type == 'employer') {
                
                $interviewProcess = Process::where(function ($query) use ($currentUser) {
                    $query->where(function ($subQuery) {
                        $subQuery->where('employer_id', 0)
                                 ->where('status', 1); // For employer_id = 0 and staff_id = 0, ensure status is 1
                    })
                    ->orWhere(function ($subQuery) use ($currentUser) {
                        $subQuery->where('employer_id', $currentUser);
                    });
                })
                ->orderBy('id', 'desc')
                ->get();
                
            } else{
                
                $employerId = Staff::where('id', $currentUser)->value('employer_id');
                
                $interviewProcess = Process::where(function ($query) use ($currentUser, $employerId) {
                    $query->where(function ($subQuery) {
                        $subQuery->where('employer_id', 0)
                                 ->where('status', 1); // For employer_id = 0 and staff_id = 0, ensure status is 1
                    })
                    ->orWhere(function ($subQuery) use ($currentUser, $employerId) {
                        $subQuery->where(function ($innerQuery) use ($employerId, $currentUser) {
                            if (!is_null($employerId)) {
                                $innerQuery->where('employer_id', $employerId);
                            }
                            $innerQuery->orWhere('staff_id', $currentUser);
                        });
                    });
                })
                ->orderBy('id', 'desc')
                ->get();
                
            }
            
            

            $interviewProcessData = array();
            foreach ($interviewProcess as $key => $value) {
                $employerStatusArray = explode(',', $value->employer_status);
               

                // Check if the current user's ID is in the employer_status array
                $userPresent = in_array($currentUser, $employerStatusArray);

              
                $interviewProcessData[$key]['interview_process_id'] = $value->id;
            $interviewProcessData[$key]['employer_id'] = $value->employer_id;
            $interviewProcessData[$key]['interview_process_name'] = $value->process_name;
            $interviewProcessData[$key]['status'] = $userPresent ? 0 : 1; // Set status based on user presence
            $interviewProcessData[$key]['slug'] = $value->slug;
            $interviewProcessData[$key]['position'] = $value->position;
            $interviewProcessData[$key]['round'] = $value->round;
            $interviewProcessData[$key]['general_process_status'] = $value->general_process_status;
            $interviewProcessData[$key]['user_type'] = $value->user_type;
            $interviewProcessData[$key]['created'] = format_date($value->created_at);
            }
        }
return Response(['response'=>$interviewProcessData , 'message'=>'success' , 'status' => 200 ],200);
            
    }

    public function admin_addInterviewProcess(Request $request) {
        // $validator = Validator::make($request->all(), [
        //     'process_name' => 'required|unique:interview_processes,process_name',
        // ]);
        // $validator->setAttributeNames([
        //     'process_name' => 'Process Name',
        // ]);
        // if($validator->fails()){
        //     return Response(['response' => $validator->errors(), 'status' => 500], 200);
        // }
        // else {
            // $interviewProcess = Process::insert([
            //     'process_name' => $request->process_name,
            //     'round' => 1,
            //     'status' => 1,
            //     'position' => 1,
            //     'user_id' => 1,
            //     'slug' => createSlug('processes', $request->process_name),
            // ]);
            
             $slug = Str::slug($request->process_name);
            
            $currentUser = Auth::user()->id;
            $currentUserCheck = Admin::where('id', $currentUser)->first();
            
            
            $staffDetail = Staff::find($currentUser);
        
            if(!empty($staffDetail)){
                
                $adminData = $staffDetail;
                    
                    $accessData = isset($adminData->roles) ? unserialize($adminData->roles) : [];
                
                        global $subadminAccess;
                        $accessControlArray = $subadminAccess;
                
                        if (!is_array($accessControlArray)) {
                            return response()->json(['message' => 'Access control data is missing or invalid', 'status' => 500], 500);
                        }
                
                        $accessArray = [];
                        foreach ($accessControlArray as $key => $ac) {
                            $accessArray[$key] = $ac; // Start with the original sub-array
                
                            // Override with $accessData if available
                            if (isset($accessData[$key])) {
                                foreach ($accessData[$key] as $accessKey => $accessValue) {
                                    $accessArray[$key][$accessKey] = $accessValue;
                                }
                            }
                        }
                    
                    
                if($accessArray['11']['Add'] == 0){
                    return Response(['response' => 'You are not allowed to access this page.', 'message' => 'You are not allowed to access this page.', 'status' => 500], 200);
                }
            }
            
            
            $existingInterviewProcess = Process::where('employer_id', $currentUser)->where('process_name', $request->process_name)->exists();
            
            if($existingInterviewProcess){
                return Response(['response' => 'This process already exist.', 'message' => 'This process already exist.', 'status' => 500], 200);
            }
            
            $interviewProcess = '';
            
            $process = Process::where('employer_id', $currentUser)->where('general_process_status', '1')->first();
            
            // echo $currentUser;
            if (!empty($currentUserCheck)) {
                $interviewProcess = Process::insertGetId([
                    'process_name' => $request->process_name,
                    'slug' => $slug,
                    'status' => 1,
                    'user_id' => 1,
                    'position' => 1,
                    'employer_id' => 0,
                    'staff_id' => '',
                    'user_type' => 'admin'
                ]);
            } else {
                
                if($request->user_type == 'staff'){
                    
                    $employerId = Staff::where('id', $currentUser)->value('employer_id');
                    
                    $interviewProcess = Process::insertGetId([
                        'process_name' => $request->process_name,
                        'slug' => $slug,
                         'user_id' => 1,
                        'position' => 1,
                        'status' => 1,
                        'employer_id' => $employerId,
                        'general_process_status' => $request->process_type,
                        'staff_id' => $currentUser,
                        'user_type' => $request->user_type,
                    ]);
                    
                } else{
                    
                    $interviewProcess = Process::insertGetId([
                        'process_name' => $request->process_name,
                        'slug' => $slug,
                         'user_id' => 1,
                        'position' => 1,
                        'status' => 1,
                        'employer_id' => $currentUser,
                        'general_process_status' => $request->process_type,
                        'staff_id' => '0',
                        'user_type' => 'employer',
                    ]);
                
                }
                
                
            }
            
            
            if($request->user_type == 'staff'){
                
                $employerId = Staff::where('id', $currentUser)->value('employer_id');
                
                if(!empty($process)){
                    // that means general job exists
                    
                    $jobDetails = Job::where('employer_id', $employerId)
                    ->where('general_job_status', '1')
                    ->first();
                    
                    $processOrderIds = explode(',', $jobDetails->process_order_ids);
    
                    // Trim whitespace and filter out empty values
                    $processOrderIds = array_filter(array_map('trim', $processOrderIds));
                
                    // Add new ID (Replace `NEW_ID` with the actual value)
                    $newId = $interviewProcess; // Ensure this is a string
                    if (!in_array($newId, $processOrderIds)) {
                        $processOrderIds[] = $newId;
                    }
                
                    // Convert back to a string and update
                    $jobDetails->update(['process_order_ids' => implode(',', $processOrderIds)]);
                    
                } else{
                    //that means no general job exists. so we will add it.
                    Job::create([
                        'title' => 'General Job',
                        'employer_id' => $employerId,
                        'process_order_ids' => $interviewProcess,
                        'general_job_status' => 1,
                    ]);
                }
                
            } else{
                
                if(!empty($process)){
                    // that means general job exists
                    
                    $jobDetails = Job::where('employer_id', $currentUser)
                    ->where('general_job_status', '1')
                    ->first();
                    
                    $processOrderIds = explode(',', $jobDetails->process_order_ids);
    
                    // Trim whitespace and filter out empty values
                    $processOrderIds = array_filter(array_map('trim', $processOrderIds));
                
                    // Add new ID (Replace `NEW_ID` with the actual value)
                    $newId = $interviewProcess; // Ensure this is a string
                    if (!in_array($newId, $processOrderIds)) {
                        $processOrderIds[] = $newId;
                    }
                
                    // Convert back to a string and update
                    $jobDetails->update(['process_order_ids' => implode(',', $processOrderIds)]);
                    
                } else{
                    //that means no general job exists. so we will add it.
                    Job::create([
                        'title' => 'General Job',
                        'employer_id' => $currentUser,
                        'process_order_ids' => $interviewProcess,
                        'general_job_status' => 1,
                    ]);
                }
                
            }
            
            return Response(['response' => $interviewProcess, 'message' => 'Process name added successfully', 'status' => 200], 200);
        // }
    }
    
    public function admin_editInterviewProcess(Request $request, $slug) {
        $existingInterviewProcess = Process::where('slug', $slug)->first();
        
        
        $userId = Auth::user()->id;
        
        $staffDetail = Staff::find($userId);
        
        if(!empty($staffDetail)){
            $adminData = $staffDetail;
                
            $accessData = isset($adminData->roles) ? unserialize($adminData->roles) : [];
                
            global $subadminAccess;
            $accessControlArray = $subadminAccess;
                
            if (!is_array($accessControlArray)) {
                return response()->json(['message' => 'Access control data is missing or invalid', 'status' => 500], 500);
            }
                
            $accessArray = [];
            foreach ($accessControlArray as $key => $ac) {
                $accessArray[$key] = $ac; // Start with the original sub-array
                
                // Override with $accessData if available
                if (isset($accessData[$key])) {
                    foreach ($accessData[$key] as $accessKey => $accessValue) {
                        $accessArray[$key][$accessKey] = $accessValue;
                    }
                }
            }
                    
                    
            if($accessArray['11']['Edit'] == 0){
                return Response(['response' => 'You are not allowed to access this page.', 'message' => 'You are not allowed to access this page.', 'status' => 500], 200);
            }
        }

        if(!empty($request->all())){
            $validator = Validator::make($request->all(), [
                'process_name' => 'required|unique:interview_processes,process_name,'
            ]);    
            $validator->setAttributeNames([
                'process_name' => 'Process Name',
            ]);
            if($validator->fails()){
                return Response(['response' => $validator->errors(), 'status' => 500], 200);
            } else {
                $interviewProcess = Process::where('slug', $slug)->update([
                    'process_name' => $request->process_name,
                    'slug' => createSlug('processes', $request->process_name),
                ]);
                return Response(['response' => $interviewProcess, 'message' => 'Process name updated successfully', 'status' => 200], 200);
            }
        } else {
            return Response(['response' => $existingInterviewProcess, 'message' => '', 'status' => 200], 200);
        }
    }
    
    public function admin_deleteInterviewProcess(Request $request, $slug) {
        // $interviewProcess = Process::where('slug', $slug)->first();
        // if(!empty($interviewProcess)) {
        //     Process::where('slug', $slug)->delete();
        //     return Response(['response' => "", 'message' => 'Process name deleted successfully', 'status' => 200], 200);
        // } else {
        //     return Response(['response' => '', 'message' => 'Process name not found', 'status' => 500], 200);
        // }
        $interviewProcess = Process::where('slug', $slug)->first();
        $currentUser = Auth::user()->id;
        $currentUserCheck = Admin::where('id', $currentUser)->first();
        // echo $currentUser;
        if (!empty($currentUserCheck)) {
            //admin
            if (!empty($interviewProcess)) {
                Process::where('slug', $slug)->delete();
                $msgString = 'Process name deleted successfully';
                return Response(['response' => $msgString, 'message' => $msgString, 'status' => 200], 200);
            } else {

                $msgString = 'No record deleted';
                return Response(['response' => $msgString, 'message' => $msgString, 'status' => 500], 200);
            }
        } else {
            //employer
            if ($interviewProcess->employer_id != 0) {
                // echo "hi";
                Process::where('slug', $slug)->delete();
                $msgString = 'Process name deleted successfully';
                return Response(['response' => $msgString, 'message' => $msgString, 'status' => 200], 200);
            } else {
                return Response(['response' => "", 'message' => "This is a system generated process and cannot be deleted", 'status' => 500], 200);
            }
        }
    }


    // ***************************************************************************************************

    public function admin_interviewStatus(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)) {
            

            $interviewStatus = StatusAttributes::orderBy('id', 'desc')->get();

            $interviewStatusData = array();
            foreach ($interviewStatus as $key => $value) {

                $employerName = "System Generated";
                if ($value->employer_id != 0) {
                    $employerRecord = Employer::where('id', $value->employer_id)->first();
                    if (!empty($employerRecord)) {
                        $employerName = $employerRecord->first_name . " " . $employerRecord->last_name;
                    }
                }

            $interviewStatusData[$key]['interview_status_id'] = $value->id;
            $interviewStatusData[$key]['employer_id'] = $value->employer_id;
            $interviewStatusData[$key]['interview_status_name'] = $value->status_name;
            $interviewStatusData[$key]['status'] = $value->status;
            $interviewStatusData[$key]['slug'] = $value->slug;
            $interviewStatusData[$key]['position'] = $value->position;
            $interviewStatusData[$key]['created'] = format_date($value->created_at);
            }
        } else { 
            
            $interviewStatus = StatusAttributes::where(function ($query) use ($employerCheck) {
                $query->where('employer_id', $employerCheck->id)
                    ->orWhere('employer_id', 0);
            })
                ->where('status', 1)
                ->orderBy('id', 'desc')
                ->get();

            $interviewStatusData = array();
            foreach ($interviewStatus as $key => $value) {
                $employerStatusArray = explode(',', $value->employer_status);
               

                // Check if the current user's ID is in the employer_status array
                $userPresent = in_array($currentUser, $employerStatusArray);
            
                $interviewStatusData[$key]['interview_status_id'] = $value->id;
                $interviewStatusData[$key]['employer_id'] = $value->employer_id;
                $interviewStatusData[$key]['interview_status_name'] =  $value->status_name;
                $interviewStatusData[$key]['status'] = $userPresent ? 0 : 1; // Set status based on user presence;
                $interviewStatusData[$key]['slug'] = $value->slug;
                $interviewStatusData[$key]['position'] = $value->position;
                $interviewStatusData[$key]['created'] = format_date($value->created_at);
            }
        }

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

    public function admin_addInterviewStatus(Request $request) {
        $validator = Validator::make($request->all(), [
            'status_name' => 'required|unique:status_attributes,status_name',
        ]);
        $validator->setAttributeNames([
            'status_name' => 'Status Name',
        ]);
        if($validator->fails()){
            return Response(['response' => $validator->errors(), 'message' => $validator->errors(), 'status' => 500], 200);
        }
        else {
            
            $slug = Str::slug($request->status_name);
            
            $currentUser = Auth::user()->id;
            $adminCheck = Admin::where('id', $currentUser)->first();
            $employerCheck = Employer::where('id', $currentUser)->first();
            $staffCheck = Staff::where('id', $currentUser)->first();
            // echo $currentUser;
            if (!empty($adminCheck)) {
                $interviewStatus = StatusAttributes::insert([
                    'status_name' => $request->status_name,
                    'slug' => $slug,
                    'status' => 1,
                    'position' => 1,
                    'employer_id' => 0
                ]);
            } else {
                $interviewStatus = StatusAttributes::insert([
                    'status_name' => $request->status_name,
                    'slug' => $slug,
                    'position' => 1,
                    'status' => 1,
                    'employer_id' => $employerCheck->id
                ]);
            }
            return Response(['response' => $interviewStatus, 'message' => 'Status name added successfully', 'status' => 200], 200);
        }
    }
    
    public function admin_editInterviewStatus(Request $request, $slug) {
        $existingInterviewStatus = StatusAttributes::where('slug', $slug)->first();

        if(!empty($request->all())){
            $validator = Validator::make($request->all(), [
                'status_name' => 'required'
            ]);    
            $validator->setAttributeNames([
                'status_name' => 'Status Name',
            ]);
            if ($validator->fails()) {
            $msg = $this->validatersErrorString($validator->errors());
            return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
        }else {
                $interviewStatus = StatusAttributes::where('slug', $slug)->update([
                    'status_name' => $request->status_name,
                    'slug' => createSlug('status_attributes', $request->status_name),
                ]);
                return Response(['response' => $interviewStatus, 'message' => 'Status name updated successfully', 'status' => 200], 200);
            }
        } else {
            return Response(['response' => $existingInterviewStatus, 'message' => '', 'status' => 200], 200);
        }
    }
    
    public function admin_deleteInterviewStatus(Request $request, $slug) {
        // $interviewStatus = StatusAttributes::where('slug', $slug)->first();
        // if(!empty($interviewStatus)) {
        //     StatusAttributes::where('slug', $slug)->delete();
        //     return Response(['response' => "", 'message' => 'Status name deleted successfully', 'status' => 200], 200);
        // } else {
        //     return Response(['response' => '', 'message' => 'Status name not found', 'status' => 500], 200);
        // }
        
        $interviewStatus = StatusAttributes::where('slug', $slug)->first();

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

                $msgString = 'No record deleted';
                return Response(['response' => $msgString, 'message' => $msgString, 'status' => 500], 200);
            }
        } else {
            //employer
            if ($interviewStatus->employer_id != 0) {
                // echo "hi";
                StatusAttributes::where('slug', $slug)->delete();
                $msgString = 'Status name 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 admin_assignUserToProcessListing(Request $request)
        {
        
        
        $currentUser = Auth::user()->id;
        $currentUserCheck = Admin::where('id', $currentUser)->first();
        
        $staffDetail = Staff::find($currentUser);
        
        if(!empty($staffDetail)){
            
            $adminData = $staffDetail;
                
                $accessData = isset($adminData->roles) ? unserialize($adminData->roles) : [];
            
                    global $subadminAccess;
                    $accessControlArray = $subadminAccess;
            
                    if (!is_array($accessControlArray)) {
                        return response()->json(['message' => 'Access control data is missing or invalid', 'status' => 500], 500);
                    }
            
                    $accessArray = [];
                    foreach ($accessControlArray as $key => $ac) {
                        $accessArray[$key] = $ac; // Start with the original sub-array
            
                        // Override with $accessData if available
                        if (isset($accessData[$key])) {
                            foreach ($accessData[$key] as $accessKey => $accessValue) {
                                $accessArray[$key][$accessKey] = $accessValue;
                            }
                        }
                    }
                
                
                if($accessArray['13']['Module'] == 0){
                    return Response(['response' => 'You are not allowed to access this page.', 'message' => 'You are not allowed to access this page.', 'status' => 500], 200);
                }
        }
        
        
        if (!empty($currentUserCheck)) {
             $listing = DB::table('assign_users_to_processes')->orderBy('id','desc')->get();
            
            $listingData = array();
    
            foreach ($listing as $key => $value) {
                $process = Process::find($value->process_id);
                $user = Admin::find($value->user_id);
    
                $listingData[$key]['id'] = $value->id;
                $listingData[$key]['user_name'] = $user ? $user->first_name . " " . $user->last_name : 'Unknown';
                $listingData[$key]['process_name'] = $process ? $process->process_name : 'Unknown';
                $listingData[$key]['admin_id'] = $value->admin_id;
                $listingData[$key]['employer_id'] = $value->employer_id;
                $listingData[$key]['status'] = $value->status;
                $listingData[$key]['slug'] = $value->slug;
                $listingData[$key]['round'] = $value->round;
                $listingData[$key]['created_at'] = format_date($value->created_at);
            }
             
        }
         else{
             
            $listing = '';
             
            if($request->user_type == 'staff'){
                
                $employerID = Staff::where('id', $currentUser)->value('employer_id');
                
                $listing = DB::table('assign_users_to_processes')->where(function ($query) use ($currentUser, $employerID) {
                    $query->where(function ($subQuery) {
                        $subQuery->where('employer_id', 0);
                    })
                    ->orWhere(function ($subQuery) use ($currentUser, $employerID) {
                        $subQuery->where(function ($innerQuery) use ($employerID, $currentUser) {
                            if (!is_null($employerID)) {
                                $innerQuery->where('employer_id', $employerID);
                            }
                            $innerQuery->orWhere('staff_id', $currentUser);
                        });
                    });
                })
                ->orderBy('id', 'desc')
                ->get();
                
            } else{
                
                $listing = DB::table('assign_users_to_processes')->where(function ($query) use ($currentUser) {
                    $query->where(function ($subQuery) {
                        $subQuery->where('employer_id', 0);
                    })
                    ->orWhere(function ($subQuery) use ($currentUser) {
                        $subQuery->where('employer_id', $currentUser);
                    });
                })
                ->orderBy('id', 'desc')
                ->get();
                
                // $listing = DB::table('assign_users_to_processes')->where('employer_id', $currentUser)->orderBy('id','desc')->get();
            }
             
            
            
            $listingData = array();
    
            foreach ($listing as $key => $value) {
                 $employerStatusArray = explode(',', $value->employer_status);

                // Check if the current user's ID is in the employer_status array
                $userPresent = in_array($currentUser, $employerStatusArray);
                $process = Process::find($value->process_id);
                $user = Staff::find($value->user_id);
    
                $listingData[$key]['id'] = $value->id;
                $listingData[$key]['user_name'] = $user ? $user->first_name . " " . $user->last_name : 'Unknown';
                $listingData[$key]['process_name'] = $process ? $process->process_name : 'Unknown';
                $listingData[$key]['admin_id'] = $value->admin_id;
                $listingData[$key]['employer_id'] = $value->employer_id;
                $listingData[$key]['status'] = $value->status;
                $listingData[$key]['slug'] = $value->slug;
                $listingData[$key]['round'] = $value->round;
                $listingData[$key]['created_at'] = format_date($value->created_at);
            }
         }
    
           
            
             
    
        return Response(['response' => $listingData, 'message' => 'success', 'status' => 200], 200);
    }



    public function admin_addUserToProcess(Request $request)
    {
        $currentUser = Auth::user()->id;
        $staffDetail = Staff::find($currentUser);
        
            if(!empty($staffDetail)){
                
                $adminData = $staffDetail;
                    
                    $accessData = isset($adminData->roles) ? unserialize($adminData->roles) : [];
                
                        global $subadminAccess;
                        $accessControlArray = $subadminAccess;
                
                        if (!is_array($accessControlArray)) {
                            return response()->json(['message' => 'Access control data is missing or invalid', 'status' => 500], 500);
                        }
                
                        $accessArray = [];
                        foreach ($accessControlArray as $key => $ac) {
                            $accessArray[$key] = $ac; // Start with the original sub-array
                
                            // Override with $accessData if available
                            if (isset($accessData[$key])) {
                                foreach ($accessData[$key] as $accessKey => $accessValue) {
                                    $accessArray[$key][$accessKey] = $accessValue;
                                }
                            }
                        }
                    
                    
                if($accessArray['13']['Add'] == 0){
                    return Response(['response' => 'You are not allowed to access this page.', 'message' => 'You are not allowed to access this page.', 'status' => 500], 200);
                }
            }
        

        if (!empty($request->user_id) && !empty($request->process_id)) {
            $validator = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required',
                    'process_id' => 'required',
                    
 
                ]

            );


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

                // $listing = DB::table('assign_users_to_processes')->insert([
                //     'user_id' => $request->user_id,
                //     'process_id' => $request->process_id,
                //     'admin_id' => 0,
                //     'status' => 1,
                //     'round' => 0,
                //     'slug' => createSlug('assign_users_to_processes', $request->user_id),
                // ]);
                // return Response(['response' => $listing, 'message' => 'User assigned to Process successfully', 'status' => 200], 200);
                
               
            
            // $currentUser = Auth::user()->id;
            $currentUserCheck = Admin::where('id', $currentUser)->first();
            
            $existingAssignedUser = DB::table('assign_users_to_processes')
                                        ->where('user_id', $request->user_id)
                                        ->where('process_id', $request->process_id)
                                        ->exists();
                                        
            
            if($existingAssignedUser){
                return Response(['response' => 'This process is already assigned to the user', 'message' => 'success', 'status' => 200], 200);
            }
            
            
            // echo $currentUser;
            if (!empty($currentUserCheck)) {
                // $designation = Skill::insert([
                //     'skill_name' => $request->designation_name,
                //     'slug' => $slug,
                //     'type' => 'Designation',
                //     'status' => 1,
                //     'employer_id' => 0
                // ]);
                $listing = DB::table('assign_users_to_processes')->insert([
                   'user_id' => $request->user_id,
                    'process_id' => $request->process_id,
                     
                    'admin_id' => 0,
                     'status' => 1,
                     'round' => 0,
                    'slug' => createSlug('assign_users_to_processes', $request->user_id),
                    'employer_id' => 0,
                    'staff_id' => '0',
                    'user_type' => 'admin',
                 ]);
            } else {
                
                if($request->user_type == 'staff'){
                    
                    $employerID = Staff::where('id', $currentUser)->value('employer_id');
                    
                    $listing = DB::table('assign_users_to_processes')->insert([
                       'user_id' => $request->user_id,
                      
                        'process_id' => $request->process_id,
                        'admin_id' => 0,
                         'status' => 1,
                         'round' => 0,
                        'slug' => createSlug('assign_users_to_processes', $request->user_id),
                        'employer_id' => $employerID,
                        'staff_id' => $currentUser,
                        'user_type' => $request->user_type,
                    ]);
                    
                } else{
                    
                    $listing = DB::table('assign_users_to_processes')->insert([
                       'user_id' => $request->user_id,
                      
                        'process_id' => $request->process_id,
                        'admin_id' => 0,
                         'status' => 1,
                         'round' => 0,
                        'slug' => createSlug('assign_users_to_processes', $request->user_id),
                        'employer_id' => $currentUser,
                        'staff_id' => '0',
                        'user_type' => 'employer'
                    ]);
                    
                }
                
                
            }
            }
            // return Response(['response' => '', 'message' => 'All fields are required', 'status' => 500], 200);
            return Response(['response' => $listing, 'message' => 'User assigned to Process successfully', 'status' => 200], 200);
        } else {
            // $currentUser = Auth::user()->id;
            $currentUserCheck = Admin::where('id', $currentUser)->first();
            // echo $currentUser;
            if (!empty($currentUserCheck)) {
                $processNames = Process::all();
                $users = Admin::all();
            } else{
                
                if($request->user_type == 'staff'){
                    
                    $EmployerId = Staff::where('id', $currentUser)->value('employer_id');
                    
                    $currentUserCheck = Employer::where('id', $EmployerId)->first();
                    $processNames = Process::where('employer_id', $EmployerId)->orWhere('employer_id', 0)->get();
                    $users = Staff::where('employer_id', $EmployerId)->get();
                    
                } else{
                    
                    $currentUserCheck = Employer::where('id', $currentUser)->first();
                    $processNames = Process::where('employer_id', $currentUser)->orWhere('employer_id', 0)->get();
                    $users = Staff::where('employer_id', $currentUser)->get();
                    
                }
                
                
            }
            return Response(['response' => ['processes' => $processNames, 'users' => $users], 'message' => 'success', 'status' => 200], 200);
        }
    }


    public function admin_editUserToProcess(Request $request, $id)
    {
        $currentUser = Auth::user()->id;
        $existingUserAssignedToProcess = DB::table('assign_users_to_processes')->where('id', $id)->first();
        $processNames = '';
        $users = '';
        
        if($request->user_type == 'staff'){
            
            $employerId = Staff::where('id', $currentUser)->value('employer_id');
            
            $processNames = Process::where('employer_id', $employerId)->orWhere('employer_id', 0)->get();
            $users = Staff::where('employer_id', $employerId)->get();
            
        } else{
            
            $processNames = Process::where('employer_id', $currentUser)->orWhere('employer_id', 0)->get();
            $users = Staff::where('employer_id', $currentUser)->get();
        }
        
        
        $requestData = $request->except('user_type');

        if (!empty($requestData)) {

            $validator = Validator::make($request->all(), [
                'user_id' => 'required',
                'process_id' => 'required',

            ]);
            $validator->setAttributeNames([
                'user_id' => 'User',
                'process_id' => 'Process',
            ]);

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

                $listing = DB::table('assign_users_to_processes')->where('id', $id)->update([
                    'user_id' => $request->user_id,
                    'process_id' => $request->process_id,
                    'slug' => createSlug('assign_users_to_processes', $request->user_id),
                ]);

                return Response(['response' => $listing, 'message' => 'User Process updated successfully', 'status' => 200], 200);
            }
        } else {
            return Response(['response' =>['existingData' => $existingUserAssignedToProcess, 'processes' => $processNames, 'users' => $users],  'message' => '', 'status' => 200], 200);
        }
    }



    public function admin_deleteUserToProcess(Request $request, $id){

        $existingRecord = DB::table('assign_users_to_processes')->where('id', $id)->first();

         if(!empty($existingRecord)){
             DB:: table('assign_users_to_processes')->where('id', $id)->delete();
            return Response(['response' => '', 'message' => 'User Process deleted successfully', 'status' => 200], 200);

         } else{

             return Response(['response' => '', 'message' => 'User Process not found', 'status' => 500], 200);
         }
    }


    public function admin_activateUserToProcess(Request $request, $slug){
        $userData = DB::table('assign_users_to_processes')->where('id', $slug)->first();

        if(!empty($userData)){
            DB::table('assign_users_to_processes')->where('id', $slug)->update([
                'status' => 1
            ]);
            return Response(['response' => $userData, 'message' => 'User Process activated successfully', 'status' => 200], 200);
        }
    }

    public function admin_deactivateUserToProcess(Request $request, $slug){
        $userData = DB::table('assign_users_to_processes')->where('id', $slug)->first();

        if(!empty($userData)){
            DB::table('assign_users_to_processes')->where('id', $slug)->update([
                'status' => 0
            ]);
            return Response(['response' => $userData, 'message' => 'User Process deactivated successfully', 'status' => 200], 200);
        }
    }
    
    
    public function admin_multipleActionsUserToProcess(Request $request){
        if ($request->filled('action')) {
            $idList = $request->idList;
            
            if ($idList) {
                if ($request->action == 'activate') {
                    DB::table('skills')->whereIn('id', explode(',', $idList))->update(['status' => '1']);
                    
                    return Response(['response' => 'Activated Successfully', 'message' => 'success', 'status' => 200], 200);
                    
                } elseif ($request->action == 'deactivate') {
                    DB::table('skills')->whereIn('id', explode(',', $idList))->update(['status' => '0']);
                    
                    return Response(['response' => 'De-activated Successfully', 'message' => 'success', 'status' => 200], 200);

                } elseif ($request->action == 'delete') {
                    DB::table('skills')->whereIn('id', explode(',', $idList))->delete();
                    
                    return Response(['response' => 'Deleted Successfully', 'message' => 'success', 'status' => 200], 200);

                }
            }
        }
        
        return Response(['response' => '', 'message' => 'please select action', 'status' => 500], 200);
    }
    
    // ************************** Manage Sub-Admins **************************

    public function admin_subadminsListing(Request $request) {

        $listing = Admin::where('id', '!=', 1)->get();


        if ($request->filled('action')) {
            $idList = $request->idList;
            if ($idList) {
                if ($request->action == 'activate') {
                    Admin::whereIn('id', explode(',', $idList))->update(['status' => '1']);
                } elseif ($request->action == 'deactivate') {
                    Admin::whereIn('id', explode(',', $idList))->update(['status' => '0']);
                } elseif ($request->action == 'delete') {
                    Admin::whereIn('id', explode(',', $idList))->delete();
                   
                }
            }
        }


        if(!empty($listing)){
            $subadminData = array();

            foreach ($listing as $key => $value) {
                $subadminData[$key]['id'] = $value->id;
                $subadminData[$key]['first_name'] = $value->first_name;
                $subadminData[$key]['last_name'] = $value->last_name;
                $subadminData[$key]['email'] = $value->email;
                $subadminData[$key]['created_at'] = format_date($value->created_at);
                $subadminData[$key]['status'] = $value->status;
                $subadminData[$key]['username'] = $value->username;
                $subadminData[$key]['slug'] = $value->slug;

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

    }

    public function admin_addSubadmin(Request $request) {

        $validator = Validator::make($request->all(), [
            'first_name' => 'required',
            'last_name' => 'required',
            'email' => 'required|unique:admins,email',
            'username' => 'required|unique:admins,username',
            'password' => 'required',
            'confirm_password' => 'required|same:password',
        ]);

        $validator->setAttributeNames([
            'first_name' => 'First Name',
            'last_name' => 'Last Name',
            'email' => 'Email',
            'username' => 'Username',
            'password' => 'Password',
            'confirm_password' => 'Confirm Password',
        ]);

        // if($validator->fails()) {
        //     return Response(['response' => $validator->errors(), 'status' => 500], 200);
        // } 
        
        if ($validator->fails()) {
            $msg = $this->validatersErrorString($validator->errors());
            return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
        }
        else {
            if($request->password != $request->confirm_password){
                return Response(['response' => 'Password and confirm password does not match', 'status' => 500], 200);
            }
            $password = Hash::make($request->password);
            Admin::insert([
                'first_name' => $request->first_name,
                'last_name' => $request->last_name,
                'email' => $request->email,
                'username' => $request->username,
                'password' => $password,
                'status' => 1,
                'slug' => createSlug('admins', $request->username),
            ]);

            return Response(['response' => '', 'message' => 'Sub-Admin added successfully', 'status' => 200], 200);
        }
    }
    
    // public function admin_editSubadmin(Request $request, $slug) {

    //     $subadmin = Admin::where('slug', $slug)->first();

    //     if (!$subadmin) {
    //         return Response(['response' => 'Subadmin not found', 'status' => 404], 404);
    //     }
    
    //     $subadminData = [
    //         'id' => $subadmin->id,
    //         'first_name' => $subadmin->first_name,
    //         'last_name' => $subadmin->last_name,
    //         'email' => $subadmin->email,
    //         'created_at' => format_date($subadmin->created_at),
    //         'status' => $subadmin->status,
    //         'username' => $subadmin->username,
    //         'slug' => $subadmin->slug,
    //     ];
    //     if(!empty($request->all())){
    //         $validator = Validator::make($request->all(), [
    //             'first_name' => 'required',
    //             'last_name' => 'required',
    //             'email' => 'required|unique:admins,email',
    //             'username' => 'required|unique:admins,username',
    //         ]);

    //         $validator->setAttributeNames([
    //             'first_name' => 'First Name',
    //             'last_name' => 'Last Name',
    //             'email' => 'Email',
    //             'username' => 'Username',
    //             // 'password' => 'Password',
    //             // 'confirm_password' => 'Confirm Password',

    //         ]);

    //         if($validator->fails()) {
    //             return Response(['response' => $validator->errors(), 'status' => 500], 200);
    //         } else {
    //             if(!empty($request->password) && !empty($request->confirm_password)){
    //                 if($request->password != $request->confirm_password){
    //                     return Response(['response' => 'Password and confirm password does not match', 'status' => 500], 200);
    //                 }
    //                 $password = Hash::make($request->password);
    //                 Admin::where('slug', $request->slug)->update([
    //                     'first_name' => $request->first_name,
    //                     'last_name' => $request->last_name,
    //                     'email' => $request->email,
    //                     'username' => $request->username,
    //                     'password' => $password,
    //                     'slug' => createSlug('admins', $request->username),
    //                 ]);
    //             }

    //             Admin::where('slug', $request->slug)->update([
    //                 'first_name' => $request->first_name,
    //                 'last_name' => $request->last_name,
    //                 'email' => $request->email,
    //                 'username' => $request->username,
    //                 'slug' => createSlug('admins', $request->username),
    //             ]);
    //             return Response(['response' => '', 'message' => 'Sub-Admin updated successfully', 'status' => 200], 200);
    //         }

    //     } else{
    //         return Response(['response' => $subadminData, 'message' => '', 'status' => 200], 200);
    //     }
    // }
    
    public function admin_editSubadmin(Request $request, $slug) {
        $subadmin = Admin::where('slug', $slug)->first();
    
        if (!$subadmin) {
            return Response(['response' => 'Subadmin not found', 'status' => 404], 404);
        }
    
        $subadminData = [
            'id' => $subadmin->id,
            'first_name' => $subadmin->first_name,
            'last_name' => $subadmin->last_name,
            'email' => $subadmin->email,
            'created_at' => format_date($subadmin->created_at),
            'status' => $subadmin->status,
            'username' => $subadmin->username,
            'slug' => $subadmin->slug,
        ];
    
        if (!empty($request->all())) {
            $validator = Validator::make($request->all(), [
                'first_name' => 'required',
                'last_name' => 'required',
                'email' => 'required|unique:admins,email,' . $subadmin->id,
                'username' => 'required|unique:admins,username,' . $subadmin->id,
            ]);
    
            $validator->setAttributeNames([
                'first_name' => 'First Name',
                'last_name' => 'Last Name',
                'email' => 'Email',
                'username' => 'Username',
            ]);
    
            if ($validator->fails()) {
                return Response(['response' => $validator->errors(), 'status' => 500], 200);
            } else {
                $updateData = [];
                if ($request->has('password') && !empty($request->password) && $request->password === $request->confirm_password) {
                    $updateData['password'] = Hash::make($request->password);
                }
    
                if ($subadmin->first_name !== $request->first_name) {
                    $updateData['first_name'] = $request->first_name;
                }
    
                if ($subadmin->last_name !== $request->last_name) {
                    $updateData['last_name'] = $request->last_name;
                }
    
                if ($subadmin->email !== $request->email) {
                    $updateData['email'] = $request->email;
                }
    
                if ($subadmin->username !== $request->username) {
                    $updateData['username'] = $request->username;
                    $updateData['slug'] = createSlug('admins', $request->username);
                }
    
                if (!empty($updateData)) {
                    Admin::where('slug', $slug)->update($updateData);
                    return Response(['response' => '', 'message' => 'Sub-Admin updated successfully', 'status' => 200], 200);
                } else {
                    return Response(['response' => 'No fields updated', 'status' => 200], 200);
                }
            }
        } else {
            return Response(['response' => $subadminData, 'message' => '', 'status' => 200], 200);
        }
    }


    public function admin_activateSubadmin(Request $request) {
        $subadminData = Admin::where('slug', $request->slug)->first();

        if(!empty($subadminData)){
            Admin::where('slug', $request->slug)->update([
                'status' => 1
            ]);
            return Response(['response' => "", 'message' => 'Sub-Admin activated successfully', 'status' => 200], 200);
        }
    }

    public function admin_deactivateSubadmin(Request $request) {
        $subadminData = Admin::where('slug', $request->slug)->first();

        if(!empty($subadminData)){
            Admin::where('slug', $request->slug)->update([
                'status' => 0
            ]);
            return Response(['response' => "", 'message' => 'Sub-Admin deactivated successfully', 'status' => 200], 200);
        }
    }

    public function admin_deleteSubadmin(Request $request) {
        $subadminData = Admin::where('slug', $request->slug)->first();

        if(!empty($subadminData)){
            Admin::where('slug', $request->slug)->delete();
            return Response(['response' => "", 'message' => 'Sub-Admin deleted successfully', 'status' => 200], 200);
        } else {
            return Response(['response' => "", 'message' => 'Sub-Admin not found', 'status' => 500], 200);
        }
    }
    
    
    // *********************************** Logout****************************************************
    
    public function logout(Request $request) {
        // Revoke the current user's token
        $request->user()->currentAccessToken()->delete();

        return response()->json(['message' => 'User logged out successfully', 'status' =>200], 200);
    }
    
    
    // *********************************** constant api****************************************************
    
    public function getConstants(Request $request) {
        
        
        $employerCode = $request->employer_id;
        
        $employerId = Employer::where('employer_code', $employerCode)->value('id');
        
        $generalSetting = GeneralSetting::where('employer_id', $employerId)->first();
        $employerData = Employer::where('id', $employerId)->first();
        $footerStatus = $generalSetting->footer_status ?? null;
        $existApplicationData = DirectApplicationForm::where('employer_id', $employerId)->first();
            
        $data = [];
        $data['showFooterOnHomepage'] = (string) ($generalSetting->footer_status ?? 0);
        $data['primary_color'] = $generalSetting->primary_color ?? 'N/A';
        $data['font_style'] = $generalSetting->font_style;
        $data['show_primary_banner'] = (string) ($generalSetting->show_primary_banner ?? 0);
        $data['secondary_color'] = $generalSetting->secondary_color;
        // $data['primary_banner'] = $generalSetting->primary_banner ?? 'N/A';
        // $data['secondary_banner'] = $generalSetting->secondary_banner;
        
        if(!empty($generalSetting->primary_banner)){
            $data['existing_primary_banner'] = DISPLAY_FULL_BANNER_IMAGE_PATH . $generalSetting->primary_banner;
        } else{
            $data['existing_primary_banner'] = '';
        }
            
        if(!empty($generalSetting->secondary_banner)){
            $data['existing_secondary_banner'] = DISPLAY_FULL_BANNER_IMAGE_PATH . $generalSetting->secondary_banner;
        } else{
            $data['existing_secondary_banner'] = '';
        }
            
        if(!empty($generalSetting->application_form_banner)){
            $data['existing_application_form_banner'] = DISPLAY_FULL_BANNER_IMAGE_PATH . $generalSetting->application_form_banner;
        } else{
            $data['existing_application_form_banner'] = '';
        }
        
            
        $data['company_contact'] = $employerData->company_contact;
        $data['company_email'] = $employerData->company_email;
        $data['company_address'] = $employerData->company_address;
        $data['show_company_logo'] = $employerData->company_logo_status;
        
        if(!empty($employerData->company_logo)){
            $data['company_logo'] = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $employerData->company_logo;
        } else{
            $data['company_logo'] = '';
        }
        
        if(!empty($existApplicationData)){
            $data['general_application_data'] = 1;
        } else{
            $data['general_application_data'] = 0;
        }
        
        
        // $company = Employer::where('id', $employerId)->value('company_logo');
        // $companyLogoStatus = Employer::where('id', $employerId)->value('company_logo_status');
        
        // if(!empty($company)){
        //     $companyLogo = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $company;
        // } else{
        //     $companyLogo = '';
        // }
        
        // $footerStatus = GeneralSetting::where('employer_id', $employerId)->value('footer_status');
        

        // $constants = [
        //     'site_captcha_key' => CAPTCHA_PUBLIC_KEY
        // ];

        return Response(['response' => ['data' => $data], 'message' => '', 'status' => 200], 200);
    }
    
    
    public function sendCredentials(){
        $constants = [
            'site_captcha_key' => CAPTCHA_PUBLIC_KEY
        ];
        
        return Response(['response' => $constants, 'message' => '', 'status' => 200], 200);
    }
    
    public function saveGeneralSetting(Request $request){
        $employerId = Auth::user()->id;
        
        if(!empty($request->all())){
             $validator = Validator::make($request->all(), [
            'offer_letter_expiry' => 'required',
            'offer_letter_expiry_value' => 'required',
            'onboarding_expiry' => 'required',
            'onboarding_expiry_value' => 'required',
        ]);
        
        
            if ($validator->fails()) {
                $msg = $this->validatersErrorString($validator->errors());
                return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
            } else{
                $existingData = GeneralSetting::where('employer_id', $employerId)->first();
                if(!empty($existingData)){
                     GeneralSetting::where('employer_id', $employerId)->update([
                        'offer_letter_expiry' => $request->offer_letter_expiry,
                        'offer_letter_expiry_value' => $request->offer_letter_expiry_value,
                        'onboarding_expiry' => $request->onboarding_expiry,
                        'onboarding_expiry_value' => $request->onboarding_expiry_value,
                        'employer_id' => $employerId,
                    ]);
                
                    return Response(['response' => '', 'message' => 'General Settings updated successfully', 'status' => 200], 200);
                    
                }else{
                    GeneralSetting::insert([
                        'offer_letter_expiry' => $request->offer_letter_expiry,
                        'offer_letter_expiry_value' => $request->offer_letter_expiry_value,
                        'onboarding_expiry' => $request->onboarding_expiry,
                        'onboarding_expiry_value' => $request->onboarding_expiry_value,
                        'employer_id' => $employerId,
                    ]);
                
                    return Response(['response' => '', 'message' => 'General Settings Saved Successfully', 'status' => 200], 200);
                }
            }
        } else{
            $generalSetting = GeneralSetting::where('employer_id', $employerId)->first();
            if(!empty($generalSetting)){
                return Response(['response' => $generalSetting, 'message' => '', 'status' => 200], 200); 
            }else{
                return Response(['response' => '', 'message' => '', 'status' => 200], 200); 
            }
            
        }
    }
    
    // public function siteSetting(Request $request){
    //     $employerId = Auth::user()->id;
        
    //     if(!empty($request->all())){
    //          $validator = Validator::make($request->all(), [
    //         'showFooterOnHomepage' => 'required',
    //         'primary_color' => 'required',
    //         'font_style' => 'required',
    //         'primary_banner' => 'required',
    //         'secondary_banner' => 'required',
    //         'show_primary_banner' => 'required',
    //         'secondary_color' => 'required',
    //     ]);
        
        
    //         if ($validator->fails()) {
    //             $msg = $this->validatersErrorString($validator->errors());
    //             return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
    //         } else{
    //             $existingData = GeneralSetting::where('employer_id', $employerId)->first();
    //             if(!empty($existingData)){
    //                  GeneralSetting::where('employer_id', $employerId)->update([
    //                     'footer_status' => $request->showFooterOnHomepage,
    //                     'primary_color' => $request->primary_color,
    //                     'font_style' => $request->font_style,
    //                     'show_primary_banner' => $request->show_primary_banner,
    //                     'secondary_color' => $request->secondary_color,
    //                     'employer_id' => $employerId,
    //                 ]);
                
    //                 return Response(['response' => '', 'message' => 'General Settings updated successfully', 'status' => 200], 200);
                    
    //             }else{
    //                 GeneralSetting::insert([
    //                     'footer_status' => $request->showFooterOnHomepage,
    //                     'primary_color' => $request->primary_color,
    //                     'font_style' => $request->font_style,
    //                     'show_primary_banner' => $request->show_primary_banner,
    //                     'secondary_color' => $request->secondary_color,
    //                     'employer_id' => $employerId,
    //                 ]);
                
    //                 return Response(['response' => '', 'message' => 'General Settings Saved Successfully', 'status' => 200], 200);
    //             }
    //         }
    //     } else{
    //         $generalSetting = GeneralSetting::where('employer_id', $employerId)->first();
    //         $footerStatus = $generalSetting->footer_status;
    //         if(!empty($footerStatus)){
    //             return Response(['response' => ['showFooterOnHomepage' => $footerStatus], 'message' => '', 'status' => 200], 200); 
    //         }else{
    //             return Response(['response' => '', 'message' => '', 'status' => 200], 200); 
    //         }
            
    //     }
        
    // }
    
    
    public function siteSetting(Request $request)
    {
        $employerId = Auth::user()->id;
    
        if (!empty($request->all())) {
            // $validator = Validator::make($request->all(), [
            //     'showFooterOnHomepage' => 'required',
            //     'primary_color' => 'required',
            //     'font_style' => 'required',
            //     'primary_banner' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            //     'secondary_banner' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            //     'show_primary_banner' => 'required',
            //     'secondary_color' => 'required',
            //     'company_contact' => 'nullable',
            //     'company_email' => 'nullable',
            //     'company_address' => 'nullable',
            // ]);
    
            // if ($validator->fails()) {
            //     $msg = $this->validatersErrorString($validator->errors());
            //     return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
            // }
    
            // Check if employer data exists in the request and update employer table
            $employerData = [];
            if ($request->has('company_contact')) {
                $employerData['company_contact'] = $request->company_contact;
            }
            if ($request->has('company_email')) {
                $employerData['company_email'] = $request->company_email;
            }
            if ($request->has('company_address')) {
                $employerData['company_address'] = $request->company_address;
            }
            if ($request->has('allow_candidate_accounts')) {
                $employerData['allow_candidate_accounts'] = $request->allow_candidate_accounts;
            }
    
            if (!empty($employerData)) {
                Employer::where('id', $employerId)->update($employerData);
                // return Response(['response' => '', 'message' => 'Employer data updated successfully', 'status' => 200], 200);
            }
    
            // Handle General Settings Update (Only if employer data is NOT being updated)
            $existingData = GeneralSetting::where('employer_id', $employerId)->first();
    
            // Handle file uploads
            $primaryBannerPath = $existingData->primary_banner ?? null;
            $secondaryBannerPath = $existingData->secondary_banner ?? null;
            $applicationFormBanner = $existingData->application_form_banner ?? null;
    
            if ($request->hasFile('primary_banner')) {
                $primaryBannerPath = $request->file('primary_banner')->store('uploads/site_settings', 'public');
            }
    
            if ($request->hasFile('secondary_banner')) {
                $secondaryBannerPath = $request->file('secondary_banner')->store('uploads/site_settings', 'public');
            }
            
            if($request->hasFile('application_form_banner')){
                $applicationFormBanner = $request->file('application_form_banner')->store('uploads/site_settings', 'public');
            }
    
            // Data for GeneralSetting table
            $generalData = [
                'footer_status' => $request->showFooterOnHomepage,
                'primary_color' => $request->primary_color,
                'font_style' => $request->font_style,
                'show_primary_banner' => $request->show_primary_banner,
                'secondary_color' => $request->secondary_color,
                'employer_id' => $employerId,
                'primary_banner' => $primaryBannerPath,
                'secondary_banner' => $secondaryBannerPath,
                'application_form_banner' => $applicationFormBanner,
            ];
    
            if ($existingData) {
                GeneralSetting::where('employer_id', $employerId)->update($generalData);
                return Response(['response' => '', 'message' => 'General Settings updated successfully', 'status' => 200], 200);
            } else {
                GeneralSetting::insert($generalData);
                return Response(['response' => '', 'message' => 'General Settings Saved Successfully', 'status' => 200], 200);
            }
        } else {
            $generalSetting = GeneralSetting::where('employer_id', $employerId)->first();
            $employerData = Employer::where('id', $employerId)->first();
            $footerStatus = $generalSetting->footer_status ?? null;
            
            $data = [];
            $data['showFooterOnHomepage'] = (string) ($generalSetting->footer_status ?? 0);
            $data['primary_color'] = $generalSetting->primary_color;
            $data['font_style'] = $generalSetting->font_style;
            $data['show_primary_banner'] = (string) ($generalSetting->show_primary_banner ?? 0);
            $data['secondary_color'] = $generalSetting->secondary_color;
            
            if(!empty($generalSetting->primary_banner)){
                $data['existing_primary_banner'] = DISPLAY_FULL_BANNER_IMAGE_PATH . $generalSetting->primary_banner;
            } else{
                $data['existing_primary_banner'] = '';
            }
            
            if(!empty($generalSetting->secondary_banner)){
                $data['existing_secondary_banner'] = DISPLAY_FULL_BANNER_IMAGE_PATH . $generalSetting->secondary_banner;
            } else{
                $data['existing_secondary_banner'] = '';
            }
            
            if(!empty($generalSetting->application_form_banner)){
                $data['existing_application_form_banner'] = DISPLAY_FULL_BANNER_IMAGE_PATH . $generalSetting->application_form_banner;
            } else{
                $data['existing_application_form_banner'] = '';
            }
            
            
            
            
            $data['company_contact'] = $employerData->company_contact;
            $data['company_email'] = $employerData->company_email;
            $data['company_address'] = $employerData->company_address;
            $data['allow_candidate_accounts'] = (string) $employerData->allow_candidate_accounts;
    
            if (!empty($footerStatus)) {
                return Response(['response' => $data, 'message' => '', 'status' => 200], 200);
            } else {
                return Response(['response' => $data, 'message' => '', 'status' => 200], 200);
            }
        }
    }


    
}
