<?php

namespace App\Http\Controllers\API;

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


class SkillsController extends Controller
{
    //
    public function listing (Request $request) {
        // $skill = Skill::where('type', 'Skill')->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();
                   
        //         }
        //     }
        // }

        // $skillData = array();

        // foreach($skill as $key => $value) {
        //     $skillData[$key]['skill_id'] = $value->id;
        //     $skillData[$key]['skill_name'] = $value->skill_name;
        //     $skillData[$key]['slug'] = $value->slug;
        //     $skillData[$key]['status'] = $value->status;
        //     $skillData[$key]['created'] = format_date($value->created);
        // }
        // return Response(['response' => $skillData, 'status' => 200], 200);
        
         
        $currentUser = Auth::user()->id;
        $currentUserCheck = Admin::where('id', $currentUser)->first();
        // 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::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]['skill_id'] = $value->id;
                $skillData[$key]['skill_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) {
                            $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]);
                            }
                        }
                    } 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
                        $qualifications = DB::table('skills')->whereIn('id', explode(',', $idList))->get();

                        foreach ($skills as $skill) {
                            $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]);
                            }
                        }
                    } 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',"Skill")
                ->where('status', 1)
                ->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]['skill_id'] = $value->id;
                $skillData[$key]['skill_name'] = $value->skill_name;
                $skillData[$key]['type'] = $value->type;
                $skillData[$key]['slug'] = $value->slug;
                $skillData[$key]['employer_status'] = $value->employer_status;
                $skillData[$key]['status'] = $userPresent ? 0 : 1; // Set status based on user presence
                $skillData[$key]['created'] = format_date($value->created);
            }
        }
        //$qualification = Qualification::orderBy('id','desc')->get();






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

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

        //         return Response(['response' => $skill, 'message' => 'Skill updated successfully', 'status' => 200], 200);
        //     }
        // } else {
        //     return Response(['response' => $existingSkill, 'status' => 200], 200);
        // }
        $skill = 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' => 'Skill 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' => 'Skills updated successfully', 'status' => 200], 200);
            }
        } else {
            return Response(['response' => $skill, 'message' => '', 'status' => 200], 200);
        }
    }

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

    //   if(!empty($skillData)){
    //         Skill::where('slug',$slug)->delete();
    //         $msgString = 'Skill 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 = 'Skills 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 = 'Skills 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 activateSkill($slug) {
        // $skillData = Skill::where('slug', $slug)->first();
        // if(!empty($skillData)){
        //     Skill::where('slug', $slug)->update([
        //         'status' => 1
        //     ]);
        //     return Response(['response' => "", 'message' => 'Skill 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' => 'Skills activated successfully', 'status' => 200], 200);
            }
        } else {
            // Employer login
            $skill = Skill::where('slug', $slug)->first();
            if (!empty($skill)) {
                $employerStatus = $qualification->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();
                }
            }
        }

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

    public function deactivateSkill($slug) {
        // $skillData = Skill::where('slug', $slug)->first();
        // if(!empty($skillData)){
        //     Skill::where('slug', $slug)->update([
        //         'status' => 0
        //     ]);
        //     return Response(['response' => "", 'message' => 'Skill 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' => 'Skills deactivated successfully', 'status' => 200], 200);
            }
        } else {
            // Employer login
            $skill = Skills::where('slug', $slug)->first();
            if (!empty($skill)) {
                $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();
                }
            }
        }
        return Response(['response' => '', 'message' => "Skills deactivated successfully", 'status' => 200], 200);
    }
}
