<?php

namespace App\Http\Controllers\Admin;

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

use Auth;
use App\Models\Ticket\Comment;
use App\Models\Ticket\Category;
use App\Models\Subcategorychild;
use App\Mail\AppMailer;
use App\Models\Customer;
use App\Models\User;
use App\Models\Apptitle;
use App\Models\Footertext;
use App\Models\Seosetting;
use App\Models\Pages;
use Illuminate\Support\Facades\Validator;
use DB;
use Mail;
use App\Mail\mailmailablesend;
use App\Models\Ticketnote;
use App\Models\Projects;
use App\Notifications\TicketCreateNotifications;
use App\Models\CustomerSetting;
use App\Models\Groupsusers;
use Str;
use App\Entities\Cannedmessages;
use App\Entities\CategoryEnvato;
use App\Models\Customfield;
use App\Models\TicketCustomfield;
use App\Models\CCMAILS;
use App\Models\Groups;
use App\Models\Ticket\Ticket;
use App\Models\tickethistory;
use Spatie\Permission\Models\Role;
use File;
use Illuminate\Support\Facades\Schema;
use App\Models\Holiday;
use Carbon\Carbon;
use App\Models\TicketDraft;
use App\Models\Ticketviolation;
use laravelLara\infoinst\Jobs\MailSend;
use Jenssegers\Agent\Agent;
use Torann\GeoIP\Facades\GeoIP;
use App\Models\EmployeeActivity;
use App\Events\ConversationEvent;
use Illuminate\Support\Facades\Log;
use App\Notifications\TicketAssignNotification;

class AdminTicketController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $tickets = Ticket::paginate();
        $categories = Category::all();

        return '';
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request, $ticket_id)
    {
        $this->authorize('Ticket Edit');
        $ticket_id = decrypt($ticket_id);
        $ticket = Ticket::where('ticket_id', $ticket_id)->first();
        if (!$ticket) {
            return response(['noticket' => 'There was no ticket with ' . $ticket_id]);
        }

        $usersRoles  = $ticket->users;
        $selfassignRoles = $ticket->selfassign;
        $myassignuserRoles = $ticket->myassignuser;
        $closedusersRoles = $ticket->closedusers;
        if ($usersRoles) {
            $usersRoles  = $ticket->users->roles;
            $data['usersRoles'] = $usersRoles;
        }
        if ($selfassignRoles) {
            $selfassignRoles  = $ticket->selfassign->roles;
            $data['selfassignRoles'] = $selfassignRoles;
        }
        if ($myassignuserRoles) {
            $myassignuserRoles  = $ticket->myassignuser->roles;
            $data['myassignuserRoles'] = $myassignuserRoles;
        }
        if ($closedusersRoles) {
            $closedusersRoles  = $ticket->closedusers->roles;
            $data['closedusersRoles'] = $closedusersRoles;
        }

        $ticket = Ticket::with('cust', 'selfassign', 'closedusers', 'ticketassignmutliples', 'myassignuser', 'ticket_customfield', 'toassignuser', 'users', 'ticketnote', 'subcategoriess', 'category', 'ticketviolation')->where('ticket_id', $ticket_id)->firstOrFail();

        $data['ticket'] = $ticket;
        $assignee = $ticket->ticketassignmutliples;

        $ticketassignmutliples = [];
        foreach ($assignee as $assignees) {
            $assine = $assignees->toassignuser;
            $assine['role'] = $assignees->toassignuser->getRoleNames()[0];
            array_push($ticketassignmutliples, $assine);
        }

        $data['ticketassignmutliples'] = $ticketassignmutliples;

        $custsimillarticket = Ticket::where('cust_id', $ticket->cust->id)->count();
        $data['custsimillarticket'] = $custsimillarticket;

        $data['allowreply'] = false;

        $finalassigne = [];
        $assignee = $ticket->ticketassignmutliples;
        foreach ($assignee as $assignees) {
            array_push($finalassigne, $assignees->toassignuser_id);
        }

        if (Auth::user()->getRoleNames()[0] == 'superadmin' || in_array(Auth::user()->id, $finalassigne) || $ticket->selfassignuser_id == Auth::user()->id) {
            $data['allowreply'] = true;
        } else {
            if ($ticket->category) {
                $aa = $ticket->category->groupscategoryc()->get();
                if ($aa->isNotEmpty()) {
                    $categoryArr = Category::with('groupscategoryc')->get();
                    foreach ($categoryArr as $individualCategory) {
                        if ($individualCategory->id == $ticket->category->id) {
                            foreach ($individualCategory->groupscategoryc as $individualGroupc) {
                                $groupId = $individualGroupc->group_id;
                                $groupUser = Groups::with('groupsuser')->get();
                                foreach ($groupUser as $individualGroup) {
                                    foreach ($individualGroup->groupsuser as $groups) {
                                        if ($groups->groups_id == $groupId) {
                                            if (($groups->users_id == Auth::user()->id)) {

                                                $data['allowreply'] = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    foreach (usersdata() as $admin) {
                        if ($admin->id == Auth::user()->id) {
                            $data['allowreply'] = true;
                        }
                    }
                }
            } else {
                foreach (usersdata() as $admin) {
                    if ($admin->id == Auth::user()->id) {
                        $data['allowreply'] = true;
                    }
                }
            }
        }

        $getMedia =  $ticket->getMedia('ticket');
        $data['getMedia'] = $getMedia;
        $page = $request['page'] ?? 1;
        $comments =  Comment::with(['cust', 'user.roles', 'media' => function ($query) {
            $query->where('collection_name', 'comments');
        }])->where('ticket_id', $ticket->id)->latest()->paginate($request['per_page']);
        // Now, iterate through each comment and add the profile image information
        foreach ($comments as $comment) {
            $commentMedia = $comment->media;

            // Add the profile image information for each media item
            foreach ($commentMedia as $mediaItem) {
                $conversionsDisk = $mediaItem->conversions_disk ?? 'public';
                $provider = existprovider($conversionsDisk)->provider;
                $imageUrl = $provider::getImageUrl($mediaItem->id . '/' . $mediaItem->file_name);

                // Only set the "profileimage" attribute if it's not already set
                if (!isset($mediaItem['profileimage'])) {
                    $mediaItem['profileimage'] = $imageUrl;
                }
            }
        }
        $data['comments'] = $comments;

        $ticketnote = [];

        $tn =  Ticketnote::where('ticket_id', $ticket->id)->latest()->get();
        foreach ($tn as $tns) {
            $tns->users->getRoleNames();
            array_push($ticketnote, $tns);
        }
        $data['ticketnote'] = $ticketnote;

        $ticketdraft = TicketDraft::where('ticket_id', $ticket->id)->first();
        $data['ticketdraft'] = $ticketdraft;
        if ($ticketdraft) {
            $data['imageArray'] = $ticketdraft->getMedia('ticketdrafts')->all();
            foreach ($data['imageArray'] as $imageArray) {
                # code...
                $conversions_disk = $imageArray->conversions_disk ?? 'public';
                $provider = existprovider($conversions_disk)->provider;
                $imageUrl = $provider::getImageUrl($imageArray->id . '/' . $imageArray->file_name);
                // Only set the "image" attribute if it's not already set
                if ($imageArray !== $imageUrl) {
                    $imageArray['profileimage'] = $imageUrl;
                }
            }
        }

        $cannedmessages = Cannedmessages::tickedetails($ticket_id);
        $cannedmessage = [];
        foreach ($cannedmessages as $object) {
            if ($object->status == 1 && $object->responsetype != 'livechat') {
                $cannedmessage[] = $object->toArray();
            }
        }
        $data['cannedmessages'] = $cannedmessage;


        $setting = response([
            'purchasecode_on' => setting('purchasecode_on'),
            'FILE_UPLOAD_MAX' => setting('FILE_UPLOAD_MAX'),
            'ticketrating' => setting('ticketrating'),
            'USER_REOPEN_ISSUE' => setting('USER_REOPEN_ISSUE'),
            'default_timezone' => setting('default_timezone'),
            'time_format' => setting('time_format'),
            'date_format' => setting('date_format'),
            'ENVATO_EXPIRED_BLOCK' => setting('ENVATO_EXPIRED_BLOCK'),
            'MAX_FILE_UPLOAD' => setting('MAX_FILE_UPLOAD'),
            'FILE_UPLOAD_TYPES' => setting('FILE_UPLOAD_TYPES'),
            'ENVATO_ON' => setting('ENVATO_ON'),
            'cust_or_tick_violation' => setting('cust_or_tick_violation'),
            "bot_image" => setting("bot_image"),
            "bot_name" => setting("bot_name"),
            'USER_FILE_UPLOAD_TYPES' => setting('USER_FILE_UPLOAD_TYPES'),
            'LengthTextFieldStatus' => setting('LengthTextFieldStatus'),
            'maxLengthTextField' => setting('maxLengthTextField'),
            'minLengthTextField' => setting('minLengthTextField'),
            'enableGeminiApi' => setting('enableGeminiApi'),
			'emp_google_translate' => setting('emp_google_translate'),
        ]);
        $data['setting'] = $setting;

        $projects = Projects::select('projects.*', 'projects_categories.category_id')->join('projects_categories', 'projects_categories.projects_id', 'projects.id')
            ->get();
        $data['projects'] = $projects;

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

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

        $totalrow1 = $category1->count();
        if ($totalrow1 > 0) {
            foreach ($category1 as $categories) {
                foreach ($categories->subcatlists()->where('status', '1')->get() as $subcategorylist) {
                    array_push($subcategory, $subcategorylist);
                }
            }
        }
        $data['subcategory'] = $subcategory;

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

        if (!$data['allowreply']) {
            abort(403);
        }
        $data['nouser'] =  asset('uploads/profile/user-profile.png');

        $data['languages'] = languages();

        $data['timezonedata'] = Auth::user()->timezone ?? setting('default_timezone');

        return $data;
    }


    public function purchasedetailsverify(Request $request)
    {
        $ticket = Ticket::findOrFail($request->id);
        $ticket->usernameverify = 'verified';
        $ticket->update();;

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

        $tickethistory->ticketnote = $ticket->ticketnote->isNotEmpty();
        $tickethistory->overduestatus = $ticket->overduestatus;
        $tickethistory->status = $ticket->status;
        $tickethistory->currentAction = 'User verified';
        $tickethistory->username = Auth::user()->name;
        $tickethistory->type = Auth::user()->getRoleNames()[0];

        $tickethistory->save();

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

    public function adminticketclosing(Request $request, $id)
    {
        $this->authorize('Ticket Edit');

        $id = decrypt($id);
        $ticket = Ticket::findOrFail($id);
        $ticket->status = 'Closed';
        $ticket->auto_close_ticket = null;
        $ticket->auto_replystatus = null;
        $ticket->auto_overdue_ticket = null;
        $ticket->overduestatus = null;
        $ticket->closedby_user = Auth::id();
        $ticket->ticketreopen = 'stopreopen';
        $ticket->update();

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

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

        $tickethistory->ticketnote = $ticket->ticketnote->isNotEmpty();
        $tickethistory->overduestatus = $ticket->overduestatus;
        $tickethistory->status = $ticket->status;
        $tickethistory->currentAction = 'Force Closed';
        $tickethistory->username = Auth::user()->name;
        $tickethistory->type = Auth::user()->getRoleNames()[0];

        $tickethistory->save();

        return response()->json(['success' => 'Ticket has been Closed forcefully.']);
    }
    public function addimportantticket(Request $request, $id)
    {
        $this->authorize('Ticket Edit');

        $id = decrypt($id);
        $ticket = Ticket::findOrFail($id);
        $ticket->importantticket = $ticket->importantticket == null ? 'on' : null;
        $ticket->update();

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

        $tickethistory->ticketnote = $ticket->ticketnote->isNotEmpty();
        $tickethistory->overduestatus = $ticket->overduestatus;
        $tickethistory->status = $ticket->status;
        $tickethistory->currentAction = $ticket->importantticket == 'on' ? 'Mark As Starred' :  'Mark As Unstarred';
        $tickethistory->username = Auth::user()->name;
        $tickethistory->type = Auth::user()->getRoleNames()[0];

        $tickethistory->save();

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = $ticket->importantticket == 'on' ? 'Marked ticket as important' : 'Marked as un-important';
        $activity->ticket_id = $ticket->ticket_id;
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => lang('Important ticket added successfully.', 'alerts')]);
    }
    public function wrongcustomer(Request $request)
    {
        $ticket = Ticket::findOrFail($request->id);
        $ticket->usernameverify = 'wrongcustomer';
        $ticket->update();

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

        $tickethistory->ticketnote = $ticket->ticketnote->isNotEmpty();
        $tickethistory->overduestatus = $ticket->overduestatus;
        $tickethistory->status = $ticket->status;
        $tickethistory->currentAction = 'User Unverified';
        $tickethistory->username = Auth::user()->name;
        $tickethistory->type = Auth::user()->getRoleNames()[0];

        $tickethistory->save();
        return response()->json(['success' => 'The cutomer mentioned details are wrong.']);
    }


    public function commentshow($ticket_id)
    {

        $ticket = Ticket::where('ticket_id', $ticket_id)->firstOrFail();
        if (request()->id > 0) {
            $comments = $ticket->comments()->where('id', '<', request()->id)
                ->orderBy('id', 'DESC')
                ->limit(6)
                ->latest()
                ->get();
        } else {
            $comments = $ticket->comments()
                ->orderBy('id', 'DESC')
                ->limit(6)
                ->latest()
                ->get();
        }

        $output = '';
        $last_id = '';
        $i = 0;
        $len = count($comments);
        if (!$comments->isEmpty()) {
            foreach ($comments as $comment) {
                if ($comment->user_id != null) {

                    if ($i == 0) {
                        $output .= '
                            <div class="card-body">
                                <div class="d-sm-flex">
                                    <div class="d-flex me-3">
                                        <a href="javascript:;">';
                        if ($comment->user != null) {
                            if ($comment->user->image == null) {
                                $output .= '<img src="' . asset('uploads/profile/user-profile.png') . '"  class="media-object brround avatar-lg" alt="default">';
                            } else {
                                $output .= '<img class="media-object brround avatar-lg" alt="' . $comment->user->image . '" src="' . asset('uploads/profile/' . $ticket->user->image) . '">';
                            }
                        } else {
                            $output .= '<img src="' . asset('uploads/profile/user-profile.png') . '"  class="media-object brround avatar-lg" alt="default">';
                        }
                        $output .=
                            '</a>
                                    </div>
                                    <div class="media-body">';
                        if ($comment->user != null) {
                            $output .= '<h5 class="mt-1 mb-1 font-weight-semibold">' . $comment->user->name . '<span class="badge badge-primary-light badge-md ms-2">' . $comment->user->getRoleNames()[0] . '</span></h5>';
                        } else {
                            $output .= '<h5 class="mt-1 mb-1 font-weight-semibold text-muted">~</h5>';
                        }
                        $output .= '<small class="text-muted"><i class="feather feather-clock"></i> ' . $comment->created_at->diffForHumans() . '</small>
                                        <span class="fs-13 mb-0 mt-1" value="">
                                            ' . $comment->comment . '
                                        </span>
                                        <div class="editsupportnote-icon animated" id="supportnote-icon-' . $comment->id . '">
                                            <form action="' . url('admin/ticket/editcomment/' . $comment->id) . '" method="POST">
                                                ' . csrf_field() . '
                                                <textarea class="editsummernote" name="editcomment">' . $comment->comment . '</textarea>
                                                <div class="btn-list mt-1">
                                                    <input type="submit" class="btn btn-secondary" onclick="this.disabled=true;this.form.submit();" value="Update">
                                                </div>
                                            </form>
                                        </div>
                                        ';
                        if (Auth::id() == $comment->user_id) {
                            $output .= '<div class="row galleryopen">';
                            foreach ($comment->getMedia('comments') as $commentss) {
                                $output .= '<div class="file-image-1  removespruko' . $commentss->id . '" id="imageremove' . $commentss->id . '">
                                                        <div class="product-image  ">
                                                            <a href="' . $commentss->getFullUrl() . '" class="imageopen">
                                                                <img src="' . $commentss->getFullUrl() . '" class="br-5" alt="' . $commentss->file_name . '">
                                                            </a>
                                                            <ul class="icons">
                                                                <li><a href="javascript:(0);" class="bg-danger " onclick="deleteticket(event.target)" data-id="' . $commentss->id . '"><i class="fe fe-trash" data-id="' . $commentss->id . '"></i>' . csrf_field() . '</a></li>
                                                            </ul>
                                                        </div>
                                                        <span class="file-name-1">
                                                            ' . Str::limit($commentss->file_name, 10, $end = '.......') . '
                                                        </span>
                                                    </div>
                                                    ';
                            }
                            $output .= '</div>';
                        } else {
                            $output .= '<div class="row galleryopen">';
                            foreach ($comment->getMedia('comments') as $commentss) {
                                $output .= '<div class="file-image-1  removespruko' . $commentss->id . '" id="imageremove' . $commentss->id . '">
                                                        <div class="product-image">
                                                            <a href="' . $commentss->getFullUrl() . '" class="imageopen">
                                                                <img src="' . $commentss->getFullUrl() . '" class="br-5" alt="' . $commentss->file_name . '">
                                                            </a>
                                                        </div>
                                                        <span class="file-name-1">
                                                            ' . Str::limit($commentss->file_name, 10, $end = '.......') . '
                                                        </span>
                                                    </div>
                                                    ';
                            }
                            $output .= '</div>';
                        }
                        $output .= '</div>';

                        if (Auth::id() == $comment->user_id) {
                            if ($comment->display != null)
                                $output .= '<div class="ms-auto">
                                            <span class="action-btns supportnote-icon" onclick="showEditForm(' . $comment->id . ')"><i class="feather feather-edit text-primary fs-16"></i></span>
                                        </div>';
                        }


                        $output .= '</div>
                            </div>';
                    } else {

                        $output .= '<div class="card-body">
                                <div class="d-sm-flex">
                                    <div class="d-flex me-3">
                                        <a href="javascript:;">';
                        if ($comment->user != null) {
                            if ($comment->user->image == null) {
                                $output .= '<img src="' . asset('uploads/profile/user-profile.png') . '"  class="media-object brround avatar-lg" alt="default">';
                            } else {
                                $output .= '<img class="media-object brround avatar-lg" alt="' . $comment->user->image . '" src="' . asset('uploads/profile/' . $ticket->user->image) . '">';
                            }
                        } else {
                            $output .= '<img src="' . asset('uploads/profile/user-profile.png') . '"  class="media-object brround avatar-lg" alt="default">';
                        }
                        $output .= '</a>
                                    </div>
                                    <div class="media-body">';
                        if ($comment->user != null) {
                            $output .= '<h5 class="mt-1 mb-1 font-weight-semibold">' . $comment->user->name . '<span class="badge badge-primary-light badge-md ms-2">' . $comment->user->getRoleNames()[0] . '</span></h5>';
                        } else {
                            $output .= '<h5 class="mt-1 mb-1 font-weight-semibold text-muted">~</h5>';
                        }
                        $output .= '<small class="text-muted"><i class="feather feather-clock"></i>' . $comment->created_at->diffForHumans() . '</small>
                                        <span class="fs-13 mb-0 mt-1" value="">
                                            ' . $comment->comment . '
                                        </span>
                                        <div class="row galleryopen">';
                        foreach ($comment->getMedia('comments') as $commentss) {
                            $output .= '<div class="file-image-1  removespruko' . $commentss->id . '" id="imageremove{{$commentss->id}}">
                                                    <div class="product-image  ">
                                                        <a href="' . $commentss->getFullUrl() . '" class="imageopen">
                                                            <img src="' . $commentss->getFullUrl() . '" class="br-5" alt="' . $commentss->file_name . '">
                                                        </a>
                                                    </div>
                                                    <span class="file-name-1">
                                                        ' . Str::limit($commentss->file_name, 10, $end = '.......') . '
                                                    </span>
                                                </div>';
                        }
                        $output .= '</div>
                                    </div>
                                </div>
                            </div>';
                    }
                } else {
                    $output .= '<div class="card-body">
                            <div class="d-sm-flex">
                                <div class="d-flex me-3">
                                    <a href="javascript:;">';
                    if ($comment->cust->image == null) {
                        $output .= ' <img src="' . asset('uploads/profile/user-profile.png') . '"  class="media-object brround avatar-lg" alt="default">';
                    } else {
                        $output .= '<img class="media-object brround avatar-lg" alt="' . $comment->cust->image . '" src="' . asset('uploads/profile/' . $ticket->cust->image) . '">';
                    }
                    $output .= ' </a>
                                </div>
                                <div class="media-body">
                                    <h5 class="mt-1 mb-1 font-weight-semibold">' . $comment->cust->username . '<span class="badge badge-primary-light badge-md ms-2">' . $comment->cust->userType . '</span></h5>
                                    <small class="text-muted"><i class="feather feather-clock"></i>' . $comment->created_at->diffForHumans() . '</small>
                                    <span class="fs-13 mb-0 mt-1" value="">
                                        ' . $comment->comment . '
                                    </span>
                                    <div class="row galleryopen">';
                    foreach ($comment->getMedia('comments') as $commentss) {
                        $output .= '<div class="file-image-1  removespruko' . $commentss->id . '" id="imageremove' . $commentss->id . '">
                                                <div class="product-image">
                                                    <a href="' . $commentss->getFullUrl() . '" class="imageopen">
                                                        <img src="' . $commentss->getFullUrl() . '" class="br-5" alt="' . $commentss->file_name . '">
                                                    </a>
                                                </div>
                                                <span class="file-name-1">
                                                    ' . Str::limit($commentss->file_name, 10, $end = '.......') . '
                                                </span>
                                            </div>';
                    }
                    $output .= '</div>
                                </div>
                            </div>
                        </div>';
                }
                $last_id = $comment->id;
                $i++;
            }

            $output .= '
           <div id="load_more">
            <button type="button" name="load_more_button" class="btn btn-success" data-id="' . $last_id . '" id="load_more_button">Load More</button>
           </div>
           ';
        } else {
            $output .= '
                    <div id="load_more">
                        <button type="button" name="load_more_button" class="btn btn-info ">No Data Found</button>
                    </div>
                    ';
        }

        return response()->json(['html' => $output, 'coment' => $comments]);
    }


    /**
     * Close the specified ticket.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    public function close(Request $request, $ticket_id, AppMailer $mailer)
    {
        $ticket = Ticket::where('ticket_id', $ticket_id)->firstOrFail();

        $ticket->status = $request->input('status');

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

        $ticketOwner = $ticket->user;

        $mailer->sendTicketStatusNotification($ticketOwner, $ticket);

        return response()->json(["warning" => 'The ticket has been closed.']);
    }

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

        $comment = $ticket->comments()->get();


        if (count($comment) > 0) {
            // $media = $ticket->getMedia('ticket');

            // foreach ($media as $media) {

            //     $media->delete();
            // }
            // $medias = $ticket->comments()->get();

            // foreach ($medias as $mediass) {
            //     foreach ($mediass->getMedia('comments') as $mediasss) {

            //         $mediasss->delete();
            //     }
            // }
            $comment->each->delete();

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

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

            $tickethistory->save();

            $ticket->delete();

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


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

            // $media = $ticket->getMedia('ticket');

            // foreach ($media as $media) {

            //     $media->delete();
            // }

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

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

            $tickethistory->save();

            foreach ($ticket->ticket_history as $deletetickethistory) {
                $deletetickethistory->delete();
            }

            // $ticket->ticketassignmutliples()->delete();
            $ticket->delete();
            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Deleted a ticket';
            $activity->ticket_id = $tickethistory->ticket_id;
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();

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


    public function ticketmassdestroy(Request $request)
    {
        // $student_id_array = $request->input('id');
        $student_id_arrays = $request->input('id');

        $student_id_array = array_map(function ($encryptedValue) {
            return decrypt($encryptedValue);
        }, $student_id_arrays);

        $tickets = Ticket::whereIn('id', $student_id_array)->get();


        foreach ($tickets as $ticket) {

            $comment = $ticket->comments()->get();


            if (count($comment) > 0) {
                // $media = $ticket->getMedia('ticket');

                // foreach ($media as $media) {

                //     $media->delete();
                // }
                // $medias = $ticket->comments()->get();

                // foreach ($medias as $mediass) {
                //     foreach ($mediass->getMedia('comments') as $mediasss) {

                //         $mediasss->delete();
                //     }
                // }
                $comment->each->delete();

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

                $tickethistory->ticketnote = $ticket->ticketnote->isNotEmpty();
                $tickethistory->ticketviolation = $ticket->ticketviolation;
                $tickethistory->overduestatus = $ticket->overduestatus;
                $tickethistory->status = $ticket->status;
                $tickethistory->replystatus = $ticket->replystatus;
                $tickethistory->currentAction = 'Ticket Deleted';
                $tickethistory->username = Auth::user()->name;
                $tickethistory->type = Auth::user()->getRoleNames()[0];
                $tickethistory->assignUser = null;
                $tickethistory->save();
                foreach ($ticket->ticket_history as $deletetickethistory) {
                    $deletetickethistory->delete();
                }

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

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

                // $media = $ticket->getMedia('ticket');

                // foreach ($media as $media) {

                //     $media->delete();
                // }

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

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

                foreach ($ticket->ticket_history as $deletetickethistory) {
                    $deletetickethistory->delete();
                }
                $tickets->each->delete();


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

    // Admin Ticket View
    public function createticket()
    {

        $this->authorize('Ticket Create');
        $categories = Category::whereIn('display', ['ticket', 'all'])->where('status', '1')->get();
        $data['categories'] = $categories;

        $customfields = Customfield::whereIn('displaytypes', ['both', 'createticket'])->whereIn('status', [1])->get();
        $data['customfields'] = $customfields;

        $agents = User::where('status', 1)->get();
        $data['agents'] = $agents;

        $setting = response([
            'SUPPORT_POLICY_URL' => setting('SUPPORT_POLICY_URL'),
            'FILE_UPLOAD_MAX' => setting('FILE_UPLOAD_MAX'),
            'cc_email' => setting('cc_email'),
            'default_timezone' => setting('default_timezone'),
            'time_format' => setting('time_format'),
            'date_format' => setting('date_format'),
            'ENVATO_EXPIRED_BLOCK' => setting('ENVATO_EXPIRED_BLOCK'),
            'MAX_FILE_UPLOAD' => setting('MAX_FILE_UPLOAD'),
            'TICKET_CHARACTER' => setting('TICKET_CHARACTER'),
            'FILE_UPLOAD_TYPES' => setting('FILE_UPLOAD_TYPES'),
            'envato_on' => setting('ENVATO_ON'),
            'USER_FILE_UPLOAD_TYPES' => setting('USER_FILE_UPLOAD_TYPES'),
            'LengthTextFieldStatus' => setting('LengthTextFieldStatus'),
            'maxLengthTextField' => setting('maxLengthTextField'),
            'minLengthTextField' => setting('minLengthTextField')
        ]);
        $data['setting'] = $setting;

        return $data;
    }

    // Admins Creating  Ticket

    public function gueststore(Request $request)
    {
        $this->authorize('Ticket Create');

        $this->validate($request, [
            'message' => ['required',  function ($attribute, $value, $fail) {
                // Remove all HTML tags and decode entities like &nbsp;
                $decodedValue = html_entity_decode(strip_tags($value));

                // Replace non-breaking spaces (\u{A0}) with regular spaces
                $normalizedValue = str_replace("\u{A0}", ' ', $decodedValue);

                // Trim unwanted tags from the start and end
                $normalizedValue = preg_replace('/^(<(p|div)><br><\/(p|div)>)+|(<(p|div)><br><\/(p|div)>)+$/', '', $normalizedValue);
                // Trim spaces and check if the result is empty
                if (trim($normalizedValue) === '') {
                    $fail('The comment must contain valid text, not just spaces or HTML.');
                }
            }]
        ]);
        
        $categories = CategoryEnvato::where('category_id', $request->category)->first();
        if (setting('ENVATO_ON') == 'on' && $categories != null) {
            if ($request->envato_id == 'undefined' || $request->envato_id == null || isset($request->envato_id) == false) {
                return response()->json(['message' => 'envatoerror', 'error' => 'Please enter valid details to create a ticket.'], 200);
            }
        }

        $subcategoriess = Subcategorychild::where('category_id', $request->category)->pluck('subcategory_id')->toArray();

        if ($request->subscategory && $subcategoriess != null && ($request->subscategory != "null" || $request->subscategory != null) && !in_array($request->subscategory, $subcategoriess)) {
            return response()->json(['message' => 'subcaterror', 'error' => 'Please enter valid details to create a ticket.'], 200);
        }


        $email  = $request->email;
        $completeDomain = substr(strrchr($email, "@"), 1);

        $emaildomainlist = setting('EMAILDOMAIN_LIST');
        $emaildomainlistArray = explode(",", $emaildomainlist);
        if (setting('EMAILDOMAIN_BLOCKTYPE') == 'blockemail') {
            if (setting('EMAILDOMAIN_LIST') == null) {
                $ticket = $this->emailpassgueststore($request);
                return response()->json(['message' => 'createticket', 'success' => 'A ticket has been opened with the ticket ID ' . $ticket->ticket_id, 'ticket_id' => encrypt($ticket->ticket_id)], 200);
            } else {
                if (in_array($completeDomain, $emaildomainlistArray)) {

                    return response()->json(['message' => 'domainblock', 'error' => 'Domain is Blocked List'], 200);
                }
                $ticket = $this->emailpassgueststore($request);
                return response()->json(['message' => 'createticket', 'success' => 'A ticket has been opened with the ticket ID ' . $ticket->ticket_id, 'ticket_id' => encrypt($ticket->ticket_id)], 200);
            }
        }
        if (setting('EMAILDOMAIN_BLOCKTYPE') == 'allowemail') {
            if (setting('EMAILDOMAIN_LIST') == null) {
                $ticket =  $this->emailpassgueststore($request);
                return response()->json(['message' => 'createticket', 'success' => 'A ticket has been opened with the ticket ID ' . $ticket->ticket_id, 'ticket_id' => encrypt($ticket->ticket_id)], 200);
            } else {
                if (in_array($completeDomain, $emaildomainlistArray)) {
                    $ticket = $this->emailpassgueststore($request);
                    return response()->json(['message' => 'createticket', 'success' => 'A ticket has been opened with the ticket ID ' . $ticket->ticket_id, 'ticket_id' => encrypt($ticket->ticket_id)], 200);
                }
                return response()->json(['message' => 'domainblock', 'error' => 'Domain is Blocked List'], 200);
            }
        }
    }

    private function emailpassgueststore($request)
    {
        $this->authorize('Ticket Create');

        $this->validate($request, [
            'subject' => 'required|string|max:255',
            'category' => 'required',
            'message' => 'required|no_script_tags|string',
            'email' => 'email|required|max:255',
        ]);

        if ($request->ccemail) {
            $this->validate($request, [
                'ccmail' => 'email|indisposable'
            ]);
        }


        $userexits = Customer::where('email', $request->email)->count();
        if ($userexits == 1) {
            $guest = Customer::where('email', $request->email)->first();
        } else {
            $guest = Customer::create([

                'firstname' => '',
                'lastname' => '',
                'username' => 'GUEST',
                'email' => $request->email,
                'userType' => 'Guest',
                'password' => null,
                'country' => '',
                'timezone' => 'UTC',
                'status' => '1',
                'image' => null,

            ]);
            $customersetting = new CustomerSetting();
            $customersetting->custs_id = $guest->id;
            $customersetting->save();
        }
        $comment = $request->input('message');

        // Trim unwanted tags from the start and end
        $comment = preg_replace('/^(<(p|div)><br><\/(p|div)>)+|(<(p|div)><br><\/(p|div)>)+$/', '', $comment);
        $ticket = Ticket::create([
            'subject' => $request->input('subject'),
            'cust_id' => $guest->id,
            'category_id' => $request->input('category'),
            'priority' => $request->input('priority'),
            'message' => $comment,
            'project' => $request->input('project'),
            'status' => 'New',
        ]);
        $ticket = Ticket::find($ticket->id);
        $ticket->ticket_id = setting('CUSTOMER_TICKETID') . 'G-' . $ticket->id;
        $ticket->user_id = Auth::user()->id;
        if ($request->input('envato_id')) {
            $ticket->purchasecode = encrypt($request->input('envato_id'));
            if ($request->input('productname')) {
                $ticket->item_name = $request->input('productname');
            }
        }
        if ($request->input('envato_support')) {

            $ticket->purchasecodesupport = $request->input('envato_support');
        }

        $categoryfind = Category::find($request->category);
        $ticket->priority =  $request->priority ? $request->priority : $categoryfind->priority;
        $ticket->subcategory = $request->subscategory;

        $ticket->update();

        $customfields = Customfield::whereIn('displaytypes', ['both', 'createticket'])->where('status', 1)->get();

        if ($customfields != false) {
            foreach ($customfields as $customfield) {
                $ticketcustomfield = new TicketCustomfield();
                $ticketcustomfield->ticket_id = $ticket->id;
                $ticketcustomfield->fieldnames = $customfield->fieldnames;
                $ticketcustomfield->fieldtypes = $customfield->fieldtypes;
                $ticketcustomfield->fieldoptions = $customfield->fieldoptions;
                if($request->input('custom_' . $customfield->id) == 'undefined' || $request->input('custom_' . $customfield->id) == 'null'){
                    $ticketcustomfield->values = Null;
                }
                else{
                    if ($customfield->fieldtypes == 'checkbox') {
                        if ($request->input('custom_' . $customfield->id) != null) {

                            // $string = implode(',', $request->input('custom_' . $customfield->id));
                            $ticketcustomfield->values = $request->input('custom_' . $customfield->id);
                        }
                    }
                    if ($customfield->fieldtypes != 'checkbox') {
                        if ($customfield->fieldprivacy == '1') {
                            $ticketcustomfield->privacymode  = $customfield->fieldprivacy;
                            $ticketcustomfield->values = encrypt($request->input('custom_' . $customfield->id));
                        } else {

                            $ticketcustomfield->values = $request->input('custom_' . $customfield->id);
                        }
                    }
                }
                $ticketcustomfield->save();
            }
        }

        $ccmails = new CCMAILS();
        $ccmails->ticket_id = $ticket->id;
        $ccmails->ccemails = $request->ccmail;
        $ccmails->save();


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

        $tickethistory->ticketnote = $ticket->ticketnote->isNotEmpty();
        $tickethistory->ticketviolation = $ticket->ticketviolation;
        $tickethistory->overduestatus = $ticket->overduestatus;
        $tickethistory->status = $ticket->status;
        $tickethistory->replystatus = $ticket->replystatus;
        $tickethistory->currentAction = 'Created';
        $tickethistory->username = $ticket->users->name;
        $tickethistory->type = $ticket->users->getRoleNames()[0];
        $tickethistory->assignUser = null;

        $tickethistory->save();

        // syncing table for assigned agent
        if ($request->assignagent) {
            $ticket->myassignuser_id = Auth::id();
            $ticket->selfassignuser_id = null;
            $ticket->save();
            $ticket->ticketassignmutliple()->sync($request->assignagent);

            $ticketData = [
                'ticket_username' => $ticket->cust->username,
                'ticket_id' => $ticket->ticket_id,
                'ticket_title' => $ticket->subject,
                'ticket_description' => $ticket->message,
                'ticket_customer_url' => url('/guest/ticket/' . encrypt($ticket->ticket_id)),
                'ticket_admin_url' => url('/admin/ticket-view/' . $ticket->encrypted_id),
                'ticket_category' => $ticket->category ? $ticket->category->name : null,
                'status' => $ticket->status
            ];

            try {

                $assignee = $ticket->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->notify(new TicketAssignNotification($ticket));
                            if ($users->usetting->emailnotifyon == 1) {
                                dispatch((new MailSend($users->email, 'when_ticket_assign_to_other_employee', $ticketData)));
                            }
                        }
                    }
                }
            } catch (\Exception $e) {
                $geolocation = GeoIP::getLocation(request()->getClientIp());
                $agent = new Agent();
                $activity = new EmployeeActivity();
                $activity->user_id = Auth::user()->id;
                $activity->activity_type = 'Assigned ticket to other employees.';
                $activity->ticket_id = $ticket->ticket_id;
                $activity->ip_address = $geolocation->ip;
                $activity->browser = $agent->browser();
                $activity->device = $agent->device();
                $activity->save();
                // return response()->json(['code'=>200, 'success'=> lang('The ticket was successfully assigned.', 'alerts')], 200);
            }
        }

        // if($ticket->selfassignuser_id == Auth()->user()->id){

        //     $selfupdate = new tickethistory();
        //     $selfupdate->ticket_id = $ticket->id;
        //     $selfupdate->ticketnote = $ticket->ticketnote->isNotEmpty();
        //     $selfupdate->overduestatus = $ticket->overduestatus;
        //     $selfupdate->status = $ticket->status;
        //     $selfupdate->currentAction = 'Self Assigned';
        //     $selfupdate->assigned_date = today();
        //     $selfupdate->assigned_time = now();
        //     $selfupdate->username = $ticket->users->name;
        //     $selfupdate->type = $ticket->users->getRoleNames()[0];

        //     $selfupdate->save();
        // }

        if ($request->assignagent) {
            $users = User::with('roles')->where('status', 1)->findorFail($request->assignagent);
            $otherupdate = new tickethistory();

            $otherupdate->ticket_id = $ticket->id;
            $otherupdate->ticketnote = $ticket->ticketnote->isNotEmpty();
            $otherupdate->overduestatus = $ticket->overduestatus;
            $otherupdate->status = $ticket->status;
            $otherupdate->assignUser = $users;
            $otherupdate->currentAction = 'Assigner';
            $otherupdate->assigned_date = today();
            $otherupdate->assigned_time = now();
            $otherupdate->username = Auth::user()->name;
            $otherupdate->type = Auth::user()->getRoleNames()[0];

            $otherupdate->save();
        }


        foreach ($request->file('ticket', []) as $file) {
            $provider =  storage()->provider;
            $provider::mediaupload($ticket, $file, 'ticket');
        }

        // create ticket notification
        $notificationcat = $ticket->category->groupscategoryc()->get();
        $groupIds = $notificationcat->pluck('group_id')->toArray();
        $groupstatus = false;
        foreach ($groupIds as $groupid) {
            $groupexist = Groups::where('groupstatus', '1')->find($groupid);
            if ($groupexist) {
                $groupstatus = true;
            }
        }

        $icc = array();

        if ($groupstatus) {

            foreach ($notificationcat as $igc) {
                $groups = $igc->groupsc()
                    ->where('groupstatus', 1)
                    ->with('groupsuser')
                    ->get();

                foreach ($groups as $group) {
                    $users = $group->groupsuser;

                    foreach ($users 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')->get();
                foreach ($admins as $admin) {
                    $admin->notify(new TicketCreateNotifications($ticket));
                }
            } else {

                $user = User::whereIn('id', $icc)->whereHas('roles', function ($query) {
                    $query->where('name', '!=', 'superadmin');
                })->get();
                foreach ($user as $users) {
                    $users->notify(new TicketCreateNotifications($ticket));
                }
                $admins = User::leftJoin('groups_users', 'groups_users.users_id', 'users.id')->whereNull('groups_users.groups_id')->whereNull('groups_users.users_id')->get();
                foreach ($admins as $admin) {
                    if ($admin->getRoleNames()[0] == 'superadmin') {
                        $admin->notify(new TicketCreateNotifications($ticket));
                    }
                }
            }
        } else {
            foreach (usersdata() as $admin) {
                $admin->notify(new TicketCreateNotifications($ticket));
            }
        }
        $cust = Customer::with('custsetting')->find($ticket->cust_id);
        $cust->notify(new TicketCreateNotifications($ticket));

        $ccemailsend = CCMAILS::where('ticket_id', $ticket->id)->first();
        $ticketData = [
            'ticket_username' => $ticket->cust->username,
            'ticket_id' => $ticket->ticket_id,
            'ticket_title' => $ticket->subject,
            'ticket_status' => $ticket->status,
            'ticket_description' => $ticket->message,
            'ticket_customer_url' => url('/guest/ticket/' . encrypt($ticket->ticket_id)),
            'ticket_admin_url' => url('/admin/ticket-view/' . encrypt($ticket->ticket_id)),
            'ticket_category' => $ticket->category ? $ticket->category->name : null,
            'status' => $ticket->status,
            'comment' => $request->input('message')
        ];

        try {

            $notificationcat = $ticket->category->groupscategoryc()->get();
            $groupIds = $notificationcat->pluck('group_id')->toArray();
            $groupstatus = false;
            foreach ($groupIds as $groupid) {
                $groupexist = Groups::where('groupstatus', '1')->find($groupid);
                if ($groupexist) {
                    $groupstatus = true;
                }
            }

            $icc = array();

            if ($groupstatus) {

                foreach ($notificationcat as $igc) {
                    $groups = $igc->groupsc()
                        ->where('groupstatus', 1)
                        ->with('groupsuser')
                        ->get();

                    foreach ($groups as $group) {
                        $users = $group->groupsuser;

                        foreach ($users 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('users.status', 1)->get();
                    foreach ($admins as $admin) {
                        if ($admin->usetting->emailnotifyon == 1) {
                            dispatch((new MailSend($admin->email, 'admin_send_email_ticket_created', $ticketData)));
                        }
                    }
                } else {

                    $user = User::whereIn('id', $icc)->whereHas('roles', function ($query) {
                        $query->where('name', '!=', 'superadmin');
                    })->where('status', 1)->get();
                    foreach ($user as $users) {
                        if ($users->usetting->emailnotifyon == 1) {
                            dispatch((new MailSend($users->email, 'admin_send_email_ticket_created', $ticketData)));
                        }
                    }
                    $admins = User::leftJoin('groups_users', 'groups_users.users_id', 'users.id')->whereNull('groups_users.groups_id')->whereNull('groups_users.users_id')->where('users.status', 1)->get();
                    foreach ($admins as $admin) {
                        if ($admin->getRoleNames()[0] == 'superadmin' && $admin->usetting->emailnotifyon == 1) {
                            dispatch((new MailSend($admin->email, 'admin_send_email_ticket_created', $ticketData)));
                        }
                    }
                }
            } else {
                foreach (usersdata() as $admin) {
                    if ($admin->usetting->emailnotifyon == 1) {
                        dispatch((new MailSend($admin->email, 'admin_send_email_ticket_created', $ticketData)));
                    }
                }
            }


            // $holidays = Holiday::whereDate('startdate', '<=', $today)->whereDate('enddate', '>=', $today)->where('status','1')->get();
            $today = Carbon::today();
            $activeHolidays = Holiday::where('status', 1)->get();
            $now = now();
            $currentYear = $now->year;
            $holidays = $activeHolidays->filter(function ($holiday) use ($now, $currentYear) {
                $holidayStart = Carbon::parse($holiday->startdate);
                $holidayEnd = Carbon::parse($holiday->enddate);
                if ($holiday->is_fixed) {
                    return $holidayStart->month === $now->month && $holidayStart->day === $now->day;
                }
                return $holidayStart->isSameDay($now);
            });

            if ($holidays->isNotEmpty() && setting('24hoursbusinessswitch') != 'on') {

                dispatch((new MailSend($ticket->cust->email, 'customer_send_ticket_created_that_holiday_or_announcement', $ticketData)));
                if ($ccemailsend->ccemails != null) {
                    dispatch((new MailSend($ccemailsend->ccemails, 'customer_send_ticket_created_that_holiday_or_announcement', $ticketData)));
                }
            } else {
                dispatch((new MailSend($ticket->cust->email, 'customer_send_guestticket_created', $ticketData)));
                if ($ccemailsend->ccemails != null) {
                    dispatch((new MailSend($ccemailsend->ccemails, 'customer_send_guestticket_created', $ticketData)));
                }
            }
        } catch (\Exception $e) {
            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Created a ticket for customer';
            $activity->ticket_id =  $ticket->ticket_id;
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();
            return $ticket;
        }
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Created a ticket for customer';
        $activity->ticket_id =  $ticket->ticket_id;
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return $ticket;
    }

    public function guestmedia(Request $request)
    {
        $path = public_path('uploads/guestticket/');

        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }

        $file = $request->file('file');

        $name = uniqid() . '_' . trim($file->getClientOriginalName());

        $file->move($path, $name);

        return response()->json([
            'name'          => $name,
            'original_name' => $file->getClientOriginalName(),
        ]);
    }

    public function note(Request $request)
    {

        $rules = [
            'ticket_id' => 'required|exists:tickets,id',  // Assuming 'tickets' is the name of the table
            'ticketnote' => 'required|string|max:255',    // Adjust length as needed
        ];

        // Validate the request
        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors()
            ], 422);
        }


        $ticketnote = $request->input('ticketnote');

        // Trim unwanted tags from the start and end
        $ticketnote = preg_replace('/^(<(p|div)><br><\/(p|div)>)+|(<(p|div)><br><\/(p|div)>)+$/', '', $ticketnote);

        $ticketnote = Ticketnote::create([
            'ticket_id' => $request->input('ticket_id'),
            'user_id' => Auth::user()->id,
            'ticketnotes' => $ticketnote
        ]);

        $ticket = Ticket::where('id', $request->input('ticket_id'))->firstOrFail();

        $tickethistory = new tickethistory();
        $tickethistory->ticket_id = $ticket->id;
        $tickethistory->ticketnote = $ticket->ticketnote->isNotEmpty();
        $tickethistory->ticketviolation = $ticket->ticketviolation;
        $tickethistory->overduestatus = $ticket->overduestatus;
        $tickethistory->currentAction = 'Note Created';
        $tickethistory->username = Auth::user()->name;
        $tickethistory->type = Auth::user()->getRoleNames()[0];
        $tickethistory->status = $ticket->status;
        $tickethistory->status = $ticket->replystatus;
        $tickethistory->save();
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Added a ticket note. ';
        $activity->ticket_id = $tickethistory->ticket_id;
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        $user = User::findOrFail($ticketnote->user_id);
        $ticketData = [
            'note_id' => $ticketnote->id,
            'role_name' => Auth::user()->getRoleNames()[0],
            'role_id' => Auth::user()->id,
            'ticket_id' => $ticket->ticket_id,
            'note_username' => $user->name,
            'ticket_note' => $ticketnote->ticketnotes,
            'ticket_admin_url' => url('/admin/ticket-view/' . encrypt($ticket->ticket_id)),
            'ticket_category' => $ticket->category ? $ticket->category->name : null,
            'status' => $ticket->status,
            'comment' => $request->input('message'),
        ];

        try {
            $admins = User::leftJoin('groups_users', 'groups_users.users_id', 'users.id')->whereNull('groups_users.groups_id')->whereNull('groups_users.users_id')->where('users.status', 1)->get();
            $admins->filter(function ($admin) use ($ticketnote, $ticket, $ticketData) {
                // $admin->notify(new TicketCreateNotifications($ticket));
                if ($admin->getRoleNames()[0] == 'superadmin' && $admin->usetting->emailnotifyon == 1 && setting('NOTE_CREATE_MAILS') == 'on' && $ticketnote->user_id != $admin->id) {
                    dispatch((new MailSend($admin, 'send_mail_to_admin_when_ticket_note_created', $ticketData)));
                }
            });
        } catch (\Exception $e) {
        }

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

    public function noteshow($ticket_id)
    {
        $ticket = Ticket::where('ticket_id', $ticket_id)->firstOrFail();
        $comments = $ticket->comments;
        $category = $ticket->category;

        $title = Apptitle::first();
        $data['title'] = $title;

        $footertext = Footertext::first();
        $data['footertext'] = $footertext;

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        $post = Pages::all();
        $data['page'] = $post;


        return view('admin.viewticket.note', compact('ticket', 'category', 'comments', 'title', 'footertext'))->with($data);
    }

    public function notedestroy($id)
    {
        $ticketnotedelete = Ticketnote::find($id);



        $ticket = Ticket::where('id', $ticketnotedelete->ticket_id)->firstOrFail();

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

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

        $tickethistory->save();


        $ticketnotedelete->delete();

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

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

    public function deleteViolation($id)
    {

        $ticketviolationdelete = Ticketviolation::find($id);



        $ticket = Ticket::where('id', $ticketviolationdelete->ticket_id)->firstOrFail();

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

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

        $tickethistory->save();

        $ticketviolationdelete->delete();

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

    public function sublist(Request $request)
    {

        $parent_id = $request->cat_id;

        $subcategories = Projects::select('projects.*', 'projects_categories.category_id')->join('projects_categories', 'projects_categories.projects_id', 'projects.id')
            ->where('projects_categories.category_id', $parent_id)
            ->get();

        return response()->json([
            'subcategories' => $subcategories
        ]);
    }


    public function changepriority(Request $req)
    {

        $this->validate($req, [
            'priority' => 'required',
        ]);

        $priority = Ticket::with('category', 'subcategoriess')->find($req->priority_id);
        $priority->priority = $req->priority;
        $priority->update();

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

        $tickethistory->ticketnote = $priority->ticketnote->isNotEmpty();
        $tickethistory->ticketviolation = $priority->ticketviolation;
        $tickethistory->overduestatus = $priority->overduestatus;
        $tickethistory->status = $priority->status;
        $tickethistory->replystatus = $priority->replystatus;
        $tickethistory->currentAction = 'Priority 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 = 'Changed ticket priority for ticket';
        $activity->ticket_id = $tickethistory->ticket_id;
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

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

    public function alltickets(Request $request)
    {

        if (Auth::user()->dashboard == 'Admin') {
            return $this->adminalltickets($request);
        }
        if (Auth::user()->dashboard == 'Employee' || Auth::user()->dashboard == null) {
            return $this->employeealltickets($request);
        }
    }

    public function adminalltickets($request)
    {
        $user = User::with('usetting')->findOrFail(Auth::user()->id);
        $data['timezonedata'] = Auth::user()->timezone ?? setting('default_timezone');;
        $role = Role::where('name', $user->getRoleNames()[0])->get();
        foreach ($role as $roles) {
            $data['permissions'] = $roles->getPermissionNames();
        }
        $query = Ticket::with('cust', 'ticketdraft', 'ticketnote', 'ticketassignmutliples', 'selfassign', 'category', 'users')
            ->latest('tickets.updated_at');
        $category      = $request['categories'] ?? null;
        $user  = $request['user'] ?? null;
        $status  = $request['status'] ?? null;
        $searchTerm = $request['filter'] ?? null;
        $perPage    = $request['per_page'] ?? 15;
        $page       = $request['page'] ?? 1;
        // filter by category
        if ($category && $category != 'null') {
            $query->where('category_id', $category);
        }

        // get only tickets that specified user has created
        if ($user && $user != 'null') {
            $query->WhereHas('cust', function ($query) use ($user) {
                $query->where('userType', $user);
            });
        }
        // get only tickets that specified user has created
        if ($status && $status != 'null') {
            $query->where('status', $status);
        }

        if ($searchTerm) {
            $query->where(function ($query) use ($searchTerm) {
                $columns = Schema::getColumnListing('tickets');
                foreach ($columns as $column) {
                    $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                }
                $query->orWhereHas('category', function ($query) use ($searchTerm) {
                    $query->where('name', 'LIKE', $searchTerm . '%');
                })->orWhereHas('cust', function ($query) use ($searchTerm) {
                    $query->where('username', 'LIKE', $searchTerm . '%');
                })
                    ->orWhereHas('selfassign', function ($query) use ($searchTerm) {
                        $query->where(function ($query) use ($searchTerm) {
                            $query->where('name', 'LIKE', "%{$searchTerm}%");
                            // Check for 'self' in the search term
                            if (strpos('self', strtolower($searchTerm)) !== false) {
                                // Also check if the selfassignuser_id is not null
                                $query->orWhere('selfassignuser_id', '!=', null);
                            }
                        });
                    })
                    ->orWhereHas('ticketassignmutliples', function ($query) use ($searchTerm) {
                        // Assuming you defined the 'assignedUser()' relationship in ticketassignchild model
                        $query->whereHas('toassignuser', function ($query) use ($searchTerm) {
                            $query->where('name', 'LIKE', "%{$searchTerm}%");
                        });
                        if (stripos('multi Assign', strtolower($searchTerm)) !== false) {
                            $query->orWhere('ticket_id', '!=', null);
                        }
                    });
            });
        }
        $items = $query->paginate($perPage);
        $data['queryList'] = $items;

        $data['setting'] = response()->json(['date_format' => setting('date_format')]);

        return $data;
    }

    public function employeealltickets($request)
    {
        $user = User::with('usetting')->findOrFail(Auth::user()->id);
        $data['timezonedata'] = Auth::user()->timezone ?? setting('default_timezone');
        $role = Role::where('name', $user->getRoleNames()[0])->get();
        foreach ($role as $roles) {
            $data['permissions'] = $roles->getPermissionNames();
        }

        $agent = User::count();
        $data['agent'] = $agent;

        $customer = Customer::count();
        $data['customer'] = $customer;

        $groupexists = Groupsusers::where('users_id', Auth::id())->exists();

        // if there in group get group tickets
        if ($groupexists) {
            $query = Ticket::with('cust', 'ticketdraft', 'ticketnote', 'ticketassignmutliples', 'selfassign', 'category', 'users')->select('tickets.*', "groups_categories.group_id", "groups_users.users_id")
                ->leftJoin('groups_categories', 'groups_categories.category_id', 'tickets.category_id')
                ->leftJoin('groups_users', 'groups_users.groups_id', 'groups_categories.group_id')
                ->whereNotNull('groups_users.users_id')
                ->where('groups_users.users_id', Auth::id())
                ->latest('tickets.updated_at')->groupBy('tickets.id');

            $category      = $request['categories'] ?? null;
            $user  = $request['user'] ?? null;
            $status  = $request['status'] ?? null;
            $searchTerm = $request['filter'] ?? null;
            $perPage    = $request['per_page'] ?? 15;
            $page       = $request['page'] ?? 1;
            // filter by category
            if ($category && $category != 'null') {
                $query->where('category_id', $category);
            }

            // get only tickets that specified user has created
            if ($user && $user != 'null') {
                $query->WhereHas('cust', function ($query) use ($user) {
                    $query->where('userType', $user);
                });
            }
            // get only tickets that specified user has created
            if ($status && $status != 'null') {
                $query->where('status', $status);
            }

            if ($searchTerm) {
                $query->where(function ($query) use ($searchTerm) {
                    $columns = Schema::getColumnListing('tickets');
                    foreach ($columns as $column) {
                        $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                    }
                    $query->orWhereHas('category', function ($query) use ($searchTerm) {
                        $query->where('name', 'LIKE', $searchTerm . '%');
                    })->orWhereHas('cust', function ($query) use ($searchTerm) {
                        $query->where('username', 'LIKE', $searchTerm . '%');
                    })
                        ->orWhereHas('selfassign', function ($query) use ($searchTerm) {
                            $query->where(function ($query) use ($searchTerm) {
                                $query->where('name', 'LIKE', "%{$searchTerm}%");
                                // Check for 'self' in the search term
                                if (strpos('self', strtolower($searchTerm)) !== false) {
                                    // Also check if the selfassignuser_id is not null
                                    $query->orWhere('selfassignuser_id', '!=', null);
                                }
                            });
                        })
                        ->orWhereHas('ticketassignmutliples', function ($query) use ($searchTerm) {
                            // Assuming you defined the 'assignedUser()' relationship in ticketassignchild model
                            $query->whereHas('toassignuser', function ($query) use ($searchTerm) {
                                $query->where('name', 'LIKE', "%{$searchTerm}%");
                            });
                            if (stripos('multi Assign', strtolower($searchTerm)) !== false) {
                                $query->orWhere('ticket_id', '!=', null);
                            }
                        });
                });
            }
            $items = $query->paginate($perPage);


            $data['queryList'] = $items;
            $ticketnote = DB::table('ticketnotes')->pluck('ticketnotes.ticket_id')->toArray();
            $data['ticketnote'] = $ticketnote;
        }
        // If no there in group we get the all tickets
        else {


            $query = Ticket::with('cust', 'ticketdraft', 'ticketnote', 'ticketassignmutliples', 'selfassign', 'category', 'users')->select('tickets.*', "groups_categories.group_id", "groups_users.users_id")
                ->leftJoin('groups_categories', 'groups_categories.category_id', 'tickets.category_id')
                ->leftJoin('groups_users', 'groups_users.groups_id', 'groups_categories.group_id')
                ->whereNull('groups_users.users_id')
                ->latest('tickets.updated_at')->groupBy('tickets.id');

            $category      = $request['categories'] ?? null;
            $user  = $request['user'] ?? null;
            $status  = $request['status'] ?? null;
            $searchTerm = $request['filter'] ?? null;
            $perPage    = $request['per_page'] ?? 15;
            $page       = $request['page'] ?? 1;
            // filter by category
            if ($category && $category != 'null') {
                $query->where('category_id', $category);
            }

            // get only tickets that specified user has created
            if ($user && $user != 'null') {
                $query->WhereHas('cust', function ($query) use ($user) {
                    $query->where('userType', $user);
                });
            }
            // get only tickets that specified user has created
            if ($status && $status != 'null') {
                $query->where('status', $status);
            }

            if ($searchTerm) {
                $query->where(function ($query) use ($searchTerm) {
                    $columns = Schema::getColumnListing('tickets');
                    foreach ($columns as $column) {
                        $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                    }
                    $query->orWhereHas('category', function ($query) use ($searchTerm) {
                        $query->where('name', 'LIKE', $searchTerm . '%');
                    })->orWhereHas('cust', function ($query) use ($searchTerm) {
                        $query->where('username', 'LIKE', $searchTerm . '%');
                    })
                        ->orWhereHas('selfassign', function ($query) use ($searchTerm) {
                            $query->where(function ($query) use ($searchTerm) {
                                $query->where('name', 'LIKE', "%{$searchTerm}%");
                                // Check for 'self' in the search term
                                if (strpos('self', strtolower($searchTerm)) !== false) {
                                    // Also check if the selfassignuser_id is not null
                                    $query->orWhere('selfassignuser_id', '!=', null);
                                }
                            });
                        })
                        ->orWhereHas('ticketassignmutliples', function ($query) use ($searchTerm) {
                            // Assuming you defined the 'assignedUser()' relationship in ticketassignchild model
                            $query->whereHas('toassignuser', function ($query) use ($searchTerm) {
                                $query->where('name', 'LIKE', "%{$searchTerm}%");
                            });
                            if (stripos('multi Assign', strtolower($searchTerm)) !== false) {
                                $query->orWhere('ticket_id', '!=', null);
                            }
                        });
                });
            }
            $items = $query->paginate($perPage);


            $data['queryList'] = $items;
            $ticketnote = DB::table('ticketnotes')->pluck('ticketnotes.ticket_id')->toArray();
            $data['ticketnote'] = $ticketnote;
        }

        $data['setting'] = response()->json(['date_format' => setting('date_format')]);
        return $data;
    }

    public function violationdetails(Request $request, $id)
    {
        $cust = Ticket::find($id);
        $ticdata = Ticket::where('ticketviolation', 'on')->where('cust_id', $cust->cust_id)->count();
        // if ($ticdata < setting('max_tic_to_violation')) {
        //     $allowedpattern = 'only_ticket';
        // } else {
        //     $allowedpattern = 'ticket_and_customer';
        // }


        return response()->json(['allowedpattern' => 'allowedpattern']);
    }
    // To show cursor
    public function employeesreplyingstore(Request $request)
    {
        $this->authorize('Ticket Edit');
        $ticket = Ticket::findOrFail($request->ticketId);
        $ticketIdReply = $ticket->ticket_id;
        $currentContent = preg_replace('/\s+|&nbsp;/', ' ', trim(strip_tags($request->content)));

        if ($request->isTyping) {
            $ticket->employeesreplying = $request->userID;
            $ticket->employeereplytime = now();
        } else {
            $ticket->employeesreplying = null;
            $ticket->employeereplytime = null;
        }

        $ticket->save();

        // Prepare user details
        $userdetail = $request->isTyping ? Auth::user() : null;
        if (webSocketCheck()) {
            try {
                event(new ConversationEvent(dbname(), $currentContent, null, $userdetail, null, null, 'collossionDetection', $ticketIdReply, $ticket, null));
            } catch (\Exception $e) {
                Log::error('Error dispatching WebSocket event: ' . $e->getMessage());
            }
        }
    }
    public function employeesreplyingremove(Request $request)
    {
        $this->authorize('Ticket Edit');
        $id = $request->userID;
        $ticket = Ticket::findOrFail($request->ticketId);
        $ticket->employeesreplying = null;
        $ticket->employeereplytime = null;
        $ticket->save();
    }
    public function getemployeesreplying($ticket_id)
    {
        $this->authorize('Ticket Edit');
        $ticket = Ticket::findOrFail($ticket_id);
        $carbonInstance = Carbon::parse($ticket->employeereplytime);
        $diff_time = $carbonInstance->timezone(setting('default_timezone'))->diffForHumans();
        $empList = explode(",", $ticket->employeesreplying);
        $employee = User::get();
        $employees = [];
        $empnames = 'empnames';
        foreach ($employee as $emp) {
            if (in_array($emp->id, $empList) && $emp->id != Auth::id()) {
                array_push($employees, $emp);
            }
        }
        return response()->json(['employees' => $employees, 'empnames' => $empnames, 'diff_time' => $diff_time]);
    }
    public function fileuploadPermission(Request $request, $id)
    {
        $ticket = Ticket::findorFail($id);
        $ticket->fileupload_allowed =  $request->permission;
        $ticket->save();

        if (webSocketCheck()) {
            try {
                event(new ConversationEvent(dbname(), null, null, null, null, null, 'fileuploadperm', $ticket->ticket_id, null));
            } catch (\Exception $e) {
                Log::error('Error dispatching WebSocket event: ' . $e->getMessage());
            }
        }

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


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