<?php

namespace App\Http\Controllers\API;

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

class CategoryController extends Controller
{
    //
    public function listing(Request $request) {
        // $category = Category::where('parent_id', 0)->orderBy('id', 'desc')->get();

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

        
        // $categoryData = array();

        // foreach($category as $key => $value) {
        //     $categoryData[$key]['category_id'] = $value->id;
        //     $categoryData[$key]['category_name'] = $value->category_name;
        //     $categoryData[$key]['slug'] = $value->slug;
        //     $categoryData[$key]['status'] = $value->status;
        //     $categoryData[$key]['meta_title'] = $value->meta_title;
        //     $categoryData[$key]['meta_description'] = $value->meta_description;
        //     $categoryData[$key]['meta_keywords'] = $value->meta_keywords;
        //     $categoryData[$key]['meta_keyphrase'] = $value->meta_keyphrase;
        //     $categoryData[$key]['page_header'] = $value->page_header;
        //     $categoryData[$key]['created'] = format_date($value->created_at);
        // }
        // return Response(['response' => $categoryData, '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('categories')->whereIn('id', explode(',', $idList))->update(['status' => '1']);
                    } elseif ($request->action == 'deactivate') {
                        DB::table('categories')->whereIn('id', explode(',', $idList))->update(['status' => '0']);
                    } elseif ($request->action == 'delete') {
                        DB::table('categories')->whereIn('id', explode(',', $idList))->delete();
                    }
                }
            }

            $category = Category::orderBy('id', 'desc')->get();

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

                $categoryData[$key]['category_id'] = $value->id;
                $categoryData[$key]['category_name'] = $value->category_name;
                $categoryData[$key]['employer_name'] = $employerName;
                $categoryData[$key]['slug'] = $value->slug;
                $categoryData[$key]['status'] = $value->status;
                $categoryData[$key]['meta_title'] = $value->meta_title;
                $categoryData[$key]['meta_description'] = $value->meta_description;
                $categoryData[$key]['meta_keywords'] = $value->meta_keywords;
                 $categoryData[$key]['meta_keyphrase'] = $value->meta_keyphrase;
                  $categoryData[$key]['page_header'] = $value->page_header;
                $categoryData[$key]['created'] = format_date($value->created_at);
            }
        } 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('categories')->whereIn('id', explode(',', $idList))->update(['status' => '1']);

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

                        foreach ($categories as $category) {
                            $employerStatus = $category->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('categories')->where('id', $category->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
                        $categories = DB::table('categories')->whereIn('id', explode(',', $idList))->get();

                        foreach ($categories as $category) {
                            $employerStatus = $category->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('categories')->where('id', $category->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
                        $categories = Category::whereIn('id', $idListArray)->get();
                        
                        $systemGeneratedSkills = [];
                        $deletableSkills = [];
                        
                        foreach ($categories as $category) {
                            if ($category->employer_id == 0) {
                                $systemGeneratedSkills[] = $category;
                            } else {
                                $deletableSkills[] = $category->id;
                            }
                        }
                        
                        // Prepare response for system generated skills
                        if (!empty($systemGeneratedSkills)) {
                            $systemGeneratedSkillsDetails = array_map(function ($category) {
                                return [
                                    'id' => $category->id,
                                    'name' => $category->category_name
                                ];
                            }, $systemGeneratedSkills);
                        
                            return Response([
                                'response' => "",
                                'message' => 'You cannot delete system generated category.',
                                '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 category have been successfully deleted.',
                            'status' => 200
                        ], 200);
                    }
                }
            }

            $category = Category::where(function ($query) use ($currentUser) {
                $query->where('employer_id', $currentUser)
                    ->orWhere('employer_id', 0);
                    
            })
            
                ->where('status', 1)
                ->orderBy('id', 'desc')
                ->get();

            $categoryData = array();
            foreach ($category 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);
                
                
                 $categoryData[$key]['category_id'] = $value->id;
                $categoryData[$key]['category_name'] = $value->category_name;
                $categoryData[$key]['employer_id'] = $value->employer_id;
                $categoryData[$key]['employer_status'] = $value->employer_status ;
                $categoryData[$key]['slug'] = $value->slug;
                $categoryData[$key]['status'] = $userPresent ? 0 : 1; // Set status based on user presence
                $categoryData[$key]['meta_title'] = $value->meta_title;
                $categoryData[$key]['meta_description'] = $value->meta_description;
                $categoryData[$key]['meta_keywords'] = $value->meta_keywords;
                 $categoryData[$key]['meta_keyphrase'] = $value->meta_keyphrase;
                  $categoryData[$key]['page_header'] = $value->page_header;
                $categoryData[$key]['created'] = format_date($value->created_at);
            }
        }
        //$qualification = Qualification::orderBy('id','desc')->get();






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

    public function addCategory(Request $request) {
        $validator = Validator::make($request->all(),[
            'category_name' => 'required|unique:categories,category_name',
        ]);
        $validator->setAttributeNames([
            'category_name' => 'Category Name',
        ]);

         if ($validator->fails()) {
            $msg = $this->validatersErrorString($validator->errors());
            return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
        } else {
            $slug = createSlug('categories', $request->category_name);
            $currentUser = Auth::user()->id;
            $currentUserCheck = Admin::where('id', $currentUser)->first();
            // echo $currentUser;
            if (!empty($currentUserCheck)) {
                $category = Category::insert([
                    'category_name' => $request->category_name,
                    'slug' => $slug,
                    'status' => 1,
                    'employer_id' => 0
                ]);
            } else {
                $category = Category::insert([
                    'category_name' => $request->category_name,
                    'slug' => $slug,
                    'status' => 1,
                    'employer_id' => $currentUser
                ]);
            }
            // $category = Category::insert([
            //     'category_name' => $request->category_name,
            //     'slug' => $slug,
            //     'status' => 1,
            //     'cat_id' => 0,
            //     'parent_id' => 0,
            // ]);
            return Response(['response' => $category, 'message' => 'Category added successfully', 'status' => 200], 200);
        }
    }

    public function editCategory(Request $request, $slug) {
        // $existingCategory = Category::where('slug', $slug)->first();

        // if(!empty($request->all())){
        //     $validator = Validator::make($request->all(), [
        //         'category_name' => 'required|unique:categories,category_name,'
        //     ]);    
        //     $validator->setAttributeNames([
        //         'category_name' => 'Category Name',
        //     ]);
        //     if ($validator->fails()) {
        //     $msg = $this->validatersErrorString($validator->errors());
        //     return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
        // } else {
        //         $category = Category::where('id', $existingCategory->id)->update([
        //             'category_name' => $request->category_name,
        //             'slug' => createSlug('categories', $request->category_name),
        //             'status' => 1,
        //             'cat_id' => 0,
        //         ]);
        //         return Response(['response' => $category, 'message' => 'Category updated successfully', 'status' => 200], 200);
        //     }
        // } else {
        //     return Response(['response' => $existingCategory, 'status' => 200], 200);
        // }
        
          $category = Category::where('slug', $slug)->first();
        if (!empty($request->all())) {
            $validator = Validator::make($request->all(), [
                'category_name' => 'required|unique:categories,category_name',
            ]);

            $validator->setAttributeNames([
                'category_name' => 'Category Name',
            ]);

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

                return Response(['response' => $category, 'message' => 'Category updated successfully', 'status' => 200], 200);
            }
        } else {
            return Response(['response' => $category, 'message' => '', 'status' => 200], 200);
        }
    }
    
    public function deleteCategory($slug) {
        // $categoryData = Category::where('slug', $slug)->first();

        // if(!empty($categoryData)) {
        //     Category::where('slug', $slug)->delete();
        //     return Response(['response' => $categoryData, 'message' => 'Category deleted successfully', 'status' => 200], 200);
        // } else{
        //     return Response(['response' => $categoryData, 'message' => 'No record deleted', 'status' => 200], 200);
        // }
        
        $categoryData = Category::where('slug', $slug)->first();

        $currentUser = Auth::user()->id;
        $currentUserCheck = Admin::where('id', $currentUser)->first();
        // echo $currentUser;
        if (!empty($currentUserCheck)) {
            //admin
            if (!empty($categoryData)) {
                Category::where('slug', $slug)->delete();
                $msgString = 'Categories 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 ($categoryData->employer_id != 0) {
                // echo "hi";
                Category::where('slug', $slug)->delete();
                $msgString = 'Categories deleted successfully';
                return Response(['response' => $msgString, 'message' => $msgString, 'status' => 200], 200);
            } else {
                return Response(['response' => "", 'message' => "This is a system generated category and cannot be deleted", 'status' => 500], 200);
            }
        }

    }

    public function activateCategory(Request $request, $slug) {
        // $categorydata = Category::where('slug', $slug)->first();

        // if(!empty($categorydata)) {
        //     Category::where('slug', $slug)->update(['status' => 1]);
        //     return Response(['response' => $categorydata, 'message' => 'Category activated successfully', 'status' => 200], 200);
        // }
        
        $currentUser = Auth::user()->id;
        $currentUserCheck = Admin::where('id', $currentUser)->first();
        // echo $currentUser;
        if (!empty($currentUserCheck)) {
            $categoryData = DB::table('categories')->where('slug', $slug)->first();
            if (!empty($categoryData)) {
                DB::table('categories')->where('slug', $slug)->update([
                    'status' => 1
                ]);
                return Response(['response' => "", 'message' => 'Categories activated successfully', 'status' => 200], 200);
            }
        } else {
            // Employer login
            $category = Category::where('slug', $slug)->first();
            if (!empty($category)) {
                $employerStatus = $category->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
                    $category->employer_status = $updatedEmployerStatus;

                    // Save the changes to the database
                    $category->save();
                }
            }
        }

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

    public function deactivateCategory($slug) {
       $currentUser = Auth::user()->id;
        $currentUserCheck = Admin::where('id', $currentUser)->first();
        // echo $currentUser;
        if (!empty($currentUserCheck)) {
            $categoryData = DB::table('categories')->where('slug', $slug)->first();
            if (!empty($categoryData)) {
                DB::table('categories')->where('slug', $slug)->update([
                    'status' => 0
                ]);
                return Response(['response' => "", 'message' => 'Categories deactivated successfully', 'status' => 200], 200);
            }
        } else {
            // Employer login
            $category = Category::where('slug', $slug)->first();
            if (!empty($category)) {
                $employerStatus = $category->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
                    $category->employer_status = $updatedEmployerStatus;

                    // Save the changes to the database
                    $category->save();
                }
            }
        }
        return Response(['response' => '', 'message' => "Categories deactivated successfully", 'status' => 200], 200);
    }
}
