<?php

    namespace App\Livewire\Tickets;

    use App\Models\Responses as Replies;
    use App\Models\{Tickets,User};
    use Illuminate\Support\Facades\Auth;
    use Livewire\Component;

    class Responses extends Component
    {
        public $ticket_id;

        public function mount($ticket_id)
        {
            $this->ticket_id = $ticket_id;
        }

        public function render()
        {
            if (Auth::check() and Auth::user()->id) {
                $user_id = Auth::user()->id;
            }
            if (Auth::check()) {
                $check_ticket = Tickets::where('tickets.id', '=', $this->ticket_id)
                    ->where('tickets.user_id', '=', $user_id)
                    ->first();
            } else {
                $check_ticket = Tickets::where('tickets.id', '=', $this->ticket_id)
                    ->first();
            }
            if ($check_ticket != null or Auth::user()->hasAnyRole('superadmin', 'admin', 'employee')) {
                
                $ticket = Tickets::where('tickets.id', '=', $this->ticket_id)
                    ->leftJoin('users', 'tickets.user_id', '=', 'users.id')
                    ->select('tickets.*', 'users.name as user_name', 'users.email')
                    ->first();

                $responses = Replies::where('responses.ticket_number', '=', $this->ticket_id)
                    ->leftJoin('users', 'responses.user_id', '=', 'users.id')
                    ->leftJoin('tickets', 'responses.ticket_number', '=', 'tickets.id')
                    ->select(
                        'responses.*',
                        'users.name',
                        'users.email',
                        'users.company',
                        'tickets.public_name',
                        'tickets.public_email'
                    )
                    ->selectRaw('users.company as company_name, users.id as client_id, responses.id as response_id, responses.created_at as response_created')
                    ->with('attachments')
                    ->orderBy('response_id', config('ticaga.sorting'))->get();
                return view('livewire.tickets.responses', [
                    'responses' => $responses,
                    'ticket' => $ticket,
                    'ip_address' => app('request')->ip(),
                ]);

            } else {
                return false;
            }
        }
}
