<?php

namespace App\Http\Controllers\User\Ticket;

use App\Http\Controllers\Controller;
use App\Mail\mailmailablesend;
use App\Models\Apptitle;
use App\Models\Businesshours;
use App\Models\CCMAILS;
use App\Models\Customfield;
use App\Models\Footertext;
use App\Models\Pages;
use App\Models\Projects;
use App\Models\Seosetting;
use App\Models\TicketCustomfield;
use App\Models\Ticket\Category;
use App\Models\Ticket\Comment;
use App\Models\Ticket\Ticket;
use App\Models\User;
use App\Notifications\TicketCreateNotifications;
use Auth;
use Illuminate\Http\Request;
use Mail;
use App\Models\tickethistory;
use App\Models\Ratingtoken;
use Carbon\Carbon;
use App\Entities\CategoryEnvato;
use App\Models\Announcement;
use App\Models\Employeerating;
use App\Models\Groups;
use App\Models\Holiday;
use App\Models\Userrating;
use laravelLara\infoinst\Jobs\MailSend;
use App\Jobs\SendSMS;
use App\Models\Subcategorychild;
use App\Models\Setting;
use App\Models\AddSpace;
use App\Models\Customer;

use App\Models\AllTransactions;
use App\Events\ConversationEvent;
use Illuminate\Support\Facades\Log;

class TicketController extends Controller
{

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        if (setting('CUSTOMER_TICKET') == 'no') {
            $categories = Category::whereIn('display', ['ticket', 'all'])->where('status', '1')
                ->get();
            $data['categories'] = $categories;

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

            $now = now();
            $announcement = announcement::whereDate('enddate', '>=', $now->toDateString())->whereDate('startdate', '<=', $now->toDateString())->get();
            $data['announcement'] = $announcement;

            $announcements = Announcement::whereNotNull('announcementday')->get();
            $data['announcements'] = $announcements;

            // $holidays = Holiday::whereDate('startdate', '<=', $now->toDateString())->whereDate('enddate', '>=', $now->toDateString())->where('status',1)->get();
            // $data['holidays'] =  $holidays;
            $currentYear = $now->year;

            $activeHolidays = Holiday::where('status', 1)->get();

            // Filter holidays
            $data['holidays'] = $activeHolidays->filter(function ($holiday) use ($now, $currentYear) {
                $holidayStart = Carbon::parse($holiday->startdate);
                $holidayEnd = Carbon::parse($holiday->enddate);

                // Check for fixed holidays (compare only day and month)
                if ($holiday->is_fixed) {
                    return $holidayStart->month === $now->month && $holidayStart->day === $now->day;
                }

                // For non-fixed holidays, check the full date
                return $holidayStart->isSameDay($now);
            });

            $quotations = AllTransactions::where('cust_id', Auth::guard('customer')->user()->id)->whereIn('status', ['pending', 'cancelled'])->latest('created_at')->get();
            $data['quotations'] = $quotations;

            $unviewedQuotations = $quotations->where('cust_viewed', '!=', 1)->where('status', 'pending');
            $data['unviewedQuotations'] = $unviewedQuotations;

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

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

            $cc_email = setting('cc_email');
            $data['cc_email'] = $cc_email;
            $FILE_UPLOAD_MAX = setting('FILE_UPLOAD_MAX');
            $data['FILE_UPLOAD_MAX'] = $FILE_UPLOAD_MAX;
            $MAX_FILE_UPLOAD = setting('MAX_FILE_UPLOAD');
            $data['MAX_FILE_UPLOAD'] = $MAX_FILE_UPLOAD;
            $FILE_UPLOAD_TYPES = setting('FILE_UPLOAD_TYPES');
            $data['FILE_UPLOAD_TYPES'] = $FILE_UPLOAD_TYPES;
            $TICKET_CHARACTER = setting('TICKET_CHARACTER');
            $data['TICKET_CHARACTER'] = $TICKET_CHARACTER;
            $ENVATO_EXPIRED_BLOCK = setting('ENVATO_EXPIRED_BLOCK');
            $data['ENVATO_EXPIRED_BLOCK'] = $ENVATO_EXPIRED_BLOCK;
            $SUPPORT_POLICY_URL = setting('SUPPORT_POLICY_URL');
            $data['SUPPORT_POLICY_URL'] = $SUPPORT_POLICY_URL;
            $USER_FILE_UPLOAD_ENABLE = setting('USER_FILE_UPLOAD_ENABLE');
            $data['USER_FILE_UPLOAD_ENABLE'] = $USER_FILE_UPLOAD_ENABLE;
            $envato_on = setting('envato_on');
            $data['envato_on'] = $envato_on;
            $terms_url = setting('terms_url');
            $data['terms_url'] = $terms_url;

            $setting = response()->json([
                'FILE_UPLOAD_TYPES' => setting('FILE_UPLOAD_TYPES'),
                'FILE_UPLOAD_MAX' => setting('FILE_UPLOAD_MAX'),
                'MAX_FILE_UPLOAD' => setting('MAX_FILE_UPLOAD'),
                'CUSTOMER_RESTRICT_EDIT_REPLY' => setting('CUSTOMER_RESTRICT_EDIT_REPLY'),
                'LengthTextFieldStatus' => setting('LengthTextFieldStatus'),
                'maxLengthTextField' => setting('maxLengthTextField'),
                'minLengthTextField' => setting('minLengthTextField'),
                'offlineTextMessage' => setting('offlineTextMessage'),
                'offlineTextTitle' => setting('offlineTextTitle'),
                'businesshourofflinemsg' => setting('businesshourofflinemsg')
            ]);
            $data['setting'] = $setting;

            $holidays = Holiday::whereDate('startdate', '<=', $now->toDateString())->whereDate('enddate', '>=', $now->toDateString())->where('status', 1)->get();
            $data['holidays'] =  $holidays;


            $now = now();
            $holidays = Holiday::whereDate('startdate', '<=', $now->toDateString())->where('status', '1')->get();
            if ($holidays->isNotEmpty()) {
                $data['isOnline'] = false;
            } else {
                $businesshours = Businesshours::get();
                $data['businesshours'] = $businesshours;
                foreach ($businesshours as $business) {
                    if (now()->timezone(setting('default_timezone'))->format('D') == $business->weeks) {
                        if (strtotime($business->starttime) <= strtotime(now()->timezone(setting('default_timezone'))->format('h:i A')) && strtotime($business->endtime) >= strtotime(now()->timezone(setting('default_timezone'))->format('h:i A')) || $business->starttime == "24H") {
                            $data['isOnline'] = true;
                        } else {

                            $data['isOnline'] = false;
                        }
                    }
                }
            }

            // customer restrict to create tickets based on allowed to create.
            if (setting('RESTRICT_TO_CREATE_TICKET') == 'on' && setting('MAXIMUM_ALLOW_TICKETS') > 0) {
                $customer = Auth::guard('customer')->user();
                $star1 = now()->subHour(setting('MAXIMUM_ALLOW_HOURS'));
                $star2 = now();
                $latestReplies = $customer->tickets()->whereBetween('created_at', [$star1, $star2])->get()->take(setting('MAXIMUM_ALLOW_TICKETS'));
                if ($latestReplies->isNotEmpty()) {
                    $totalcount = 0;
                    foreach ($latestReplies as $comment) {
                        if ($comment->user_id !== null) {
                            $totalcount++;
                        }
                    }
                    if (!$totalcount) {
                        $currentTcikets = $latestReplies->last();
                        $data['difference'] = $currentTcikets->created_at->addHour(setting('REPLY_ALLOW_IN_HOURS'))->diffForHumans(now());
                        $ticketscount = Ticket::where('cust_id', $customer->id)->whereBetween('created_at', [$star1, $star2])->count();
                        if ($ticketscount < setting('MAXIMUM_ALLOW_TICKETS')) {
                            return $data;
                        } else {
                            $pendingTime = $latestReplies->last()->created_at->addHour(setting('REPLY_ALLOW_IN_HOURS'))->diffForHumans();
                            return response()->json(['error' => 'You have reached the maximum allowed tickets to create. Please wait ' . $pendingTime . ' before creating a new ticket.']);
                        }
                    } else {
                        return $data;
                    }
                } else {
                    return $data;
                }
            } else {
                return $data;
            }
        } else {
            return response()->json(['error' => 'You cannot have access for this ticket create.']);
        }
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $categories = CategoryEnvato::where('category_id', $request->category)->first();
        // if ($categories != null && $request->envato_id == 'undefined') {
        //     return response()->json(['message' => 'envatoerror', 'error' => lang('Please enter valid details to create a ticket.', 'alerts')], 200);
        // }

        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' => lang('Please enter valid details to create a ticket.', 'alerts')], 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' => lang('Please enter valid details to create a ticket.', 'alerts')], 200);
        }

        $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.');
                }
            }]
        ]);
        $this->validate($request, [
            'subject' => 'required|max:255',
            'category' => 'required',
            'message' => 'required|no_script_tags|string',
            'agree_terms' =>  'required|in:agreed',
        ]);

        $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' => Auth::guard('customer')->user()->id,
            'category_id' => $request->input('category'),
            'message' => $comment,
            'project' => $request->input('project'),
            'status' => 'New',
        ]);
        $ticket = Ticket::find($ticket->id);
        $ticket->ticket_id = setting('CUSTOMER_TICKETID') . '-' . $ticket->id;
        // Auto Overdue Ticket

        if (setting('AUTO_OVERDUE_TICKET') == 'no') {
            $ticket->auto_overdue_ticket = null;
        } else {
            if (setting('AUTO_OVERDUE_TICKET_TIME') == '0') {
                $ticket->auto_overdue_ticket = null;
            } else {
                if (Auth::guard('customer')->check() && Auth::guard('customer')->user()) {
                    if ($ticket->status == 'Closed') {
                        $ticket->auto_overdue_ticket = null;
                    } else {
                        $ticket->auto_overdue_ticket = now()->addDays(setting('AUTO_OVERDUE_TICKET_TIME'));
                    }
                }
            }
        }
        // Auto Overdue Ticket
        $categories = CategoryEnvato::where('category_id', $request->category)->first();
        if ($request->input('envato_id') &&  $categories) {

            $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 = $categoryfind->priority;
        if ($request->subscategory) {
            $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 ($customfield->fieldtypes == 'checkbox') {
                    if ($request->input('custom_' . $customfield->id) != null) {

                        $string = $request->input('custom_' . $customfield->id);
                        $ticketcustomfield->values = $string;
                    }
                }
                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->cust->username;
        $tickethistory->type = $ticket->cust->userType;
        $tickethistory->assignUser = null;
        $tickethistory->commentmodify = null;
        $tickethistory->oldcomment = null;

        $tickethistory->save();


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

        // Create a New ticket reply
        // $notificationcat = $ticket->category->groupscategoryc()->get();
        // $icc = array();
        // if ($notificationcat->isNotEmpty()) {

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

        //         $user = User::whereIn('id', $icc)->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 {
        //     $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));
        //     }
        // }
        $request->session()->put('customerticket', Auth::guard('customer')->id());
        $ccemailsend = CCMAILS::where('ticket_id', $ticket->id)->first();
        $ticketData = [
            'ticket_username' => $ticket->cust->username,
            'ticket_id' => $ticket->ticket_id,
            'ticket_title' => $ticket->subject,
            'ticket_description' => $ticket->message,
            'ticket_status' => $ticket->status,
            'ticket_customer_url' => url('/customer/ticket-view/' . 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'),
        ];
        if (webSocketCheck()) {
            try {
                event(new \App\Events\ConversationEvent(dbname(), null, null, null, null, null, 'tableDataReload', null));
            } catch (\Exception $e) {
                Log::error('Error dispatching WebSocket event: ' . $e->getMessage());
            }
        }
        try {

            if ($ticket->cust->phonesmsenable == 1 && $ticket->cust->phoneVerified == 1 && setting('twilioenable') == 'on') {
                dispatch((new SendSMS($ticket->cust->phone, 'created_ticket', $ticketData)));
            }
            $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) {
                    dispatch((new MailSend($ccemailsend->ccemails, 'customer_send_ticket_created_that_holiday_or_announcement', $ticketData)));
                }
            } else {
                dispatch((new MailSend($ticket->cust->email, 'customer_send_ticket_created', $ticketData)));
                if ($ccemailsend->ccemails) {
                    dispatch((new MailSend($ccemailsend->ccemails, 'customer_send_ticket_created', $ticketData)));
                }
            }


            $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) {
                        $admin->notify(new TicketCreateNotifications($ticket));
                        if ($admin->usetting->emailnotifyon == 1) {
                            dispatch((new MailSend($admin->email, 'admin_send_email_ticket_created', $ticketData)));
                        }
                    }
                } else {

                    // $user = User::whereIn('id', $icc)->where('status', 1)->get();

                    $user = User::whereIn('id', $icc)->where('status', 1)->whereHas('roles', function ($query) {
                        $query->where('name', '!=', 'superadmin');
                    })->get();
                    foreach ($user as $users) {
                        $users->notify(new TicketCreateNotifications($ticket));
                        if ($users->usetting->emailnotifyon == 1) {
                            dispatch((new MailSend($users->email, 'admin_send_email_ticket_created', $ticketData)));
                        }
                    }
                    $superAdmins = User::where('status', 1)->whereHas('roles', function ($query) {
                        $query->where('name', 'superadmin');
                    })->get();

                    foreach ($superAdmins as $admin) {
                        $admin->notify(new TicketCreateNotifications($ticket));
                        if ($admin->usetting->emailnotifyon == 1) {
                            dispatch((new MailSend($admin->email, 'admin_send_email_ticket_created', $ticketData)));
                        }
                    }
                }
            } else {
                foreach (usersdata() as $admin) {
                    $admin->notify(new TicketCreateNotifications($ticket));
                    if ($admin->usetting->emailnotifyon == 1) {
                        dispatch((new MailSend($admin->email, 'admin_send_email_ticket_created', $ticketData)));
                    }
                }
            }
        } catch (\Exception $e) {
        }

        return response()->json(['success' => 'A ticket has been opened with the ticket ID ' . $ticket->ticket_id, 'ticket_id' => encrypt($ticket->ticket_id)], 200);
    }

    public function storeMedia(Request $request)
    {
        $path = public_path('uploads/ticket');

        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(),
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request, $ticket_id)
    {
        $ticket_id = decrypt($ticket_id);
        $ticket = Ticket::with('category', 'media', 'ticket_customfield', 'cust', 'users', 'subcategoriess')->where('ticket_id', $ticket_id)->first();
        if (!$ticket) {
            return response(['noticket' => 'There was no ticket with ' . $ticket_id]);
        }
        $data['ticket'] = $ticket;
        $page       = $request['page'] ?? 1;
        $comments =  Comment::with([
            'cust',
            'user' => function ($query) {
                $query->with('roles');
            },
            'media' => function ($query) {
                $query->where('collection_name', 'comments');
            }
        ])->where('ticket_id', $ticket->id)
            ->latest()->paginate($request['per_page']);

        $data['comments'] = $comments;

        $now = now();
        $holidays = Holiday::whereDate('startdate', '<=', $now->toDateString())->whereDate('enddate', '>=', $now->toDateString())->where('status', 1)->get();
        $data['holidays'] =  $holidays;

        $category = $ticket->category;
        $data['category'] = $category;


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


        if (auth()->guard('customer')->user()) {
            $unreadNotifications = auth()->guard('customer')->user()->unreadNotifications()->get();
            $unreadNotifications->transform(function ($groups) {
                if (isset($groups->data['ticket_id'])) {
                    $groups->enc_ticket_id = encrypt($groups->data['ticket_id']);
                }
                return $groups;
            });
            $data['unreadNotifications'] = $unreadNotifications;
            $data['user'] = auth()->guard('customer')->user();
        }


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

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

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

        $setting = response()->json([
            'USER_REOPEN_ISSUE' => setting('USER_REOPEN_ISSUE'),
            'USER_REOPEN_TIME' => setting('USER_REOPEN_TIME'),
            'USER_FILE_UPLOAD_ENABLE' => setting('USER_FILE_UPLOAD_ENABLE'),
            'FILE_UPLOAD_MAX' => setting('FILE_UPLOAD_MAX'),
            'customer_panel_employee_protect' => setting('customer_panel_employee_protect'),
            'employeeprotectname' => setting('employeeprotectname'),
            'MAXIMUM_ALLOW_REPLIES' => setting('MAXIMUM_ALLOW_REPLIES'),
            'FILE_UPLOAD_TYPES' => setting('FILE_UPLOAD_TYPES'),
            'MAX_FILE_UPLOAD' => setting('MAX_FILE_UPLOAD'),
            'CUSTOMER_TICKET' => setting('CUSTOMER_TICKET'),
            'CUSTOMER_RESTRICT_EDIT_REPLY' => setting('CUSTOMER_RESTRICT_EDIT_REPLY'),
            'custreplyeditwithintime' => setting('custreplyeditwithintime'),
            'default_timezone' => setting('default_timezone'),
            'ANNOUNCEMENT_USER' => setting('ANNOUNCEMENT_USER'),
            'defaultlogin_on' => setting('defaultlogin_on'),
            'KNOWLEDGE_ENABLE' => setting('KNOWLEDGE_ENABLE'),
            'FAQ_ENABLE' => setting('FAQ_ENABLE'),
            'CONTACT_ENABLE' => setting('CONTACT_ENABLE'),
            'REGISTER_POPUP' => setting('REGISTER_POPUP'),
            'REGISTER_DISABLE' => setting('REGISTER_DISABLE'),
            'GUEST_TICKET' => setting('GUEST_TICKET'),
            'login_disable' => setting('login_disable'),
            'login_disable_statement' => setting('login_disable_statement'),
            'terms_url' => setting('terms_url'),
            'CAPTCHATYPE' => setting('CAPTCHATYPE'),
            'RECAPTCH_ENABLE_REGISTER' => setting('RECAPTCH_ENABLE_REGISTER'),
            'RECAPTCH_ENABLE_LOGIN' => setting('RECAPTCH_ENABLE_LOGIN'),
            'GOOGLE_RECAPTCHA_KEY' => setting('GOOGLE_RECAPTCHA_KEY'),
            'bot_name' => setting('bot_name'),
            'bot_image' => setting('bot_image'),
            'theme_color' => setting('theme_color'),
            'theme_color_dark' => setting('theme_color_dark'),
            'LengthTextFieldStatus' => setting('LengthTextFieldStatus'),
            'maxLengthTextField' => setting('maxLengthTextField'),
            'minLengthTextField' => setting('minLengthTextField'),
            'cust_google_translate' => setting('cust_google_translate'),
            'businesshourofflinemsg' => setting('businesshourofflinemsg'),
            'offlineTextTitle' => setting('offlineTextTitle'),
            'offlineTextMessage' => setting('offlineTextMessage'),
        ]);

        $now = now();
        $holidays = Holiday::whereDate('startdate', '<=', $now->toDateString())->where('status', '1')->get();
        if ($holidays->isNotEmpty()) {
            $data['isOnline'] = false;
        } else {
            $businesshours = Businesshours::get();
            $data['businesshours'] = $businesshours;
            foreach ($businesshours as $business) {
                if (now()->timezone(setting('default_timezone'))->format('D') == $business->weeks) {
                    if (strtotime($business->starttime) <= strtotime(now()->timezone(setting('default_timezone'))->format('h:i A')) && strtotime($business->endtime) >= strtotime(now()->timezone(setting('default_timezone'))->format('h:i A')) || $business->starttime == "24H") {
                        $data['isOnline'] = true;
                    } else {

                        $data['isOnline'] = false;
                    }
                }
            }
        }
        $data['setting'] = $setting;

        $data['languages'] = languages();
        $now = now();
        $announcement = announcement::whereDate('enddate', '>=', $now->toDateString())->whereDate('startdate', '<=', $now->toDateString())->get();
        $data['announcement'] = $announcement;

        $announcements = Announcement::whereNotNull('announcementday')->get();
        $data['announcements'] = $announcements;

        $currentYear = $now->year;
        // $currentYear = "2028";
        // $now = Carbon::createFromDate(2024, 01, 26);
        $activeHolidays = Holiday::where('status', 1)->get();

        // Filter holidays
        $data['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);
        });


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

        if ($ticket->cust_id == Auth::guard('customer')->id()) {
            $data['users'] = Auth::guard('customer')->user();
        } else {
            return response()->json(['success' => 'Cannot Access This Ticket']);
        }
        $data['timezonedata'] = Auth::guard('customer')->user()->timezone ?? setting('default_timezone');
        // customer restrict to reply for the ticket.
        $commentsNull = $ticket->comments()->get();
        $latestone = $ticket->comments()->latest('created_at')->first();
        if ($commentsNull->all() != null) {
            foreach ($commentsNull as $latestone) {
                if ($latestone->lastseen == null && $latestone->user_id != null) {
                    $latestone->lastseen = now();
                    $latestone->save();
                    if (webSocketCheck()) {
                        try {
                            event(new ConversationEvent(dbname(), null, null, null, null, null, 'reloadSeenCust', $ticket->ticket_id, null, null));
                        } catch (\Exception $e) {
                            Log::error('Error dispatching WebSocket event: ' . $e->getMessage());
                        }
                    }
                }
            }
        }
        $data['nouser'] =  asset('uploads/profile/user-profile.png');
        if (setting('RESTRICT_TO_REPLY_TICKET') == 'on' && $commentsNull->all() != null && setting('MAXIMUM_ALLOW_REPLIES') > 0) {
            $star1 = now()->subHour(setting('REPLY_ALLOW_IN_HOURS'));
            $star2 = now();
            $latestReplies = $ticket->comments()->whereBetween('created_at', [$star1, $star2])->get()->take(setting('MAXIMUM_ALLOW_REPLIES'));
            $totalcount = 0;
            foreach ($latestReplies as $comment) {
                if ($comment->user_id !== null) {
                    $totalcount++;
                }
            }
            if (!$totalcount) {
                $currentTcikets = $latestReplies->last();
                if ($currentTcikets) {
                    $data['difference'] = $currentTcikets->created_at->addHour(setting('REPLY_ALLOW_IN_HOURS'))->diffForHumans(now());
                    $createdcount = $ticket->comments()->where('cust_id', $ticket->cust_id)->whereBetween('created_at', [$star1, $star2])->count();
                    $data['createdcount'] = $createdcount;
                }
                if ($ticket->cust_id == Auth::guard('customer')->id()) {
                    return $data;
                } else {
                    return response()->json(['error' => 'Cannot Access This Ticket']);
                }
            } else {
                if ($ticket->cust_id == Auth::guard('customer')->id()) {
                    $createdcount = '';
                    $data['createdcount'] = $createdcount;
                    return $data;
                } else {
                    return response()->json(['error' => 'Cannot Access This Ticket']);
                }
            }
        } else {
            if ($ticket->cust_id == Auth::guard('customer')->id()) {
                $createdcount = '';
                $data['createdcount'] = $createdcount;
                return $data;
            } else {
                return response()->json(['error' => 'Cannot Access This Ticket']);
            }
        }
    }

    /**
     * Close the specified ticket.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function close(Request $request, $ticket_id)
    {
        $ticket_id = decrypt($ticket_id);
        $ticket = Ticket::where('ticket_id', $ticket_id)->firstOrFail();

        $ticket->status = 'Re-Open';
        $ticket->replystatus = null;
        $ticket->closedby_user = null;

        $ticket->update();


        $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 = 'Re-opened';
        $tickethistory->username = Auth::guard('customer')->user()->username;
        $tickethistory->type = Auth::guard('customer')->user()->userType;
        $tickethistory->assignUser = null;
        $tickethistory->commentmodify = null;
        $tickethistory->oldcomment = null;

        $tickethistory->save();
        if (webSocketCheck()) {
            try {
                event(new \App\Events\ConversationEvent(dbname(), null, null, null, null, null, 'tableDataReload', null, null));
                event(new \App\Events\ConversationEvent(dbname(), null, 'Reopen', null, null, null, 'customer', $ticket->ticket_id, null));
            } catch (\Exception $e) {
                Log::error('Error dispatching WebSocket event: ' . $e->getMessage());
            }
        }
        $ccemailsend = CCMAILS::where('ticket_id', $ticket->id)->first();

        $ticketData = [
            'ticket_username' => $ticket->cust->username,
            'ticket_id' => $ticket->ticket_id,
            'ticket_title' => $ticket->subject,
            'ticket_description' => $ticket->message,
            'ticket_status' => $ticket->status,
            'ticket_customer_url' => url('/customer/ticket-view/' . 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
        ];
        try {

            if ($ticket->category) {


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

                        if ($ticket->myassignuser) {
                            $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->getRoleNames()[0] != 'superadmin') {
                                        $users->notify(new TicketCreateNotifications($ticket));
                                        if ($users->usetting->emailnotifyon == 1) {
                                            dispatch((new MailSend($users->email, 'admin_sendemail_whenticketreopen', $ticketData)));
                                        }
                                    }
                                }
                            }
                        } else if ($ticket->selfassignuser_id) {
                            $self = User::findOrFail($ticket->selfassignuser_id);
                            if ($self->getRoleNames()[0] != 'superadmin') {
                                $self->notify(new TicketCreateNotifications($ticket));
                                if ($self->usetting->emailnotifyon == 1) {
                                    dispatch((new MailSend($self->email, 'admin_sendemail_whenticketreopen', $ticketData)));
                                }
                            }
                        } else if ($icc) {
                            $user = User::whereIn('id', $icc)->where('status', 1)->get();
                            foreach ($user as $users) {
                                $users->notify(new TicketCreateNotifications($ticket));
                                if ($users->usetting->emailnotifyon == 1) {
                                    dispatch((new MailSend($users->email, 'admin_sendemail_whenticketreopen', $ticketData)));
                                }
                            }
                            $admins = User::get();
                            foreach ($admins as $admin) {
                                if ($admin->getRoleNames()[0] == 'superadmin') {
                                    $admin->notify(new TicketCreateNotifications($ticket));
                                    if ($admin->usetting->emailnotifyon == 1) {
                                        dispatch((new MailSend($admin->email, 'admin_sendemail_whenticketreopen', $ticketData)));
                                    }
                                }
                            }
                        } else {
                            $users = 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 ($users as $user) {
                                if ($user->getRoleNames()[0] != 'superadmin') {
                                    $user->notify(new TicketCreateNotifications($ticket));
                                    if ($user->usetting->emailnotifyon == 1) {
                                        dispatch((new MailSend($user->email, 'admin_sendemail_whenticketreopen', $ticketData)));
                                    }
                                }
                            }
                        }
                    }
                } else {
                    if ($ticket->myassignuser) {
                        $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->getRoleNames()[0] != 'superadmin') {
                                    $users->notify(new TicketCreateNotifications($ticket));
                                    if ($users->usetting->emailnotifyon == 1) {
                                        dispatch((new MailSend($users->email, 'admin_sendemail_whenticketreopen', $ticketData)));
                                    }
                                }
                            }
                        }
                    } else if ($ticket->selfassignuser_id) {
                        $self = User::findOrFail($ticket->selfassignuser_id);
                        if ($self->getRoleNames()[0] != 'superadmin') {
                            $self->notify(new TicketCreateNotifications($ticket));
                            if ($self->usetting->emailnotifyon == 1) {
                                dispatch((new MailSend($self->email, 'admin_sendemail_whenticketreopen', $ticketData)));
                            }
                        }
                    } else {
                        foreach (usersdata() as $user) {
                            if ($user->getRoleNames()[0] != 'superadmin') {
                                $user->notify(new TicketCreateNotifications($ticket));
                                if ($user->usetting->emailnotifyon == 1) {
                                    dispatch((new MailSend($user->email, 'admin_sendemail_whenticketreopen', $ticketData)));
                                }
                            }
                        }
                    }
                }
            } else {
                foreach (usersdata() as $admin) {
                    if ($admin->getRoleNames()[0] == 'superadmin') {
                        $admin->notify(new TicketCreateNotifications($ticket));
                        if ($admin->usetting->emailnotifyon == 1) {
                            dispatch((new MailSend($admin->email, 'admin_sendemail_whenticketreopen', $ticketData)));
                        }
                    }
                }
            }


            dispatch((new MailSend($ticket->cust->email, 'customer_send_ticket_reopen', $ticketData)));
            if ($ccemailsend->ccemails != null) {
                dispatch((new MailSend($ccemailsend->ccemails, 'customer_send_ticket_reopen', $ticketData)));
            }
        } catch (\Exception $e) {
            return response()->json(["success" => 'The ticket has been successfully reopened.']);
        }

        return response()->json(["success" => 'The ticket has been successfully reopened.']);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    // public function destroy($id)
    // {

    //     $ticket = Ticket::findOrFail($id);
    //     $comment = $ticket->comments()->get();

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

    //         foreach ($media as $media) {

    //             $media->delete();
    //         }
    //         $medias = $ticket->comments()->firstOrFail()->getMedia('comments');

    //         foreach ($medias as $mediass) {

    //             $mediass->delete();
    //         }
    //         $comment->each->delete();
    //         $ticket->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::guard('customer')->user()->username;
    //         $tickethistory->type = Auth::guard('customer')->user()->userType;
    //         $tickethistory->assignUser = null;
    //         $tickethistory->commentmodify = null;
    //         $tickethistory->oldcomment = null;
    //         $tickethistory->save();

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

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

    //         foreach ($media as $media) {

    //             $media->delete();
    //         }
    //         $ticket->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::guard('customer')->user()->username;
    //         $tickethistory->type = Auth::guard('customer')->user()->userType;
    //         $tickethistory->assignUser = null;
    //         $tickethistory->commentmodify = null;
    //         $tickethistory->oldcomment = null;

    //         $tickethistory->save();


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

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

        $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()->firstOrFail()->getMedia('comments');

                foreach ($medias as $mediass) {

                    $mediass->delete();
                }
                $comment->each->delete();
                $ticket->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::guard('customer')->user()->username;
                $tickethistory->type = Auth::guard('customer')->user()->userType;
                $tickethistory->assignUser = null;
                $tickethistory->commentmodify = null;
                $tickethistory->oldcomment = null;
                $tickethistory->save();
                foreach ($ticket->ticket_history as $deletetickethistory) {
                    $deletetickethistory->delete();
                }

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

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

                foreach ($media as $media) {

                    $media->delete();
                }
                $ticket->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::guard('customer')->user()->username;
                $tickethistory->type = Auth::guard('customer')->user()->userType;
                $tickethistory->assignUser = null;
                $tickethistory->commentmodify = null;
                $tickethistory->oldcomment = null;
                $tickethistory->save();
                foreach ($ticket->ticket_history as $deletetickethistory) {
                    $deletetickethistory->delete();
                }
            }
        }
        return response()->json(['success' => 'The ticket 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,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function rating($ticket_id)
    {
        $ratingticket = Ratingtoken::where('token', $ticket_id)->first();
        if (!$ratingticket) {

            return response()->json(["error" => 'Your rating has already been submitted.', 'redirect' => 'back']);
        }
        $ticket = Ticket::where('id', $ratingticket->ticket_id)->first();


        $rating = $ticket->comments()->whereNotNull('user_id')->get();
        $comment = Comment::select('user_id')->where('ticket_id', $ticket->id)->distinct()->get();
        $data['rating'] = $rating;
        $data['comment'] = $comment;
        $data['ticket'] = $ticket;
        // $ticket->comments()->select('user_id')->distinct()->get();
        if ($rating->isEmpty()) {
            return response(['redirect' => 'back']);
        } else {
            return $data;
        }
    }

    /// rating system ///
    public function star5($id)
    {

        $user = User::with('usetting')->findorFail($id);
        $user->usetting->increment('star5');
        $user->usetting->update();

        return redirect('customer/')->with('success', 'Thank you for rating us.');
    }

    public function star4($id)
    {

        $user = User::with('usetting')->findorFail($id);
        $user->usetting->increment('star4');
        $user->usetting->update();

        return redirect('customer/')->with('success', 'Thank you for rating us.');
    }

    public function star3($id)
    {

        $user = User::with('usetting')->findorFail($id);
        $user->usetting->increment('star3');
        $user->usetting->update();

        return redirect('customer/')->with('success', 'Thank you for rating us.');
    }

    public function star2($id)
    {

        $user = User::with('usetting')->findorFail($id);
        $user->usetting->increment('star2');
        $user->usetting->update();

        return redirect('customer/')->with('success', 'Thank you for rating us.');
    }

    public function star1($id)
    {

        $user = User::with('usetting')->findorFail($id);
        $user->usetting->increment('star1');
        $user->usetting->update();
        return redirect('customer/')->with('success', 'Thank you for rating us.');
    }

    public function ticketrating(Request $req)
    {

        $ticketfinding = Ticket::find($req->ticket_id);

        $ratingticket = Userrating::where('ticket_id', $req->ticket_id)->first();
        if ($ratingticket) {
            $ratingticket->ratingstar = $req->ratingticket;
            $ratingticket->ratingcomment = $req->ratingcomment;
            $ratingticket->update();

            $employeeratingloop = Employeerating::where('urating_id', $ratingticket->id)->get();
            foreach ($employeeratingloop as $employeeratings) {
                $employeeratings->delete();
            }

            $commentsfind = $ticketfinding->comments()->where('user_id', '!=', null)->distinct()->get();
            foreach ($commentsfind as $commentfinds) {
                $employeerating = new Employeerating();
                $employeerating->urating_id = $ratingticket->id;
                $employeerating->rating = $ratingticket->ratingstar;
                $employeerating->user_id = $commentfinds->user_id;
                $employeerating->save();
            }
        } else {

            $ticketrating = new Userrating();
            $ticketrating->ticket_id = $req->ticket_id;
            $ticketrating->ratingstar = $req->ratingticket;
            $ticketrating->ratingcomment = $req->ratingcomment;
            $ticketrating->cust_id = $ticketfinding->cust->id;
            $ticketrating->save();

            $ticketsfind = Ticket::where('id', $req->ticket_id)->first();
            $commentsfind = $ticketsfind->comments()->where('user_id', '!=', null)->distinct()->get();
            foreach ($commentsfind as $commentfinds) {
                $employeerating = new Employeerating();
                $employeerating->urating_id = $ticketrating->id;
                $employeerating->rating = $ticketrating->ratingstar;
                $employeerating->user_id = $commentfinds->user_id;
                $employeerating->save();
            }
        }
        $ratingticketdelete = Ratingtoken::where('ticket_id', $req->ticket_id)->first();
        $ratingticketdelete->delete();

        return response(['success' => 'Thank you for rating us.']);
    }
    /// end rating system ///

    // Print Ticket
    public function pdfmake($id)
    {
        // $id = decrypt($id);
        $title = Apptitle::first();
        $data['title'] = $title;

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

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

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

        $showprintticket = Ticket::findOrFail($id);
        $data['showprintticket'] = $showprintticket;

        return $data;
    }

    public function commentSeen(Request $req)
    {
        $comment = Comment::where('id', $req->commentId)->first();
        $comment->lastseen = now();
        $comment->save();
        if (webSocketCheck()) {
            try {
                event(new ConversationEvent(null, null, null, null, $comment, 'lastseen', $req->ticketId));
            } catch (\Exception $e) {
                Log::error('Error dispatching WebSocket event: ' . $e->getMessage());
            }
        }
    }
}
