@extends('admin.layouts.app')

@section('title', $title)

@section('content')
    <div class="col-md-12">

        @include('admin.layouts.notifications')

        <!-- Error Messages -->
        @include('admin.layouts.errors')

        <!-- Page Heading -->
        <div class="row mb-3 align-items-center">
            <div class="col">
                <h4 class="c-grey-900 d-flex">
                    {{ $title }} <span class="text-muted">&nbsp;{{ $ticket->subject }}</span>
                </h4>
            </div>
        </div>

        <!-- Ticket Details -->
        <div class="row">

            <!-- Left Section (Messages Section) -->
            <div class="col-md-8">
                @foreach($messages as $message)
                    <div class="card mb-3 shadow-sm {{ $message->user->roles[0]->display_name == 'Customer' ? 'message-customer-wrapper' : 'message-staff-wrapper' }}">
                        <div class="card-body">
                            <!-- Message Header: Sender's Name, Role, and Timestamp -->
                            <div class="d-flex justify-content-between align-items-center">
                                <span>
                                    <span class="sender-name">{{ $message->user->first_name }} {{ $message->user->last_name }}</span>
                                    <span class="badge {{ $message->user->roles[0]->display_name == 'Customer' ? 'bg-info' : 'bg-success' }}">
                                        {{ $message->user->roles[0]->display_name == 'Customer' ? 'Customer' : 'Administrator' }}
                                    </span>
                                </span>
                                <p>{{ $message->created_at->diffForHumans() }}</p>
                            </div>

                            <!-- Message Content -->
                            <p class="card-text">{!! $message->message_content !!}</p>

                            <!-- Message Box Footer Section -->
                            <div class="row">
                                <!-- Attachments Section (if any) -->
                                @if($message->media->isNotEmpty())
                                    <div class="col-md-8">
                                        <div class="attachments">
                                            <h6>Attachments:</h6>
                                            <ul>
                                                @foreach($message->media as $media)
                                                    <li><a href="{{ $media->TempUrl }}" target="_blank">{{ $media->name }}</a> ({{ $media->mime_type }})</li>
                                                @endforeach
                                            </ul>
                                        </div>
                                    </div>
                                @endif

                                <!-- Message Actions (Edit/Delete) -->
                                @if(auth()->user()->id === $message->user_id)
                                    <div class="col-md-4 d-flex justify-content-end align-items-start">
                                        <div class="mt-auto message-actions">
                                            <button class="btn btn-xs btn-primary me-2 edit-message-btn" title="Edit Message" data-message-id="{{ $message->id }}"><i class="fa fa-pencil"></i></button>
                                            <form action="{{ route('ch-admin.ticket.message.delete', $message->id) }}" method="POST" style="display:inline;">
                                                @csrf
                                                @method('DELETE')
                                                <button class="btn btn-xs btn-danger" title="Delete Message" onclick="return confirm('Are you sure you want to delete this message?')">
                                                    <i class="fa fa-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                @endif
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>

            <!-- Right Section (Ticket Editable fields) -->
            <div class="col-md-4">
                <div class="bgc-white bd bdrs-3 p-20 mB-20">
                    <h6 class="c-grey-900">Ticket Information</h6>

                    <!-- Form to Update Status and Priority -->
                    <form method="POST" action="{{ route('ch-admin.ticket.update', $ticket->id) }}">
                        @csrf
                        @method('PUT')

                        <!-- User Field -->
                        <div class="form-group mb-3">
                            <label for="user_id" class="form-label">User</label>
                            <input type="text" class="form-control" value="{{ $ticket->user->first_name }} {{ $ticket->user->last_name }}" disabled>
                        </div>

                        <!-- Status Field -->
                        <div class="form-group mb-3">
                            <label for="status" class="form-label">Status</label>
                            <select name="status" id="status" class="form-control" required>
                                <option value="">Select Status</option>
                                <option value="Open" {{ $ticket->status == 'Open' ? 'selected' : '' }}>Open</option>
                                <option value="In Progress" {{ $ticket->status == 'In Progress' ? 'selected' : '' }}>In Progress</option>
                                <option value="Resolved" {{ $ticket->status == 'Resolved' ? 'selected' : '' }}>Resolved</option>
                                <option value="Closed" {{ $ticket->status == 'Closed' ? 'selected' : '' }}>Closed</option>
                            </select>
                        </div>

                        <!-- Priority Field -->
                        <div class="form-group mb-3">
                            <label for="priority" class="form-label">Priority</label>
                            <select name="priority" id="priority" class="form-control" required>
                                <option value="">Select Priority</option>
                                <option value="Low" {{ $ticket->priority == 'Low' ? 'selected' : '' }}>Low</option>
                                <option value="Medium" {{ $ticket->priority == 'Medium' ? 'selected' : '' }}>Medium</option>
                                <option value="High" {{ $ticket->priority == 'High' ? 'selected' : '' }}>High</option>
                                <option value="Critical" {{ $ticket->priority == 'Critical' ? 'selected' : '' }}>Critical</option>
                            </select>
                        </div>

                        <!-- Category Field -->
                        <div class="form-group mb-3">
                            <label for="category_id" class="form-label">Category</label>
                            <select id="category_id" name="category_id" class="form-control">
                                <option value="">Select Category</option>
                                @foreach ($ticketCategories as $category)
                                    <option value="{{ $category->id }}"{{ $ticket->category_id == $category->id ? 'selected' : '' }}>{{ $category->name }}</option>
                                @endforeach
                            </select>
                        </div>

                        <!-- Submission Button -->
                        <div class="mt-3">
                            <div class="row">
                                <div class="col-12 mb-2">
                                    <button class="btn btn-success add-message-btn w-100" type="button">
                                        <i class="ti-plus"></i> Add new message
                                    </button>
                                </div>
                                <div class="col-12 d-flex justify-content-between">
                                    <a href="{{ route('ch-admin.ticket.index') }}" class="btn btn-secondary w-50 me-1">All Tickets</a>
                                    <button type="submit" class="btn btn-primary w-50 ms-1">Update Ticket</button>
                                </div>
                            </div>
                        </div>

                    </form>

                </div>
            </div>

        </div>

    </div>

    <!-- Modal for Adding message -->
    <div class="modal fade modal-xl" id="messageModal" tabindex="-1" aria-labelledby="messageModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="messageForm" method="POST">
                    @csrf
                    <!-- Modal Header Section -->
                    <div class="modal-header">
                        <h5 class="modal-title modal-header-title" id="messageModalLabel">Message</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>

                    <!-- Modal Body Section -->
                    <div class="modal-body">

                        <!-- Message Content -->
                        <div class="form-group">
                            <label for="message_content" class="form-label">Message</label>
                            <textarea name="message_content" id="message_content" class="form-control"></textarea>
                        </div>

                        <!-- Attachments Field START -->
                        <div class="form-group mt-3">
                            <div class="col-sm-6">
                                <div class="uploader">
                                    <button
                                        id="attachments"
                                        data-media-config='{"key": "attachments", "container": ".attachments-container", "previewsContainer": ".attachments-container-preview", "disk": "local"}'
                                        type="button"
                                        class="btn btn-primary btn-sm text-white dropzone"
                                        :disabled="loading">
                                        <i class="ti-plus"></i> Add Attachments
                                    </button>
                                    <br>

                                    <div class="attachments-container"></div>
                                    <div class="attachments-container-preview mt-3"></div>
                                </div>
                            </div>
                        </div>
                        <!-- Attachments Field END -->

                    </div>

                    <!-- Modal Footer Section -->
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary close-modal-button" data-bs-dismiss="modal">Close</button>
                        <button class="btn btn-primary submit-message-button">Add message</button>
                    </div>

                </form>
            </div>
        </div>
    </div>
@endsection

@push('head')
    <link rel="stylesheet" href="{{ url('assets/backend/css/jodit.min.css') }}">
    <script src="{{ url('assets/backend/js/vendors/jodit.min.js') }}"></script>
@endpush

@push('scripts')
    @include('admin.media.upload')
    <script src="{{ url('assets/backend/js/vendors/dropzone.min.js') }}"></script>
    <script src="{{ url('assets/backend/js/media.js') }}"></script>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const editorInstance = Jodit.make('#message_content', {
                height: 350,
                buttons: 'bold,italic,underline,strikethrough,eraser,|,ul,ol,|,paragraph,|,link,image,hr,|,align,|,source,|,undo,redo',
            });

            // Modal and button variables
            const addButton = document.querySelector('.add-message-btn');
            const editButtons = document.querySelectorAll('.edit-message-btn');
            const messageModalHeaderTitle = document.querySelector('.modal-header-title');
            const submitMessageButton = document.querySelector('.submit-message-button');
            const messageModal = new bootstrap.Modal(document.getElementById('messageModal'));
            const form = document.getElementById('messageForm');

            // Handle 'Add message' button click
            addButton.addEventListener('click', () => {
                messageModal.show();
                messageModalHeaderTitle.textContent = "Add Message";
                submitMessageButton.textContent = "Add message";
                form.action = '{{ route('ch-admin.ticket.message.store', ['ticketId' => $ticket->id]) }}';
                form.appendChild(createHiddenInput('_method', 'POST'));
                editorInstance.value = '';
            });

            // Handle 'Edit message' button click
            editButtons.forEach(button => {
                button.addEventListener('click', (event) => {
                    const messageId = event.target.getAttribute('data-message-id');
                    form.action = `{{ route('ch-admin.ticket.message.update', ':id') }}`.replace(':id', messageId);
                    form.appendChild(createHiddenInput('_method', 'PUT'));

                    httpClient.get(`{{ route('ch-admin.ticket.message.edit', ':id') }}`.replace(':id', messageId))
                        .then(response => {
                            const data = response.data;

                            editorInstance.value = data.message_content;

                            const mediaArray = data.media;
                            const uploadButton = document.getElementById('attachments');
                            uploadButton.setAttribute('data-files', JSON.stringify(mediaArray));

                            Dropzone.instances.forEach(instance => {
                                instance.destroy();
                            });

                            initializeDropzone(document.querySelector('.uploader .dropzone'));

                            messageModal.show();
                            messageModalHeaderTitle.textContent = "Edit Message";
                            submitMessageButton.textContent = "Update Message";
                        })
                        .catch(error => {
                            console.error(error);
                            alert('An error occurred. Please try again.');
                        });
                });
            });

            // Clear form fields when the modal is closed
            document.getElementById('messageModal').addEventListener('hidden.bs.modal', () => {
                form.reset();
                editorInstance.value = '';
            });

            // Helper function to create hidden input fields
            function createHiddenInput(name, value) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = name;
                input.value = value;
                return input;
            }
        });
    </script>
@endpush
