<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Skill;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use App\Models\Employer;
use App\Models\Admin;
use App\Models\Staff;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;


class DesignationController extends Controller
{
    //

    public function listing (Request $request) {
        // $designation = Skill::where('type', 'Designation')->orderBy('id','desc')->get();

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

        // $designationData = array();

        // foreach($designation as $key => $value) {
        //     $designationData[$key]['designation_id'] = $value->id;
        //     $designationData[$key]['designation_name'] = $value->skill_name;
        //     $designationData[$key]['slug'] = $value->slug;
        //     $designationData[$key]['status'] = $value->status;
        //     $designationData[$key]['created'] = format_date($value->created);
        // }
        // return Response(['response' => $designationData, '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['6']['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";

            if ($request->filled('action')) {

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

            $skill = Skill::where('type',"Designation")->orderBy('id', 'desc')->get();

            $skillData = array();
            foreach ($skill 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;
                    }
                }

                $skillData[$key]['designation_id'] = $value->id;
                $skillData[$key]['designation_name'] = $value->skill_name;
                $skillData[$key]['employer_name'] = $employerName;
                $skillData[$key]['type'] = $value->type;
                $skillData[$key]['slug'] = $value->slug;
                $skillData[$key]['status'] = $value->status;
                $skillData[$key]['created'] = format_date($value->created);
            }
        } else {

            // Multiple activate/deactivate/delete
            if ($request->filled('action')) {

                $idList = $request->idList;
                if ($idList) {
                    if ($request->action == 'activate') {
                        // DB::table('qualifications')->whereIn('id', explode(',', $idList))->update(['status' => '1']);
                        $idList = $request->idList; // Assuming $idList is comma-separated IDs

                        // Update qualifications with status = '1'
                        DB::table('skills')->whereIn('id', explode(',', $idList))->update(['status' => '1']);

                        // Fetch the updated qualifications
                        $skills = DB::table('skills')->whereIn('id', explode(',', $idList))->get();

                        foreach ($skills as $skill) {
                            if($skill->employer_id == '0'){
                                $employerStatus = $skill->employer_status;

                                // Convert the comma-separated string into an array
                                $employerStatusArray = explode(',', $employerStatus);
    
                                // Check if the current user's ID is in the array
                                if (($key = array_search($currentUser, $employerStatusArray)) !== false) {
                                    // Remove the user ID from the array
                                    unset($employerStatusArray[$key]);
    
                                    // Convert the array back to a comma-separated string
                                    $updatedEmployerStatus = implode(',', $employerStatusArray);
    
                                    // Update the qualification's employer status
                                    DB::table('skills')->where('id', $skill->id)->update(['employer_status' => $updatedEmployerStatus]);
                                }
                                
                            } else{
                                DB::table('skills')->where('id', $skill->id)->update(['status' => 1]);
                            }
                            
                        }
                    } elseif ($request->action == 'deactivate') {
                        // DB::table('qualifications')->whereIn('id', explode(',', $idList))->update(['status' => '0']);

                        $idList = $request->idList; // Assuming $idList is comma-separated IDs

                        // Update qualifications with status = '1'
                        // DB::table('qualifications')->whereIn('id', explode(',', $idList))->update(['status' => '0']);

                        // Fetch the updated qualifications
                        $skills = DB::table('skills')->whereIn('id', explode(',', $idList))->get();

                        foreach ($skills as $skill) {
                            if($skill->employer_id == '0'){
                                $employerStatus = $skill->employer_status;

                                // Convert the comma-separated string into an array
                                $employerStatusArray = explode(',', $employerStatus);
    
    
    
                                // Check if the current user's ID is not in the array
                                if (!in_array($currentUser, $employerStatusArray)) {
                                    // Add the user ID to the array
                                    $employerStatusArray[] = $currentUser;
    
                                    // Convert the array back to a comma-separated string
                                    $updatedEmployerStatus = implode(',', $employerStatusArray);
    
                                    // Update the qualification's employer status
                                    DB::table('skills')->where('id', $skill->id)->update(['employer_status' => $updatedEmployerStatus]);
                                }
                            } else{
                                DB::table('skills')->where('id', $skill->id)->update(['status' => 0]);
                            }
                            
                        }
                    } elseif ($request->action == 'delete') {
                        // DB::table('skills')->where('employer_id', '!=', 0)->whereIn('id', explode(',', $idList))->delete();
                        
                        $idListArray = explode(',', $idList);

                        // Fetch skills using Eloquent
                        $skills = Skill::whereIn('id', $idListArray)->get();
                        
                        $systemGeneratedSkills = [];
                        $deletableSkills = [];
                        
                        foreach ($skills as $skill) {
                            if ($skill->employer_id == 0) {
                                $systemGeneratedSkills[] = $skill;
                            } else {
                                $deletableSkills[] = $skill->id;
                            }
                        }
                        
                        // Prepare response for system generated skills
                        if (!empty($systemGeneratedSkills)) {
                            $systemGeneratedSkillsDetails = array_map(function ($skill) {
                                return [
                                    'id' => $skill->id,
                                    'name' => $skill->skill_name
                                ];
                            }, $systemGeneratedSkills);
                        
                            return Response([
                                'response' => "",
                                'message' => 'You cannot delete system generated skills.',
                                'system_generated_skills' => $systemGeneratedSkillsDetails,
                                'status' => 500
                            ], 200);
                        }
                        
                        // Delete only the skills that can be deleted
                        Skill::whereIn('id', $deletableSkills)->delete();
                        
                        return Response([
                            'response' => "",
                            'message' => 'Selected skills have been successfully deleted.',
                            'status' => 200
                        ], 200);
                    }
                }
            }

            // $skill = Skill::where(function ($query) use ($currentUser) {
            //     $query->where('employer_id', $currentUser)
            //         ->orWhere('employer_id', 0);
                    
            // })
            // ->Where('type',"Designation")
            //     ->where('status', 1)
            //     ->orderBy('id', 'desc')
            //     ->get();
            
            
            $skill = '';
            
            if($request->user_type == 'employer'){
                
                $skill = Skill::where('type', 'Designation')->where(function ($query) use ($currentUser) {
                    $query->where(function ($subQuery) {
                        $subQuery->where('employer_id', 0)
                                 ->where('status', 1); // For employer_id = 0, ensure status is 1
                    })
                    ->orWhere(function ($subQuery) use ($currentUser) {
                        $subQuery->where('employer_id', $currentUser);
                        // No status filter for other employer_ids
                    });
                })
                ->orderBy('id', 'desc')
                ->get();
                
            } else{
                
                $employerId = Staff::where('id', $currentUser)->value('employer_id');
                
                $skill = Skill::where('type', 'Designation')->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();
            
            }

            $skillData = array();
            foreach ($skill 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);

                $skillData[$key]['designation_id'] = $value->id;
                $skillData[$key]['designation_name'] = $value->skill_name;
                $skillData[$key]['type'] = $value->type;
                $skillData[$key]['slug'] = $value->slug;
                $skillData[$key]['employer_id'] = $value->employer_id;
                $skillData[$key]['employer_status'] = $value->employer_status;
                $skillData[$key]['user_type'] = $value->user_type;
                if($value->employer_id == '0'){
                    $skillData[$key]['status'] = $userPresent ? 0 : 1; // Set status based on user presence
                } else{
                    $skillData[$key]['status'] = $value->status;
                }
                
                $skillData[$key]['created'] = format_date($value->created);
            }
        }
        //$qualification = Qualification::orderBy('id','desc')->get();






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

    public function addDesignation(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['6']['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->all())){
            
            $validator = Validator::make($request->all(), [
                'designation_name' => 'required|unique:skills,skill_name',
            ]);
            $validator->setAttributeNames([
                'designation_name' => 'Designation Name',
            ]);
            if ($validator->fails()) {
                $msg = $this->validatersErrorString($validator->errors());
                return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
            }
            else {
                $slug = Str::slug($request->designation_name);
                
                // $currentUser = Auth::user()->id;
                $currentUserCheck = Admin::where('id', $currentUser)->first();
                // echo $currentUser;
                if (!empty($currentUserCheck)) {
                    $designation = Skill::insert([
                        'skill_name' => $request->designation_name,
                        'slug' => $slug,
                        'type' => 'Designation',
                        'status' => 1,
                        'employer_status' => '',
                        'employer_id' => 0
                    ]);
                } else {
                    
                    if($request->user_type == 'employer'){
                        
                        $designation = Skill::insert([
                            'skill_name' => $request->designation_name,
                            'slug' => $slug,
                            'type' => 'Designation',
                            'status' => 1,
                            'employer_id' => $currentUser,
                            'employer_status' => '',
                            'staff_id' => '',
                            'user_type' => $request->user_type
                        ]);
                        
                    } else{
                        
                        $employerId = Staff::where('id', $currentUser)->value('employer_id');
                        
                        $designation = Skill::insert([
                            'skill_name' => $request->designation_name,
                            'slug' => $slug,
                            'type' => 'Designation',
                            'status' => 1,
                            'employer_id' => $employerId,
                            'employer_status' => '',
                            'staff_id' => $currentUser,
                            'user_type' => $request->user_type,
                        ]);
                    
                    }
                    
                    
                }
                
    
                return Response(['response' => $designation, 'message' => 'Designation added successfully', 'status' => 200], 200);
            }
        
        }
        
    }
    public function editDesignation(Request $request, $slug) {
        // $existingDesignation = Skill::where('slug', $slug)->first();
        // if(!empty($request->all())){
        
        //     $validator = Validator::make($request->all(), [
        //         'skill_name' => 'required|unique:skills,skill_name,',
        //     ]);
        //     $validator->setAttributeNames([
        //         'skill_name' => 'Designation Name',
        //     ]);
        //     if($validator->fails()){
        //         return Response(['response' => $validator->errors(), 'status' => 500], 200);
        //     } else {
                
        //         $designation = Skill::where('slug', $request->slug)->where('type', 'Designation')->update([
        //             'skill_name' => $request->skill_name,
        //             'type' => 'Designation',
        //             'slug' => Str::slug($request->skill_name),
        //         ]);

        //         return Response(['response' => $designation, 'message' => 'Designation updated successfully', 'status' => 200], 200);
        //     }
        // } else {
        //     return Response(['response' => $existingDesignation, 'status' => 200], 200);
        // }
        
        $skill = Skill::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['6']['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(), [
                'skill_name' => 'required|unique:skills,skill_name',
            ]);

            $validator->setAttributeNames([
                'skill_name' => 'Designation Name',
            ]);

            if ($validator->fails()) {
                $msg = $this->validatersErrorString($validator->errors());
                return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
            } else {
                // Generate slug from qualification name    
                $skill = Skill::where('slug', $request->slug)->update([
                    'skill_name' => $request->skill_name,
                    'slug' => Str::slug($request->skill_name), // Store the slug in the database
                ]);

                return Response(['response' => $skill, 'message' => 'Designation updated successfully', 'status' => 200], 200);
            }
        } else {
            if($skill->employer_id == '0'){
                return Response(['response' => '', 'message' => 'You cannot edit System generated Designation', 'status' => 501], 200);
            }
            return Response(['response' => $skill, 'message' => '', 'status' => 200], 200);
        }
    }

    public function deleteDesignation($slug) {
    //     $designationData = Skill::where('slug',$slug)->first();

    //   if(!empty($designationData)){
    //         Skill::where('slug',$slug)->delete();
    //         $msgString = 'Designation 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);
    //   }
    
    $skillData = Skill::where('slug', $slug)->first();

        $currentUser = Auth::user()->id;
        $currentUserCheck = Admin::where('id', $currentUser)->first();
        // echo $currentUser;
        if (!empty($currentUserCheck)) {
            //admin
            if (!empty($skillData)) {
                Skill::where('slug', $slug)->delete();
                $msgString = 'Designation 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 ($skillData->employer_id != 0) {
                // echo "hi";
                Skill::where('slug', $slug)->delete();
                $msgString = 'Designation 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 activateDesignation($slug) {
        // $designationData = Skill::where('slug', $slug)->first();
        // if(!empty($designationData)){
        //     Skill::where('slug', $slug)->update([
        //         'status' => 1
        //     ]);
        //     return Response(['response' => "", 'message' => 'Designation activated successfully', 'status' => 200], 200);
        // }
        
        $currentUser = Auth::user()->id;
        $currentUserCheck = Admin::where('id', $currentUser)->first();
        // echo $currentUser;
        if (!empty($currentUserCheck)) {
            $skillData = DB::table('skills')->where('slug', $slug)->first();
            if (!empty($skillData)) {
                DB::table('skills')->where('slug', $slug)->update([
                    'status' => 1
                ]);
                return Response(['response' => "", 'message' => 'Designation activated successfully', 'status' => 200], 200);
            }
        } else {
            // Employer login
            $skill = Skill::where('slug', $slug)->first();
            if (!empty($skill)) {
                if($skill->employer_id == "0"){
                    $employerStatus = $skill->employer_status;

                    // Convert the comma-separated string into an array
                    $employerStatusArray = explode(',', $employerStatus);
    
                    // Check if the user ID is in the array
                    if (($key = array_search($currentUser, $employerStatusArray)) !== false) {
                        // Remove the user ID from the array
                        unset($employerStatusArray[$key]);
    
                        // Convert the array back to a comma-separated string
                        $updatedEmployerStatus = implode(',', $employerStatusArray);
    
                        // Update the qualification's employer status
                        $skill->employer_status = $updatedEmployerStatus;
    
                        // Save the changes to the database
                        $skill->save();
                    }
                } else{
                    $skill->status = 1;
                    $skill->save();
                }
                
            }
        }

        return Response(['response' => '', 'message' => "Designation activated successfully", 'status' => 200], 200);
    }

    public function deactivateDesignation($slug) {
        // $designationData = Skill::where('slug', $slug)->first();
        // if(!empty($designationData)){
        //     Skill::where('slug', $slug)->update([
        //         'status' => 0
        //     ]);
        //     return Response(['response' => "", 'message' => 'Designation deactivated successfully', 'status' => 200], 200);
        // }
        $currentUser = Auth::user()->id;
        $currentUserCheck = Admin::where('id', $currentUser)->first();
        // echo $currentUser;
        if (!empty($currentUserCheck)) {
            $skillData = DB::table('skills')->where('slug', $slug)->first();
            if (!empty($skillData)) {
                DB::table('skills')->where('slug', $slug)->update([
                    'status' => 0
                ]);
                return Response(['response' => "", 'message' => 'Designation deactivated successfully', 'status' => 200], 200);
            }
        } else {
            // Employer login
            $skill = Skills::where('slug', $slug)->first();
            if (!empty($skill)) {
                if($skill->employer_id == "0"){
                   $employerStatus = $skill->employer_status;

                    // Convert the comma-separated string into an array
                    $employerStatusArray = explode(',', $employerStatus);
    
                    // Check if the user ID is in the array
                    if (!in_array($currentUser, $employerStatusArray)) {
                        // Add the user ID to the array
                        $employerStatusArray[] = $currentUser;
    
                        // Convert the array back to a comma-separated string
                        $updatedEmployerStatus = implode(',', $employerStatusArray);
    
                        // Update the qualification's employer status
                        $skill->employer_status = $updatedEmployerStatus;
    
                        // Save the changes to the database
                        $skill->save();
                    } 
                } else{
                    $skill->status = 0;
                    $skill->save();
                }
                
            }
        }
        return Response(['response' => '', 'message' => "Designation deactivated successfully", 'status' => 200], 200);
    }
}
