<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Ticket\Category;
use App\Models\Ticket\Ticket;
use Auth;
use DB;
use App\Models\Projects;
use App\Models\Groups;
use App\Models\User;
use App\Models\Subcategory;
use App\Models\Subcategorychild;
use Illuminate\Support\Facades\Validator;
use Response;
use Str;
use App\Entities\CategoryEnvato;
use App\Models\tickethistory;
use Mail;
use App\Mail\mailmailablesend;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Role;
use laravelLara\infoinst\Jobs\MailSend;
use Jenssegers\Agent\Agent;
use Torann\GeoIP\Facades\GeoIP;
use App\Models\EmployeeActivity;
use App\Models\Groupscategories;
use App\Events\ConversationEvent;
use Illuminate\Support\Facades\Log;

class CategoriesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->authorize('Category Access');

        // $categories = DB::table('categories')->get();
        // $data['categories'] = $categories;

        $categories = Category::with('groupscategoryc');
        $searchTerm = $request['filter'] ?? null;
        $perPage    = $request['per_page'] ?? 15;
        $page       = $request['page'] ?? 1;


        if ($searchTerm) {
            $categories->where(function ($query) use ($searchTerm) {
                $columns = Schema::getColumnListing('categories');
                foreach ($columns as $column) {
                    $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                }
                $query->orWhereHas('groupscategoryc', function ($query) use ($searchTerm) {
                    $query->where('name', 'LIKE', $searchTerm . '%');
                });
            });
        }
        $items = $categories->paginate($perPage);
        $data['categories'] = $items;


        $user = User::with('usetting')->findOrFail(Auth::user()->id);
        $role = Role::where('name', $user->getRoleNames()[0])->get();
        foreach ($role as $roles) {
            $data['permissions'] = $roles->getPermissionNames();
        }
        $data['setting'] = response()->json([
            'ENVATO_ON' => setting('ENVATO_ON'),
            'cc_email' => setting('cc_email'),
            'FILE_UPLOAD_MAX' => setting('FILE_UPLOAD_MAX'),
            'MAX_FILE_UPLOAD' => setting('MAX_FILE_UPLOAD'),
            'FILE_UPLOAD_TYPES' => setting('FILE_UPLOAD_TYPES'),
            'TICKET_CHARACTER' => setting('TICKET_CHARACTER')
        ]);
        return $data;
    }

    public function totalcategorylist()
    {
        $categories = Category::with('groupscategoryc')->where('status', '!=', '0')->get();
        $data['categories'] = $categories;
        return $data;
    }

    public function status(Request $request, $id)
    {
        $calID = Category::find($id);
        $calID->status = $request->status;
        $calID->save();

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Changed status of category';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['code' => 200, 'success' => 'Updated successfully'], 200);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'display' => 'required|in:both,all,ticket,knowledge,emailToTicket',

        ]);

        if ($validator->passes()) {


            $testiId = $request->testimonial_id;
            $categoryfind = Category::find($testiId);
            if ($categoryfind) {
                if ($categoryfind->categoryslug == null) {

                    $testi =  [
                        'name' => $request->name,
                        'display' => $request->display,
                        'priority' => $request->priority,
                        'categoryslug' => Str::slug($request->name, '-'),
                        'status' => $request->status ?  '1' :  '0',
                    ];
                }
                if ($categoryfind->categoryslug != null) {

                    $testi =  [
                        'name' => $request->name,
                        'display' => $request->display,
                        'priority' => $request->priority,
                        'status' => $request->status ?  '1' :  '0',
                    ];
                }
            }
            if (!$categoryfind) {
                $testi =  [
                    'name' => $request->name,
                    'display' => $request->display,
                    'priority' => $request->priority,
                    'categoryslug' => Str::slug($request->name, '-'),
                    'status' => $request->status ?  '1' :  '0',
                ];
            }



            $testimonial = Category::updateOrCreate(['id' => $testiId], $testi);

            $subcatexists = \App\Models\Subcategorychild::where('category_id', $testimonial->id)->first();
            $categoriesData = [
                'category_id' => $testimonial->id,
                'subcatexists' => $subcatexists
            ];
            $testimonial->categoriesData = $categoriesData;


            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = $testiId ? 'updated a ctegory.' : 'Created a category';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();
            $message = $testiId ? 'Category updated successfully.' : 'Category created successfully.';
            return response()->json(['code' => 200, 'success' => $message, 'data' => $testimonial], 200);
        } else {
            return Response::json(['errors' => $validator->errors()], 500);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $this->authorize('Category Edit');
        $post = Category::find($id);

        $data = [
            'post' => $post,
        ];
        return response()->json($data);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $this->authorize('Category Edit');
        $categories = Category::where('id', $id)->findOrFail();
        $data['categories'] = $categories;


        return $data;
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'catogorynam' => 'required|string|max:255',

        ]);
        $Category = Category::findOrFail($id);

        $Category->name = $request->input('catogorynam');
        $Category->update();

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated category';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['code' => 200, 'success' => 'The category was successfully updated.'], 200);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $this->authorize('Category Delete');
        $Category = Category::findOrFail($id);

        $Category->delete();

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Deleted a category' . $Category->id;
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => 'The category was successfully deleted.']);
    }


    public function agentshow(Request $req, $id)
    {
        $output = '';

        $assign = Category::find($id);

        $group = User::leftJoin('groups_users', 'users.id', 'groups_users.users_id')
            ->leftJoin('groups_categories', 'groups_users.groups_id', 'groups_categories.group_id')
            ->where('groups_categories.category_id', $id)->first();

        if ($group != null) {
            $data = User::leftJoin('groups_users', 'users.id', 'groups_users.users_id')
                ->leftJoin('groups_categories', 'groups_users.groups_id', 'groups_categories.group_id')
                ->whereNull('groups_categories.category_id')->get();
        } else {
            $data = User::leftJoin('groups_users', 'users.id', 'groups_users.users_id')
                ->leftJoin('groups_categories', 'groups_users.groups_id', 'groups_categories.group_id')
                ->whereNull('groups_categories.category_id')->get();
        }



        $total_row = $data->count();

        $cat = DB::table("category_category_user")->where("category_category_user.category_id", $id)
            ->pluck('category_category_user.category_user_id', 'category_category_user.category_user_id')
            ->all();

        if ($total_row > 0) {
            foreach ($data as $row) {


                $output .= '

                    <option  value="' . $row->id . '" ' . ($row->id  ? in_array($row->id, $cat) ?  'selected' : '' : '') . '>' . $row->name . ' ' . (!empty($row->getRoleNames()[0]) ? $row->getRoleNames()[0] : '') . '</option>

                    ';
            }
        }
        $data = array(
            'assign_data' => $assign,
            'table_data' => $output,
            'total_data' => $total_row,
            'data' => $cat
        );
    }


    public function agentshowcreate(Request $request)
    {

        $data =  $request->assigned_id;
        $cat = Category::find($data);
        $cat->update($request->only(['assigned_name']));

        if ($request->input('assigned_user_id')) {
            foreach ($request->input('assigned_user_id') as $value) {
                $assigned_user_id[] = $value;
            }
        }

        $cat->catagent()->sync($request->get('assigned_user_id'));

        return response()->json(['success' => 'Updated successfully']);
    }


    public function groupshow(Request $req, $id)
    {

        $output = [];

        $assign = Category::find($id);

        $data = Groups::get();

        $total_row = $data->count();

        $cat = DB::table("groups_categories")->where("groups_categories.category_id", $id)
            ->pluck('groups_categories.group_id', 'groups_categories.group_id')
            ->all();



        if ($total_row > 0) {
            foreach ($data as $row) {
                array_push($output, $row);
            }
        }
        $data = array(
            'assign_data' => $assign,
            'table_data' => $output,
            'total_data' => $total_row,
            'data' => [...$cat]
        );
        return response()->json($data);
    }

    public function categorygroupassign(Request $request)
    {

        $data =  $request->category_id;
        $cat = Category::find($data);
        $cat->update($request->only(['category_name']));

        $categoryId = $cat->id;
        $groups_categories = Groupscategories::where('category_id', $categoryId)
            ->whereNotExists(function ($query) use ($categoryId) {
                $query->select(DB::raw(1))
                    ->from('groups_categories as gc2')
                    ->whereRaw('gc2.group_id = groups_categories.group_id')
                    ->where('gc2.category_id', '!=', $categoryId);
            })
            ->get();
        foreach ($groups_categories as $group) {
            $group = Groups::find($group->group_id);
            $group->update(['groupstatus' => 0]);
        }

        if ($request->input('group_id')) {
            foreach ($request->input('group_id') as $value) {
                $group = Groups::find($value);
                $group->update(['groupstatus' => 1]);
                $group_id[] = $value;
            }
        }

        $cat->groupscategory()->sync($request->get('group_id'));
        $updatedCategory = Category::with('groupscategoryc')->find($categoryId);

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Category assigned to group.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => 'Updated successfully', 'updatedData' => $updatedCategory]);
    }


    /// category list

    public function categorylist(Request $req, $ticket_id)
    {

        $output = '';
        $category = Category::whereIn('display', ['ticket', 'all'])->where('status', '1')->get();

        $totalrow = $category->count();
        $ticket = DB::table('tickets')->where('ticket_id', $ticket_id)->first();
        $envatoassignstatus = null;
        if ($ticket->category_id != null) {
            $envatocat = Category::find($ticket->category_id);
            if ($envatocat != null) {
                $envatoassigncat = $envatocat->envato->first();
                if ($envatoassigncat != null) {
                    $envatoassignstatus = 'assignedtoenvato';
                } else {
                    $envatoassignstatus = null;
                }
            } else {
                $envatoassignstatus = null;
            }
        }
        if ($totalrow > 0) {
            $output .= '<option label="Select Category"></option>';
            foreach ($category as $categories) {
                $output .= '
                    <option  value="' . $categories->id . '"' . ($categories->id == $ticket->category_id ? 'selected' : '') . '>' . $categories->name . '</option>
                    ';
            }
        } else {
            $output .= '
                <option label="No Data Found"></option>
                ';
        }

        $projectoutput = '';
        $projects = Projects::get();
        if ($projects->count() > 0) {
            foreach ($projects as $project) {
                $projectoutput .= '<option  value="' . $project->name . '"' . ($project->name == $ticket->project ? 'selected' : '') . '>' . $project->name . '</option>';
            }
        } else {
            $projectoutput .= '
                <option label="No Data Found"></option>
                ';
        }

        $subcategory = '';
        $ticket1 = DB::table('tickets')->where('ticket_id', $ticket_id)->first();
        $category1 = Subcategorychild::where('category_id', $ticket1->category_id)->get();

        $myArray = [];
        $totalrow1 = $category1->count();
        if ($totalrow1 > 0) {
            $subcategory .= '<option label="Select Category"></option>';
            foreach ($category1 as $categories) {

                foreach ($categories->subcatlists()->where('status', '1')->get() as $subcategorylist) {
                    $myArray[] = $subcategorylist;
                    $subcategory .= '
                        <option  value="' . $subcategorylist->id . '"' . ($subcategorylist->id == $ticket1->subcategory ? 'selected' : '') . '>' . $subcategorylist->subcategoryname . '</option>
                        ';
                }
            }
        }

        $data = array(
            'subCatStatus' => $myArray,
            'table_data' => $output,
            'total_data' => $totalrow,
            'ticket' => $ticket,
            'projectop' => $projectoutput,
            'subcategoryt' => $subcategory,
            'envatoassignstatus' => $envatoassignstatus,
        );
        return response()->json($data, 200);
    }


    public function categorychange(Request $req)
    {
        $this->validate($req, [
            'category' => 'required',
        ]);

        $ticketcategory = Ticket::find($req->ticket_id);
        if ($ticketcategory->category_id != null && $ticketcategory->category_id == $req->category && $ticketcategory->subcategory == $req->subscategory) {
            return response()->json(['error' => 'you are not change anything if you want update it change anything.'], 500);
        }

        if ($ticketcategory->category_id == null) {
            $oldcategoryName = '';
        } else {
            //old category name
            $oldcategory = Category::find($ticketcategory->category_id);
            $oldcategoryName = $oldcategory->name;
        }
        $ticketcategory->category_id = $req->category;
        $ticketcategory->project = $req->project;
        $ticketcategory->subcategory = $req->subscategory;
        $categories = CategoryEnvato::where('category_id', $req->category)->first();
        if ($req->envato_id && $categories) {
            $ticketcategory->purchasecode = encrypt($req->envato_id);
            $ticketcategory->purchasecodesupport = $req->envato_support;
            if ($req->productname) {
                $ticketcategory->item_name = $req->productname;
            }
        } else {
            // $ticketcategory->purchasecode = null;
            // $ticketcategory->purchasecodesupport = null;
            // $ticketcategory->item_name = null;
        }

        $findcat = Category::find($req->category);
        // new category or changed category
        $changedcategory = $findcat->name;
        $ticketcategory->priority = $findcat->priority;
        $ticketcategory->update();

        $tickethistory = new tickethistory();
        $tickethistory->ticket_id = $ticketcategory->id;

        $tickethistory->ticketnote = $ticketcategory->ticketnote->isNotEmpty();
        $tickethistory->ticketviolation = $ticketcategory->ticketviolation;
        $tickethistory->overduestatus = $ticketcategory->overduestatus;
        $tickethistory->status = $ticketcategory->status;
        $tickethistory->replystatus = $ticketcategory->replystatus;
        $tickethistory->currentAction = 'Category Updated';
        $tickethistory->username = Auth::user()->name;
        $tickethistory->type = Auth::user()->getRoleNames()[0];
        $tickethistory->assignUser = null;
        $tickethistory->save();


        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated Category for Ticket SPG-' . $tickethistory->ticket_id;
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        $ticketData = [
            'ticket_username' => $ticketcategory->cust->username,
            'ticket_id' => $ticketcategory->ticket_id,
            'ticket_title' => $ticketcategory->subject,
            'ticket_description' => $ticketcategory->message,
            'ticket_status' => $ticketcategory->status,
            'ticket_oldcategory' => $oldcategoryName,
            'ticket_changedcategory' => $changedcategory,
            'ticket_customer_url' => url('/customer/ticket-view/' . encrypt($ticketcategory->ticket_id)),
            'ticket_admin_url' => url('/admin/ticket-view/' . encrypt($ticketcategory->ticket_id)),
            'ticket_category' => $ticketcategory->category->name,
            'status' => $ticketcategory->status

        ];


        $ticketInfo = Ticket::with('category', 'subcategoriess')->find($req->ticket_id);
        $ticket_changedcategory = $changedcategory;

        try {

            $notificationcatss = $ticketcategory->category->groupscategoryc()->get();
            $icc = array();
            if ($notificationcatss->isNotEmpty()) {

                foreach ($notificationcatss as $igc) {

                    foreach ($igc->groupsc->groupsuser()->get() as $user) {
                        $icc[] .= $user->users_id;
                    }
                }

                if (!$icc) {
                    $admins = User::leftJoin('groups_users', 'groups_users.users_id', 'users.id')->whereNull('groups_users.groups_id')->whereNull('groups_users.users_id')->where('status', 1)->get();
                    foreach ($admins as $admin) {
                        if ($admin->getRoleNames()[0] != 'superadmin' && $admin->usetting->emailnotifyon == 1) {
                            dispatch((new MailSend($admin->email, 'send_mail_admin_panel_users_when_category_changed', $ticketData)));
                        }
                    }
                } else {
                    if ($ticketcategory->myassignuser) {
                        $assignee = $ticketcategory->ticketassignmutliples;
                        foreach ($assignee as $assignees) {
                            $user = User::where('id', $assignees->toassignuser_id)->where('status', 1)->get();
                            foreach ($user as $users) {
                                if ($users->id == $assignees->toassignuser_id && $users->getRoleNames()[0] != 'superadmin' && $users->usetting->emailnotifyon == 1) {
                                    dispatch((new MailSend($users->email, 'send_mail_admin_panel_users_when_category_changed', $ticketData)));
                                }
                            }
                        }
                    } else if ($ticketcategory->selfassignuser_id) {
                        $self = User::findOrFail($ticketcategory->selfassignuser_id);
                        if ($self->getRoleNames()[0] != 'superadmin' && $self->usetting->emailnotifyon == 1) {
                            dispatch((new MailSend($self->email, 'send_mail_admin_panel_users_when_category_changed', $ticketData)));
                        }
                    } else if ($icc) {
                        $user = User::whereIn('id', $icc)->where('status', 1)->get();
                        foreach ($user as $users) {
                            if ($users->usetting->emailnotifyon == 1) {
                                dispatch((new MailSend($users->email, 'send_mail_admin_panel_users_when_category_changed', $ticketData)));
                            }
                        }
                    } else {
                        foreach (usersdata() as $user) {
                            if ($user->getRoleNames()[0] != 'superadmin' && $user->usetting->emailnotifyon == 1) {
                                dispatch((new MailSend($user->email, 'send_mail_admin_panel_users_when_category_changed', $ticketData)));
                            }
                        }
                    }
                }
            } else {
                if ($ticketcategory->myassignuser) {
                    $assignee = $ticketcategory->ticketassignmutliples;
                    foreach ($assignee as $assignees) {
                        $user = User::where('id', $assignees->toassignuser_id)->where('status', 1)->get();
                        foreach ($user as $users) {
                            if ($users->id == $assignees->toassignuser_id && $users->getRoleNames()[0] != 'superadmin' && $users->usetting->emailnotifyon == 1) {
                                dispatch((new MailSend($users->email, 'send_mail_admin_panel_users_when_category_changed', $ticketData)));
                            }
                        }
                    }
                } else if ($ticketcategory->selfassignuser_id) {
                    $self = User::findOrFail($ticketcategory->selfassignuser_id);
                    if ($self->getRoleNames()[0] != 'superadmin' && $self->usetting->emailnotifyon == 1) {
                        dispatch((new MailSend($self->email, 'send_mail_admin_panel_users_when_category_changed', $ticketData)));
                    }
                } else {
                    foreach (usersdata() as $user) {
                        if ($user->getRoleNames()[0] != 'superadmin' && $user->usetting->emailnotifyon == 1) {
                            dispatch((new MailSend($user->email, 'send_mail_admin_panel_users_when_category_changed', $ticketData)));
                        }
                    }
                }
            }

            foreach (usersdata() as $admin) {
                if ($admin->getRoleNames()[0] == 'superadmin' && $admin->usetting->emailnotifyon == 1) {
                    dispatch((new MailSend($admin->email, 'send_mail_admin_panel_users_when_category_changed', $ticketData)));
                }
            }

            if ($ticketcategory->tickettype != 'emalitoticket') {
                dispatch((new MailSend($ticketcategory->cust->email, 'send_mail_customer_when_category_changed', $ticketData)));
            }
        } catch (\Exception $e) {
            return response()->json(['success' => 'Updated successfully']);
        }

        return response()->json(['success' => 'Updated successfully']);
    }

    public function categorylistshow(Request $request)
    {
        $data['category'] = Category::all();
        $data['categoryenvato'] = CategoryEnvato::pluck('category_id')->toArray();
        return $data;
    }

    public function categoryenvatoassign(Request $r)
    {

        if ($r->input('categorys_id') != null) {

            $categories = CategoryEnvato::get();

            foreach ($categories as $category) {

                $category->truncate();
            }
            foreach ($r->input('categorys_id') as $value) {

                $category = CategoryEnvato::create([
                    'category_id' => $value,
                    'envato_enable' => '1'
                ]);
            }
        } else {

            $categories = CategoryEnvato::get();

            foreach ($categories as $category) {

                $category->truncate();
            }
        }

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Category assigned to Envato API.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => 'Updated successfully', 200]);
    }

    public function subcategoryindex(Request $request)
    {

        $user = User::with('usetting')->findOrFail(Auth::user()->id);
        $role = Role::where('name', $user->getRoleNames()[0])->get();
        foreach ($role as $roles) {
            $data['permissions'] = $roles->getPermissionNames();
        }

        $subcategory = Subcategory::with('subcategorylist');

        $searchTerm = $request['filter'] ?? null;
        $perPage    = $request['per_page'] ?? 15;
        $page       = $request['page'] ?? 1;

        if ($searchTerm) {
            $subcategory->where(function ($query) use ($searchTerm) {
                $columns = Schema::getColumnListing('subcategorysd');
                foreach ($columns as $column) {
                    $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                }
            });
        }
        $items = $subcategory->paginate($perPage);
        $data['subcategory'] = $items;

        $category = Category::get();
        $data['category'] = $category;

        return $data;
    }

    public function categorygetall(Request $request)
    {
        $categoryall = Category::where('status', 1)->get();

        $output = '';
        if ($categoryall != '') {
            $output .= '<option label="No Parent"></option>';
            foreach ($categoryall as $catall) {
                $output .= '<option value="' . $catall->id . '">' . $catall->name . ' </option>';
            }
        }
        return response()->json($output);
    }

    public function subcategorystore(Request $request)
    {
        $validate = Subcategory::find($request->subcategory_id);

        if (!$validate) {
            $validator = Validator::make($request->all(), [
                'subcategoryname' => 'required|string|max:255|unique:subcategorysd',

            ]);
        }
        if ($validate) {
            if ($validate->subcategoryname == $request->subcategoryname) {
                $validator = Validator::make($request->all(), [
                    'subcategoryname' => 'required|string|max:255',

                ]);
            } else {
                $validator = Validator::make($request->all(), [
                    'subcategoryname' => 'required|string|max:255|unique:subcategorysd',

                ]);
            }
        }

        if ($validator->passes()) {

        $testiId = $request->subcategory_id;
        $testi =  [
            'subcategoryname' => $request->subcategoryname,
            'status' => $request->status ?  '1' :  '0',
        ];
        $testimonial = Subcategory::updateOrCreate(['id' => $testiId], $testi);

        if ($request->parent_id) {
            foreach ($request->parent_id as $value) {
                $parent_id[] = $value;
            }
        }

        $testimonial->subcategorysync()->sync($request->get('parent_id'));
        $updatedTestimonial = Subcategory::with('subcategorylist.subcatlistss')->find($testimonial->id);

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = $testiId ? 'Updated SubCategory.' : 'Created Subcategory';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        $message = $testiId ? 'subcategory updated successfully.' : 'subcategory created successfully.';
        return response()->json(['code' => 200, 'success' => $message, 'data' => $updatedTestimonial], 200);
        }else{
            return response()->json(['errors' => $validator->errors()]);
        }
    }

    public function subcategoryshow($id)
    {
        $subcategory = Subcategory::find($id);

        $categoryall = Category::get();

        $categoryArray = Subcategorychild::where("subcategory_id", $id)->pluck('category_id')->toArray();


        $output = '';
        if ($categoryall != '') {
            $output .= '<option label="No Parent"></option>';
            foreach ($categoryall as $catall) {
                $output .= '<option value="' . $catall->id . '"' . ($catall->id  ? in_array($catall->id, $categoryArray) ?  'selected' : '' : '') . '>' . $catall->name . ' </option>';
            }
        }
        $data = [
            'subcategory' => $subcategory,
            'categorylist' => $output
        ];
        return response()->json($data);
    }

    public function subcategorystatusupdate(Request $request)
    {
        $subcategorystatus = Subcategory::find($request->id);
        $subcategorystatus->status = $request->status;
        $subcategorystatus->update();
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Updated SubCategory status.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json([$subcategorystatus, 'success' => 'Updated successfully'], 200);
    }

    public function subcategorydelete(Request $request)
    {
        $subcategorydelete = Subcategory::find($request->id);
        $subcategorydelete->delete();
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Deleted SubCategory.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json([$subcategorydelete, 'success' => 'Deleted successfully'], 200);
    }


    public function categorymassdestroy(Request $request)
    {
        $category_id_array = $request->input('id');

        $articles = Category::whereIn('id', $category_id_array)->get();

        foreach ($articles as $article) {

            $article->delete();
        }
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Deleted multiple categories';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json(['success' => 'The category was successfully deleted.']);
    }


    public function subcategorydeleteall(Request $request)
    {
        $subcategory_id_array = $request->input('id');

        $subcats = Subcategory::whereIn('id', $subcategory_id_array)->get();

        foreach ($subcats as $subcat) {

            $subcat->delete();
        }

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Deleted multiple subcategories';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json(['success' => 'The subcategory was successfully deleted.']);
    }

    public function selfassign(Request $request)
    {
        $request->id = decrypt($request->id);
        $ticketselfassign = Ticket::find($request->id);
        $ticketselfassign->selfassignuser_id = Auth::id();
        $ticketselfassign->myassignuser_id = null;
        $ticketselfassign->update();
        $ticketselfassign->ticketassignmutliple()->detach($request->assigned_userid);
        $tickethistory = new tickethistory();
        $tickethistory->ticket_id = $ticketselfassign->id;

        $tickethistory->ticketnote = $ticketselfassign->ticketnote->isNotEmpty();
        $tickethistory->ticketviolation = $ticketselfassign->ticketviolation;
        $tickethistory->overduestatus = $ticketselfassign->overduestatus;
        $tickethistory->status = $ticketselfassign->status;
        $tickethistory->replystatus = $ticketselfassign->replystatus;
        $tickethistory->currentAction = 'Self Assigned';
        $tickethistory->username = Auth::user()->name;
        $tickethistory->assigned_date = today();
        $tickethistory->assigned_time = now();
        $tickethistory->type = Auth::user()->getRoleNames()[0];
        $tickethistory->assignUser = null;
        $tickethistory->save();


        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Self assigned a ticket ';
        $activity->ticket_id = $tickethistory->ticket_id;
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        if (webSocketCheck()) {
            try {
                event(new \App\Events\ConversationEvent(dbname(), null, null, null, null, null, 'tableDataReload', null));
                event(new ConversationEvent(dbname(), null, null,  Auth::user()->id, null, null, 'selfAsssigned', $ticketselfassign->ticket_id, 'null'));
            } catch (\Exception $e) {
                Log::error('Error dispatching WebSocket event: ' . $e->getMessage());
            }
        }

        return response()->json(['success' => 'Updated successfully', 200]);
    }
}
