@extends('layouts.master')
@section('title', 'مشاهده تیکت')

@section('breadcrumb')
    <!-- start page title -->
    <div class="row">
        <div class="col-12">
            <div class="page-title-box">
                <div class="page-title-right">
                    <ol class="breadcrumb m-0">
                        <li class="breadcrumb-item"><a href="javascript: void(0);">پنل کاربری</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('panel.tickets.index') }}">تیکت ها</a></li>
                        <li class="breadcrumb-item active">مشاهده تیکت</li>
                    </ol>
                </div>
                <h4 class="page-title">{{ $ticket->subject }}</h4>
            </div>
        </div>
    </div>
    <!-- end page title -->
@endsection

@section('content')

    <div class="row">
        <div class="col">
            <table class="table table-centered table-responsive-sm table-light mb-0 table-bordered">
                <tbody>
                <tr>
                    <td>شماره: {{ $ticket->id }}</td>
                    <td>اولویت: {!! ticket_priority_label($ticket->priority) !!}</td>
                    <td>دپارتمان: {{ $ticket->department->name }}</td>
                    <td>آخرین وضعیت: @if(!$ticket->isClosed())
                            <span class="text-{{ ticket_status_class($ticket->status) }}">{{ ticket_status($ticket->status) }}</span>
                        @else
                            <span class="text-danger">بسته</span>
                        @endif</td>
                    <td>@if($ticket->isReplied())
                            <span class="text-muted">آخرین پاسخ </span>
                            <span title="@jalali($ticket->replies->first()->created_at)" data-toggle="tooltip">@jalali($ticket->replies->first()->created_at,true)</span>
                            <span class="text-muted">توسط </span>
                            <span>{{ \App\User::find($ticket->replies->first()->replied_by)->name }}</span>
                        @else
                            <small class="text-muted">بدون پاسخ</small>
                        @endif
                    </td>
                </tr>
                </tbody>
            </table>
            <div class="card border-0 shadow-sm d-flex flex-row" style="border-top-right-radius: 0;border-top-left-radius: 0; ">
                <div class="ticket-body ml-1 w-100">
                    <div class="clearfix mb-2">
                        <div class="float-left">
                            <img class="rounded-circle mr-1"
                                 src="{{ $ticket->user->getFirstMediaUrl('avatar') ? url($ticket->user->getFirstMediaUrl('avatar')) : asset('assets/images/default-avatar.png') }}"
                                 width="30" alt="تصویر پروفایل">
                            <h5 class="mt-0 d-inline-block">
                                <span>{{ $ticket->user->name }}</span>
                                <small class="text-muted" title="@jalali($ticket->created_at)" data-toggle="tooltip">(@jalali($ticket->created_at,true))</small>
                            </h5>
                        </div>
                        <div class="clearfix mb-1">
                            @if((auth()->user()->isUser() and config('can_user_change_department')) or !auth()->user()->isUser())
                                <select id="DepartmentsList" class="custom-select custom-select-sm float-right ml-1" style="width: auto"
                                        data-refer-ticket="{{ route('panel.tickets.refer', $ticket) }}">
                                    <option value="0" selected disabled>ارجاع به دپارتمان</option>
                                    @foreach(\App\Department::all()->except($ticket->department->id) as $department)
                                        <option value="{{ $department->id }}">{{ $department->name }}</option>
                                    @endforeach
                                </select>
                            @endif
                            @if($ticket->isClosed() and ((auth()->user()->isUser() and config('can_user_reopen_ticket')) or (!auth()->user()->isUser())))
                                <button class="btn btn-sm btn-success float-right ml-1"
                                        data-reopen-ticket="{{ route('panel.tickets.reopen', $ticket) }}">بازگشایی تیکت
                                </button>
                            @elseif((!$ticket->isClosed() and (auth()->user()->isUser() and config('can_user_close_ticket')) or (!auth()->user()->isUser())))
                                <button class="btn btn-sm btn-danger float-right ml-1"
                                        data-close-ticket="{{ route('panel.tickets.close', $ticket) }}">بستن تیکت
                                </button>
                            @endif
                            <a class="float-right text-danger mt-1" href="javascript:void(0)" data-toggle="modal" data-target="#reportTicketModal">
                                <span>گزارش</span>&nbsp;<i class="mdi mdi-alert-circle-outline align-top"></i>
                            </a>
                        </div>
                    </div>
                    {!! clean(nl2br($ticket->content)) !!}
                    @if(!$ticket->getMedia('attach')->isEmpty())
                        <div class="ticket-attaches">
                            <div class="btn-group">
                                <a class="btn btn-light btn-sm dropdown-toggle" href="#" type="button" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    پیوست ها
                                    <i class="remixicon-download-2-line mr-1 align-middle"></i>
                                </a>
                                <div class="dropdown-menu">
                                    @if($ticket->getMedia('attach')->count() > 1)
                                        <a class="dropdown-item" href="{{ route('panel.tickets.attach.all', $ticket) }}">دانلود همه<i class="remixicon-file-zip-line mr-1 align-middle"></i></a>
                                        <div class="dropdown-divider"></div>
                                    @endif
                                    @foreach($ticket->getMedia('attach') as $media)
                                        <a class="dropdown-item" href="{{ route('panel.tickets.attach.download',[$ticket, $media]) }}" data-toggle="tooltip" title="{{ $media->file_name }}"> پیوست شماره {{ $loop->index + 1 }}<i class="remixicon-file-download-line  mr-1 align-middle"></i></a>
                                    @endforeach
                                </div>
                            </div>
                        </div>
                    @else
                        <small class="text-muted">بدون پیوست</small>
                    @endif
                </div>
            </div>
        </div><!-- end col -->
    </div>

    @if(!$ticket->isClosed() or ($ticket->isClosed() and !auth()->user()->isUser()))
        <div id="addReplyContainer" class="collapse show">
            <div class="card card-box">
                <h5 class="text-muted card-title">ارسال پاسخ یا
                    <button class="btn btn-xs btn-secondary" data-toggle="modal" data-target="#quickResponsesModal">انتخاب از پاسخ‌های آماده</button>
                </h5>
                <form action="{{ route('panel.tickets.reply', $ticket) }}" method="post" id="addReplyForm" data-parsley-validate data-ajax-form data-redirect-url="{{ route('panel.tickets.show', $ticket) }}">
                    <div class="form-group">
                        <textarea name="text" id="ReplyText" class="form-control" cols="30" rows="6" placeholder="متن پاسخ را وارد کنید..." required></textarea>
                    </div>
                    <div class="form-group">
                        <div class="result alert" style="display: none"></div>
                    </div>
                    <div class="from-group">
                        <button class="btn btn-bordered-success float-right ml-1" type="submit">ذخیره</button>
                        @if((auth()->user()->isUser() and config('can_user_attach_file')) or !auth()->user()->isUser())
                            <button class="btn btn-bordered-secondary float-right" type="button" data-toggle="modal" data-target="#addFileToTicketModal">
                                <span>افزودن فایل</span>
                                (<span class="files-count">0</span>)
                            </button>
                        @endif
                        @if(auth()->user()->isSuperior())
                            <div class="checkbox checkbox-primary">
                                <input id="isPrivate" type="checkbox" name="is_private" value="1">
                                <label for="isPrivate">
                                    پاسخ محرمانه
                                </label>
                                <small data-toggle="tooltip" title="با فعال کردن این گزینه پاسخ شما تنها برای پشتیبانان و مدیریت قابل مشاهده خواهد و کاربر پاسخ محرمانه را دریافت و مشاهده نخواهد کرد"><i class="fa fa-question-circle"></i></small>
                            </div>
                        @endif
                    </div>
                </form>
            </div>
        </div>
    @endif

    @foreach($ticket->replies as $reply)
        <div class="row">
            <div class="col">
                @if($reply->isUserReply())
                    <div class="card p-3" id="reply-{{$reply->id}}">
                        <div class="reply-header clearfix">
                            <h5 class="text-muted card-title float-left">
                                <img class="rounded-circle mr-1" src="{{ $reply->user->getFirstMediaUrl('avatar') ? url($reply->user->getFirstMediaUrl('avatar')) : asset('assets/images/default-avatar.png') }}" alt="تصویر پروفایل" width="30">
                                {{ $reply->user->name }} <span class="font-13" data-toggle="tooltip" title="@jalali($reply->created_at)">(@jalali($reply->created_at,true))</span>
                            </h5>
                            <small class="float-right">
                                <a class="text-danger" href="javascript:void(0)" data-toggle="modal" data-target="#reportTicketModal" data-report-reply="{{ $reply->id }}">
                                    <span>گزارش</span>&nbsp;
                                    <i class="mdi mdi-alert-circle-outline align-top"></i>
                                </a>
                            </small>
                        </div>
                        <div class="reply-content">{!! clean(nl2br($reply->content)) !!}</div>
                        @if(!$reply->getMedia('attach')->isEmpty())
                            <div class="ticket-attaches">
                                <div class="btn-group">
                                    <a class="btn btn-light btn-sm dropdown-toggle" href="#" type="button" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                        پیوست ها
                                        <i class="remixicon-download-2-line mr-1 align-middle"></i>
                                    </a>
                                    <div class="dropdown-menu">
                                        @if($reply->getMedia('attach')->count() > 1)
                                            <a class="dropdown-item" href="{{ route('panel.tickets.attach.all', $ticket) }}">دانلود همه<i class="remixicon-file-zip-line mr-1 align-middle"></i></a>
                                            <div class="dropdown-divider"></div>
                                        @endif
                                        @foreach($reply->getMedia('attach') as $media)
                                            <a class="dropdown-item" href="{{ route('panel.tickets.attach.download',[$ticket, $media]) }}" data-toggle="tooltip" title="{{ $media->file_name }}"> پیوست شماره {{ $loop->index + 1 }}<i class="remixicon-file-download-line  mr-1 align-middle"></i></a>
                                        @endforeach
                                    </div>
                                </div>
                            </div>
                        @endif
                        @if((config('ticket_signature') == 'user' or config('ticket_signature') == 'both') and $reply->user->signature)
                            <div class="signature">
                                {!! clean(nl2br($reply->user->signature)) !!}
                            </div>
                        @endif
                    </div>
                @else
                    <div class="card p-2 admin-reply" id="reply-{{$reply->id}}">
                        <div class="reply-header mb-2">
                            <div class="clearfix">
                                <h5 class="text-muted card-title mb-1 float-left">
                                    <img class="rounded-circle mr-1" src="{{ $reply->user->getFirstMediaUrl('avatar') ? url($reply->user->getFirstMediaUrl('avatar')) : asset('assets/images/default-avatar.png') }}" alt="تصویر پروفایل" width="30">
                                    {{ $reply->user->name }}
                                    @if($reply->user->isSuperiorStaff())
                                        <span class="text-warning" data-toggle="tooltip" title="پشتیبان برتر">
                                        <i class="remixicon-award-fill"></i>
                                    </span>
                                    @endif
                                    <span class="font-13" data-toggle="tooltip" title="@jalali($reply->created_at)">(@jalali($reply->created_at,true))</span>
                                </h5>
                                <small class="float-right">
                                    <a class="text-danger" href="javascript:void(0)" data-toggle="modal" data-target="#reportTicketModal" data-report-reply="{{ $reply->id }}">
                                        <span>گزارش</span>&nbsp;
                                        <i class="mdi mdi-alert-circle-outline align-top"></i>
                                    </a>
                                </small>
                            </div>
                            <div class="star-rating @if($reply->isRated() or !auth()->user()->isUser()) rated @endif" @if(!$reply->isRated()) data-rate-reply="{{ route('panel.replies.rate', $reply) }}" @else data-rating="{{ $reply->rate }}" @endif></div>
                        </div>
                        @if($reply->is_private)
                            <small class="text-pink">* این پاسخ به صورت محرمانه ارسال شده است</small>
                        @endif
                        <div class="reply-content">{!! clean(nl2br($reply->content)) !!}</div>
                        @if(!$reply->getMedia('attach')->isEmpty())
                            <div class="ticket-attaches">
                                <div class="btn-group">
                                    <a class="btn btn-light btn-sm dropdown-toggle" href="#" type="button" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                        پیوست ها
                                        <i class="remixicon-download-2-line mr-1 align-middle"></i>
                                    </a>
                                    <div class="dropdown-menu">
                                        @if($reply->getMedia('attach')->count() > 1)
                                            <a class="dropdown-item" href="{{ route('panel.tickets.attach.all', $ticket) }}">دانلود همه<i class="remixicon-file-zip-line mr-1 align-middle"></i></a>
                                            <div class="dropdown-divider"></div>
                                        @endif
                                        @foreach($reply->getMedia('attach') as $media)
                                            <a class="dropdown-item" href="{{ route('panel.tickets.attach.download',[$ticket, $media]) }}" data-toggle="tooltip" title="{{ $media->file_name }}"> پیوست شماره {{ $loop->index + 1 }}<i class="remixicon-file-download-line  mr-1 align-middle"></i></a>
                                        @endforeach
                                    </div>
                                </div>
                            </div>
                        @endif
                        @if((config('ticket_signature') == 'superior' or config('ticket_signature') == 'both') and $reply->user->signature)
                            <div class="signature">
                                {!! clean(nl2br($reply->user->signature)) !!}
                            </div>
                        @endif
                    </div>
                @endif
            </div>
        </div>
    @endforeach

    <!-- REPORT TICKET MODAL -->

    <x-modal title="گزارش تیکت" id="reportTicketModal" formId="reportTicketForm" isAjax="true" action="{{ route('panel.reports.store') }}" method="post">
        <input type="hidden" name="ticket_id" value="{{ $ticket->id }}"/>
        <input type="hidden" name="reply_id" id="replyId" value="">
        <div class="alert alert-info">گزارش شما مستقیما توسط مدیریت بررسی خواهد شد</div>
        <div class="form-group">
            <label for="reportContent">متن گزارش</label>
            <textarea name="content" id="reportContent" class="form-control" cols="30" rows="5" placeholder="متن گزارش را وارد کنید..."></textarea>
        </div>
        <div class="result alert" style="display:none"></div>
    </x-modal>

    <!-- ADD QUICK RESPONSE MODAL -->

    <x-modal title="انتخاب پاسخ آماده" id="quickResponsesModal">
        <div class="accordion accordion-flush" id="quickResponsesAccordion">
            @forelse($quickResponses as $quickResponse)
                <div class="accordion-item bg-light mb-1 border-0">
                    <h2 class="accordion-header" id="quick-response-header-{{ $loop->iteration }}">
                        <button class="accordion-button collapsed" type="button" data-toggle="collapse" data-target="#qs{{ $loop->iteration }}" aria-expanded="false" aria-controls="quick-response-{{ $loop->iteration }}">
                            {{ $quickResponse->title }}
                        </button>
                    </h2>
                    <div id="qs{{ $loop->iteration }}" class="accordion-collapse collapse" aria-labelledby="quick-response-header-{{ $loop->iteration }}" data-parent="#quickResponsesAccordion" style="">
                        <div class="accordion-body">{{$quickResponse->text}}</div>
                    </div>
                </div>
            @empty
                <p>داده‌ای یافت نشد</p>
            @endforelse

            @if(count($quickResponses) > 0)
                <button class="btn btn-sm btn-secondary float-right select-quick-response-btn" disabled>انتخاب</button>
            @endif

        </div>
    </x-modal>


    <!-- DROPZONE UPLOAD MODAL -->

    <x-modal title="افزودن فایل به تیکت" id="addFileToTicketModal" size="modal-lg">
        <div class="alert alert-light border-right">
            <span>شما میتوانید حداکثر </span>
            <span class="text-primary">{{ config('upload_max_file_count') }}</span>
            <span> تا فایل آپلود کنید</span>
        </div>
        <div class="alert alert-light border-right">
            <span>هر فایل شما نباید بیشتر از </span>
            <span class="text-primary">{{ config('upload_max_file_size') }}</span>
            <span>  مگابایت حجم داشته باشد</span>
        </div>
        <form action="{{ route('panel.tickets.storeFile') }}" method="post" class="dropzone" id="addFileForm" data-plugin="dropzone" data-previews-container="#file-previews"
              data-upload-preview-template="#uploadPreviewTemplate">
            @csrf
            <div class="fallback">
                <input name="file" type="file" multiple />
            </div>

            <div class="dz-message needsclick">
                <p class="h1 text-muted"><i class="mdi mdi-cloud-upload"></i></p>
                <h3>فایل ها را برای آپلود به اینجا بکشید و رها کنید</h3>
            </div>
        </form>

        <!-- Preview -->
        <div class="dropzone-previews mt-3" id="file-previews"></div>
    </x-modal>

@endsection

@section('script')
    @php
        $timeout = 999;
        if (ini_get('max_input_time') == -1) {
            $timeout = ini_get('max_execution_time');
        } elseif (ini_get('max_input_time') > 0) {
            $timeout = ini_get('max_input_time');
        }

        $timeout *= 1000;
    @endphp
    <script>
    $(document).ready(function(){

        $('#quickResponsesAccordion').on('hidden.bs.collapse', function () {
            $('.select-quick-response-btn').attr('disabled', 'disabled')
        })

        $('#quickResponsesAccordion').on('shown.bs.collapse', function () {
            $('.select-quick-response-btn').removeAttr('disabled')
        })

        $('.select-quick-response-btn').click(function() {
            $('#ReplyText').html('')
            $('#ReplyText').html($('#quickResponsesAccordion .accordion-collapse.collapse.show .accordion-body').html())
            $('#quickResponsesModal').modal('hide')
        })

        // check if url has #reply-* to focus that reply
        if(window.location.hash.indexOf('reply-') > -1){
            $(window.location.hash).parent().addClass('focused-reply');
            $('html, body').animate({
                scrollTop: $(window.location.hash).parent().offset().top - 80
            }, 1300)
        }
    });

    var uploadedDocumentMap = {}
    var filesCount = 0
    Dropzone.options.addFileForm = {
        /*url: '',*/
        maxFilesize: '{{ config('upload_max_file_size') }}', // MB
        maxFiles: '{{ config('upload_max_file_count') }}',
        timeout: '{{ $timeout }}',
        addRemoveLinks: true,
        acceptedFiles: '{{ config('upload_allowed_formats') }}',
        headers: {
            'X-CSRF-TOKEN': "{{ csrf_token() }}"
        },
        success: function (file, response) {
            $('#addReplyForm')
                .append('<input type="hidden" name="attach[]" value="' + response.name + '" id="' + response.id + '">')
            $('#addReplyForm')
                .append('<input type="hidden" name="attachName[]" value="' + response.original_name + '" data-related="#' + response.id + '">')
            uploadedDocumentMap[file.name] = response.name
            $('.files-count').text($('input[name="attach[]"]').length)
        },
        removedfile: function (file) {
            file.previewElement.remove()
            var name = ''
            if (typeof file.file_name !== 'undefined') {
                name = file.file_name
            } else {
                name = uploadedDocumentMap[file.name]
            }
            var attachInput = $('#addReplyForm').find('input[name="attach[]"][value="' + name + '"]');
            attachInput.remove();
            $('#addReplyForm').find('[data-related="#' + attachInput.attr('id') + '"]').remove()
            $('.files-count').text($('input[name="attach[]"]').length)
        },
    }
    </script>

@endsection
