<div class="ticket-details-sidebar">
    <div class="ticket-details-sidebar-close">
        <i class="las la-times"></i>
    </div>
    <p class="ticket-details-sidebar-title">@lang('Details')</p>
    <div class="accordion">
        <div class="accordion ticket-action-accordion" id="ticket-sidebar-accordion">
            <div class="accordion-item">
                <h2 class="accordion-header">
                    <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#ticket-info" aria-expanded="false" aria-controls="ticket-info">
                        <span class="title">
                            <span class="icon">
                                @include('admin.partials.svg.info')
                            </span>
                            @lang('Ticket Info')
                        </span>
                    </button>
                </h2>
                <div id="ticket-info" class="accordion-collapse collapse" data-bs-parent="#ticket-sidebar-accordion">
                    <div class="accordion-body">
                        <div class="ticket-sidebar-info">
                            <div class="ticket-sidebar-info-item">
                                <span class="label">@lang('Ticket ID'):</span>
                                <span class="value">
                                    {{ $ticket->ticket_number }}
                                    <button class="copy-id copyBtn" data-ticket="{{ $ticket->ticket_number }}">
                                        <i class="fa fa-copy"></i>
                                    </button>
                                </span>
                            </div>
                            <div class="ticket-sidebar-info-item">
                                <span class="label">@lang('Created'):</span>
                                <span class="value">
                                    {{ showDateTime($ticket->created_at, 'd M Y') }}
                                </span>
                            </div>
                            <div class="ticket-sidebar-info-item">
                                <span class="label">@lang('Customer Rating'):</span>
                                <span class="value">
                                    @if ($ticket->customer_happiness)
                                        {{ __($ticket->customer_happiness) }}
                                    @else
                                        @lang('Not rated')
                                    @endif
                                </span>
                            </div>
                            <div class="ticket-sidebar-info-item">
                                <span class="label">@lang('Last message'):</span>
                                <span class="value">
                                    {{ diffForHumans($ticket->replies->first()?->created_at) }}
                                </span>
                            </div>

                            <div class="ticket-sidebar-info-item">
                                <label for="department" class="form--label">@lang('Department')</label>
                                <select name="department" class="select2 style-two">
                                    @foreach ($globalValues['departments'] as $department)
                                        <option value="{{ $department->id }}">{{ __($department->name) }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="ticket-sidebar-info-item">
                                <label for="admin" class="form--label">@lang('Agent')</label>
                                <select name="admin" class="select2 style-two">
                                    <option value="0">@lang('Unassign')</option>
                                    @foreach ($globalValues['admins'] as $admin)
                                        <option value="{{ $admin->id }}">{{ $admin->name }}</option>
                                    @endforeach
                                </select>
                            </div>

                            <div class="ticket-sidebar-info-item">
                                <label for="priority" class="form--label">@lang('Priority')</label>
                                <select name="priority" class="select2 style-two">
                                    @foreach ($globalValues['priorities'] as $priority)
                                        <option value="{{ $priority->id }}">{{ __($priority->name) }}</option>
                                    @endforeach
                                </select>
                            </div>

                            <div class="ticket-sidebar-info-item">
                                <label for="status" class="form--label">@lang('Status')</label>
                                <select name="status" class="select2 style-two">
                                    @foreach ($globalValues['statuses'] as $status)
                                        <option value="{{ $status->id }}">{{ __($status->name) }}</option>
                                    @endforeach
                                </select>
                            </div>

                            <div class="ticket-sidebar-info-item">
                                <label for="source" class="form--label">@lang('Tags')</label>
                                <div class="select2-group">
                                    <span class="icon">
                                        @include('admin.partials.svg.tag')
                                    </span>

                                    <select name="tags[]" class="select2 style-two select2-multiple" multiple>
                                        @foreach ($globalValues['tags'] as $tag)
                                            <option value="{{ $tag->id }}" @if ($ticket->tags->contains($tag->id)) selected @endif>{{ $tag->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            @if ($ticket->department_data)
                <div class="accordion-item">
                    <h2 class="accordion-header">
                        <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#department-data" aria-expanded="false" aria-controls="department-data">
                            <span class="title">
                                <span class="icon">
                                    @include('admin.partials.svg.department')
                                </span>
                                @lang('Department Data')
                            </span>
                        </button>
                    </h2>
                    <div id="department-data" class="accordion-collapse collapse" data-bs-parent="#ticket-sidebar-accordion">
                        <div class="accordion-body">
                            @foreach ($ticket->department_data as $deptData)
                                <div class="ticket-sidebar-info-item">
                                    <span class="label">{{ __($deptData->name) }}:</span>
                                    <span class="value">
                                        @if ($deptData->type == 'checkbox')
                                            {{ implode(',', $deptData->value) }}
                                        @elseif($deptData->type == 'file')
                                            @if ($deptData->value)
                                                <a href="{{ route('admin.download.attachment', encrypt(getFilePath('verify') . '/' . $deptData->value)) }}"><i class="fa-regular fa-file"></i> @lang('Attachment') </a>
                                            @else
                                                @lang('No File')
                                            @endif
                                        @else
                                            {{ __($deptData->value) }}
                                        @endif
                                    </span>
                                </div>
                            @endforeach
                        </div>
                    </div>
                </div>
            @endif

            <div class="accordion-item">
                <h2 class="accordion-header">
                    <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#customer-info" aria-expanded="false" aria-controls="customer-info">
                        <span class="title">
                            <span class="icon">
                                @include('admin.partials.svg.user')
                            </span>
                            @lang('Customer Info')
                        </span>
                    </button>
                </h2>
                <div id="customer-info" class="accordion-collapse collapse" data-bs-parent="#ticket-sidebar-accordion">
                    <div class="accordion-body">
                        <div class="ticket-sidebar-info-item">
                            <span class="label">@lang('Name'):</span>
                            <span class="value">{{ $ticket->user->fullname }}</span>
                        </div>
                        <div class="ticket-sidebar-info-item">
                            <span class="label">@lang('Email'):</span>
                            <span class="value">{{ $ticket->user->email }}</span>
                        </div>
                        <div class="ticket-sidebar-info-item">
                            <span class="label">@lang('Mobile'):</span>
                            <span class="value">{{ $ticket->user->mobile ?? '-' }}</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="accordion-item">
                <h2 class="accordion-header">
                    <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#folder-action" aria-expanded="false" aria-controls="folder-action">
                        <span class="title">
                            <span class="icon">
                                @include('admin.partials.svg.folder')
                            </span>
                            @lang('Folders')
                        </span>
                    </button>
                </h2>
                <div id="folder-action" class="accordion-collapse collapse" data-bs-parent="#ticket-sidebar-accordion">
                    <div class="accordion-body">
                        <div class="ticket-sidebar-info">
                            <div class="ticket-sidebar-info-action">
                                <label for="primary" class="content">
                                    <span class="text--body">
                                        @include('admin.partials.svg.ticket')
                                    </span>
                                    @lang('Move to Primary')
                                </label>
                                <span class="action-checkbox">
                                    <div class="form--check">
                                        <input type="radio" name="folder" value="{{ Status::TICKET_PRIMARY }}" id="primary" class="form-check-input" @checked($ticket->folder == Status::TICKET_PRIMARY) />
                                    </div>
                                </span>
                            </div>
                            <div class="ticket-sidebar-info-action">
                                <label for="draft" class="content">
                                    <span class="text--body">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-hand-icon lucide-hand">
                                            <path d="M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2" />
                                            <path d="M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2" />
                                            <path d="M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8" />
                                            <path d="M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15" />
                                        </svg>
                                    </span>
                                    @lang('Move to Draft')
                                </label>
                                <span class="action-checkbox">
                                    <div class="form--check">
                                        <input type="radio" name="folder" value="{{ Status::TICKET_DRAFT }}" id="draft" class="form-check-input" @checked($ticket->folder == Status::TICKET_DRAFT) />
                                    </div>
                                </span>
                            </div>
                            <div class="ticket-sidebar-info-action">
                                <label for="spam" class="content">
                                    <span class="text--warning">
                                        @include('admin.partials.svg.exclamation')
                                    </span>
                                    @lang('Move to Spam')
                                </label>
                                <span class="action-checkbox">
                                    <div class="form--check">
                                        <input type="radio" name="folder" value="{{ Status::TICKET_SPAM }}" id="spam" class="form-check-input" @checked($ticket->folder == Status::TICKET_SPAM) />
                                    </div>
                                </span>
                            </div>
                            <div class="ticket-sidebar-info-action">
                                <label for="trash" class="content">
                                    <span class="text--danger">
                                        @include('admin.partials.svg.delete')
                                    </span>
                                    @lang('Move to Trash')
                                </label>
                                <span class="action-checkbox">
                                    <div class="form--check">
                                        <input type="radio" name="folder" value="{{ Status::TICKET_TRASH }}" id="trash" class="form-check-input" @checked($ticket->folder == Status::TICKET_TRASH) />
                                    </div>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@push('script')
    <script>
        (function($) {
            "use strict";

            $('.copyBtn').on('click', function() {
                var ticketId = $(this).data('ticket');
                navigator.clipboard.writeText(ticketId).then(function() {
                    notify('success', 'Ticket ID copied to clipboard!');
                }, function(err) {
                    notify('error', 'Failed to copy Ticket ID: ' + err);
                });
            });

            let statusId = `{{ $ticket->ticket_status_id }}`;
            let priorityId = `{{ $ticket->priority_id }}`;
            let departmentId = `{{ $ticket->department_id }}`;
            let adminId = `{{ $ticket->assign_staff_id }}`;
            let selectedTags = `{{ json_encode($ticket->tags->pluck('id')->toArray()) }}`;
            selectedTags = JSON.parse(selectedTags);

            let folder = `{{ $ticket->folder }}`;

            $('select[name="status"]').val(statusId).trigger('change');
            $('select[name="priority"]').val(priorityId).trigger('change');
            $('select[name="department"]').val(departmentId).trigger('change');
            $('select[name="admin"]').val(adminId).trigger('change');

            $('[name=status]').on('change', function() {
                statusId = $(this).val();
                saveTicketData();
            });

            $('[name=priority]').on('change', function() {
                priorityId = $(this).val();
                saveTicketData();
            });

            $('[name=department]').on('change', function() {
                departmentId = $(this).val();
                saveTicketData();
            });

            $('[name=admin]').on('change', function() {
                adminId = $(this).val();
                saveTicketData();
            });

            let oldTags = [];

            $('[name="tags[]"]').on('select2:close', function() {
                selectedTags = $(this).val() || [];
                if (JSON.stringify(oldTags) === JSON.stringify(selectedTags)) {
                    return;
                }
                oldTags = selectedTags;

                clearTimeout(window.tagsTimeout);
                window.tagsTimeout = setTimeout(function() {
                    saveTicketData();
                }, 2000);
            });

            $('[name=folder]').on('change', function() {
                folder = $(this).val();
                saveTicketData();
            });

            function saveTicketData() {
                $.ajax({
                    url: "{{ route('admin.ticket.update', $ticket->id) }}",
                    type: "POST",
                    data: {
                        _token: "{{ csrf_token() }}",
                        status: statusId,
                        priority: priorityId,
                        department: departmentId,
                        admin: adminId,
                        tags: selectedTags,
                        folder: folder
                    },
                    success: function(response) {
                        if (response.status === 'error') {
                            notify('error', response.message);
                            return;
                        }

                        $('.departmentName').text(response.data.ticket.department.name);
                        triggerDepartmentChange(response.data.ticket.department_id);
                        $('.adminName').text(response.data.ticket.admin?.name);
                        $('.priorityNameText').text(response.data.ticket.priority.name);
                        $('.statusName').text(response.data.ticket.ticket_status.name);
                        $('.ticketStatus')
                            .text(response.data.ticket.ticket_status.name)
                            .attr('data-hsl', JSON.stringify(response.data.ticket.ticket_status.converted_color));

                        $('.priorityName').attr('data-hsl_color', JSON.stringify(response.data.ticket.priority.converted_color));

                        let tagsHtml = response.data.ticket.tags
                            .map(tag =>
                                `<span class="tag-style tagStyle" data-converted_color='${JSON.stringify(tag.converted_color)}'>${tag.name}</span>`
                            )
                            .join(' ');
                        $('.ticketTags').html(tagsHtml);

                        applyBadgeColors();

                        let $adminSelect = $('select[name="admin"]');
                        $adminSelect.empty();
                        $adminSelect.append(`<option value="">@lang('Select One')</option>`);
                        response.data.admins.forEach(function(admin) {
                            $adminSelect.append(
                                `<option value="${admin.id}"${response.data.ticket.assign_staff_id == admin.id ? ' selected' : ''}>${admin.name}</option>`
                            );
                        });

                        adminId = response.data.ticket.assign_staff_id;

                        notify('success', response.message);
                    },
                    error: function(xhr) {
                        notify('error', 'Failed to update ticket: ' + xhr.responseJSON.message);
                    }
                });
            }

            function triggerDepartmentChange(departmentId) {
                $('.changeDepartment').each(function() {
                    if ($(this).data('department_id') == departmentId) {
                        $(this).trigger('click');
                        return false;
                    }
                });
            };

        })(jQuery);
    </script>
@endpush
