<?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\Employer;
use App\Models\Admin;
use Illuminate\Support\Facades\Auth;
use App\Models\Industry;

class IndustryController extends Controller
{
    //
    public function listing (Request $request) {
        // $industry = Industry::orderBy('id','desc')->get();

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

        // $industryData = array();

        // foreach($industry as $key => $value) {
        //     $industryData[$key]['industry_id'] = $value->id;
        //     $industryData[$key]['industry_name'] = $value->industry_name;
        //     $industryData[$key]['slug'] = $value->slug;
        //     $industryData[$key]['status'] = $value->status;
        //     $industryData[$key]['created'] = format_date($value->created);
        // }
        // return Response(['response' => $industryData, '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('industries')->whereIn('id', explode(',', $idList))->update(['status' => '1']);
                    } elseif ($request->action == 'deactivate') {
                        DB::table('industries')->whereIn('id', explode(',', $idList))->update(['status' => '0']);
                    } elseif ($request->action == 'delete') {
                        DB::table('industries')->whereIn('id', explode(',', $idList))->delete();
                    }
                }
            }

            $industry = Industry::orderBy('id', 'desc')->get();

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

                $industryData[$key]['industry_id'] = $value->id;
                $industryData[$key]['industry_name'] = $value->industry_name;
                $industryData[$key]['employer_name'] = $employerName;
                $industryData[$key]['slug'] = $value->slug;
                $industryData[$key]['status'] = $value->status;
                $industryData[$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('industries')->whereIn('id', explode(',', $idList))->update(['status' => '1']);

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

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

                        foreach ($industries as $industry) {
                            $employerStatus = $industry->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('industries')->where('id', $industry->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
                        $industries = Industry::whereIn('id', $idListArray)->get();
                        
                        $systemGeneratedSkills = [];
                        $deletableSkills = [];
                        
                        foreach ($industries as $industry) {
                            if ($industry->employer_id == 0) {
                                $systemGeneratedSkills[] = $industry;
                            } else {
                                $deletableSkills[] = $industry->id;
                            }
                        }
                        
                        // Prepare response for system generated skills
                        if (!empty($systemGeneratedSkills)) {
                            $systemGeneratedSkillsDetails = array_map(function ($industry) {
                                return [
                                    'id' => $industry->id,
                                    'name' => $industry->industry_name
                                ];
                            }, $systemGeneratedSkills);
                        
                            return Response([
                                'response' => "",
                                'message' => 'You cannot delete system generated industries.',
                                'system_generated_skills' => $systemGeneratedSkillsDetails,
                                'status' => 500
                            ], 200);
                        }
                        
                        // Delete only the skills that can be deleted
                        Industry::whereIn('id', $deletableSkills)->delete();
                        
                        return Response([
                            'response' => "",
                            'message' => 'Selected Industries have been successfully deleted.',
                            'status' => 200
                        ], 200);
                    }
                }
            }

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

            $industryData = array();
            foreach ($industry 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);

                $industryData[$key]['industry_id'] = $value->id;
                $industryData[$key]['industry_name'] = $value->industry_name;
                $industryData[$key]['employer_id'] = $value->employer_id;
                $industryData[$key]['slug'] = $value->slug;
                $industryData[$key]['employer_status'] = $value->employer_status;
                $industryData[$key]['status'] = $userPresent ? 0 : 1; // Set status based on user presence
                $industryData[$key]['created'] = format_date($value->created_at);
            }
        }
        //$qualification = Qualification::orderBy('id','desc')->get();






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

    public function addIndustry(Request $request) {
        $validator = Validator::make($request->all(), [
            'industry_name' => 'required|unique:industries,industry_name',
        ]);
        $validator->setAttributeNames([
            'industry_name' => 'Industry Name',
        ]);
        // 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 {
            $slug = Str::slug($request->industry_name);
             $currentUser = Auth::user()->id;
            $currentUserCheck = Admin::where('id', $currentUser)->first();
            // echo $currentUser;
            if (!empty($currentUserCheck)) {
                $industry = Industry::insert([
                    'industry_name' => $request->industry_name,
                    'slug' => $slug,
                    'status' => 1,
                    'employer_id' => 0
                ]);
            } else {
                $industry = Industry::insert([
                    'industry_name' => $request->industry_name,
                    'slug' => $slug,
                    'status' => 1,
                    'employer_id' => $currentUser
                ]);
            }
            // $industry = Industry::insert([
            //     'industry_name' => $request->industry_name,
            //     'slug' => $slug,
            //     'status' => 1,
            // ]);
            return Response(['response' => $industry, 'message' => 'Industry added successfully', 'status' => 200], 200);
        }
    }

    public function editIndustry(Request $request, $slug) {
        // $existingIndustry = Industry::where('slug', $slug)->first();

        // if(!empty($request->all())){
        //     $validator = Validator::make($request->all(), [
        //         'industry_name' => 'required|unique:industries,industry_name,'
        //     ]);    
        //     $validator->setAttributeNames([
        //         'industry_name' => 'Industry Name',
        //     ]);
        //     // 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 {
                
        //             $industry = Industry::where('slug', $request->slug)->update([
        //             'industry_name' => $request->industry_name,
        //             'slug' => Str::slug($request->industry_name),
        //         ]);
        //         return Response(['response' => $industry, 'message' => 'Industry updated successfully', 'status' => 200], 200);
        //     }
        // } else {
        //     return Response(['response' => $existingIndustry, 'status' => 200], 200);
        // }
        
        $industry = Industry::where('slug', $slug)->first();
        if (!empty($request->all())) {
            $validator = Validator::make($request->all(), [
                'industry_name' => 'required|unique:industries,industry_name',
            ]);

            $validator->setAttributeNames([
                'industry_name' => 'Industry Name',
            ]);

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

                return Response(['response' => $industry, 'message' => 'Industry updated successfully', 'status' => 200], 200);
            }
        } else {
            return Response(['response' => $industry, 'message' => '', 'status' => 200], 200);
        }
    }

    public function deleteIndustry($slug) {
    //     $industryData = Industry::where('slug',$slug)->first();

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

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

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

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

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

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

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