@extends('layouts.user-panel.master')

@section('css')
    <link rel="stylesheet" href="{{ asset('assets/css/star-rating.min.css') }}">
    <link rel="stylesheet" href="{{ asset('assets/css/dropzone.min.css') }}">
@endsection


@section('content')
    <div class="row mt-2">
        <div class="col">
            <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 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-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-danger float-right ml-1"
                            data-close-ticket="{{ route('panel.tickets.close', $ticket) }}">بستن تیکت
                    </button>
                @endif
                @if(!$ticket->isClosed() or ($ticket->isClosed() and !auth()->user()->isUser()))
                    <button class="btn btn-secondary float-right" id="addReplyBtn" type="button" data-toggle="collapse"
                            data-target="#addReplyContainer" aria-expanded="false" aria-controls="addReplyContainer">
                        ارسال پاسخ
                    </button>
                @endif
            </div>
            <div class="card d-flex flex-row">
                <div class="ticket-meta">
                    <div class="ticket-id">{{ $ticket->id }}</div>
                    <div class="ticket-title">
                        <h3 class="text-primary my-0">{{ $ticket->subject }} <span
                                    class="font-15 align-text-bottom ml-1">{!!  ticket_priority_label($ticket->priority) !!}</span>
                        </h3>
                        <p class="mb-1">{{ $ticket->department->name }} - @if(!$ticket->isClosed())<span
                                    class="text-{{ ticket_status_class($ticket->status) }}">{{ ticket_status($ticket->status) }}</span>@else
                                <span class="text-danger">بسته</span> @endif</p>
                        <p class="mb-0">
                            @if($lastReply)
                                <span class="text-muted">آخرین پاسخ </span>
                                <span title="@jalali($lastReply->created_at,false)">@jalali($lastReply->created_at,true)</span>
                                <span class="text-muted">توسط </span>
                                <span>{{ \App\User::find($lastReply->first()->replied_by)->name }}</span>
                            @else
                                <small class="text-muted">بدون پاسخ</small>
                            @endif
                        </p>
                    </div>
                </div>
                <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="تصویر پروفایل">
                            <h4 class="mt-0 d-inline-block">{{ $ticket->user->name }}</h4>
                        </div>
                        <div class="float-right text-muted text-center ml-2">
                            <small>شماره پیگیری:</small>
                            <small>{{ $ticket->track_id }}</small>
                        </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">
            <div class="card card-box">
                <h5 class="text-muted card-title">ارسال پاسخ</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()->isSuperior())
                            <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
                    </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">
                            <h5 class="text-muted card-title">
                                <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">(@jalali($reply->created_at,true))</span>
                            </h5>
                        </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">(@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>
                        <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>

    <!-- 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 () {
            // 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 - 140
                }, 1300)
            }
        });// DOC READY
    </script>
    <script src="{{ asset('assets/js/dropzone.min.js') }}"></script>
    <script>
        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
