<?php

use Livewire\Component;
use App\Models\Ticket;
use App\Models\TicketMessages;
use Livewire\Attributes\On;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;

new class extends Component {
    use WithFileUploads;

    public Ticket $ticket;
    public $newMessage = '';
    public $replyImages = [];
    public int $ticketId;

    protected $rules = [
        'newMessage' => 'nullable|string',
        'replyImages' => 'nullable|array|max:5', // Max 5 files
        'replyImages.*' => 'file|max:5120|mimes:jpg,jpeg,png,webp,pdf,doc,docx', // 5MB max
    ];

    public function mount(Ticket $ticket)
    {
        if ($ticket->user_id !== Auth::id()) {
            abort(403);
        }

        $this->ticket = $ticket->load('messages.user');
        $this->ticketId = $ticket->id;
    }

    #[On('viewTicket')]
    public function loadTicket(int $id)
    {
        $this->ticketId = $id;
        $this->ticket = Ticket::with('messages.user')->where('user_id', Auth::id())->findOrFail($id);
    }

    #[On('ticketCreated')]
    public function refreshTickets()
    {
        $this->resetPage();
    }

    public function updatedReplyImages()
    {
        if (count($this->replyImages) > 5) {
            $this->replyImages = array_slice($this->replyImages, 0, 5);
            $this->addError('replyImages', 'You can upload a maximum of 5 files.');
        }
    }

    public function removeAttachment($index)
    {
        unset($this->replyImages[$index]);
        $this->replyImages = array_values($this->replyImages);
    }

    public function sendMessage()
    {
        $this->validate();

        // Upload attachments first if any
        $storedAttachments = [];
        foreach ($this->replyImages as $file) {
            $storedAttachments[] = $file->store('ticket-files', 'public');
        }

        // Create a single message combining text + attachments
        if ($this->newMessage || !empty($storedAttachments)) {
            TicketMessages::create([
                'ticket_id' => $this->ticketId,
                'user_id' => Auth::id(),
                'message' => $this->newMessage ?? '',
                'attachments' => $storedAttachments ?: null,
                'updated_at' => now(),
                'is_admin' => false,
            ]);
        }

        // Reset input
        $this->newMessage = '';
        $this->replyImages = [];

        $this->dispatch('showToast', message: 'Message Sent.', type: 'success');

        // Reload ticket messages
        $this->ticket = $this->ticket->fresh('messages.user');
    }
};
?>
 <?php $__env->slot('title', null, []); ?> 
    <?php echo e(config('app.name')); ?> || Ticket Information
 <?php $__env->endSlot(); ?>
<div class="py-4">
    <div class="flex flex-col h-[80vh] bg-white dark:bg-gray-900 shadow rounded">

        
        <div class="p-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
            <div>
                <h2 class="text-lg font-semibold"><?php echo e($ticket->subject); ?></h2>
                <p class="text-sm text-gray-500">
                    Status:
                    <?php
                        // Define colors for each status
                        $statusColors = [
                            'open' => 'text-sky-600 bg-sky-100',
                            'pending' => 'text-yellow-600 bg-yellow-100',
                            'closed' => 'text-red-600 bg-red-100',
                            'in_progress' => 'text-blue-600 bg-blue-100',
                            'resolved' => 'text-green-600 bg-green-100',
                        ];

                        // Pick color, default to gray
                        $statusKey = $ticket->status;
                        $colorClass = $statusColors[$statusKey] ?? 'text-gray-600 bg-gray-100';

                        // Format status: replace underscores and capitalize each word
                        $formattedStatus = collect(explode('_', $ticket->status))
                            ->map(fn($word) => ucfirst($word))
                            ->implode(' ');
                    ?>

                    <span class="px-2 py-1 rounded-full font-medium <?php echo e($colorClass); ?>">
                        <?php echo e($formattedStatus); ?>

                    </span>
                </p>
            </div>

            <a href="<?php echo e(route('user.ticket.index')); ?>" class="text-sm text-blue-500 hover:underline">
                ← Back
            </a>
        </div>

  <!-- User Messages Container (WhatsApp-style) -->
<div id="messagesContainer" class="flex-1 overflow-y-auto p-4 space-y-3 custom-scrollbar">
<?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $ticket->messages; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $msg): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?>
    <div class="flex mb-4 <?php echo e($msg->is_admin ? 'justify-start' : 'justify-end'); ?>">

        
        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($msg->is_admin): ?>
            <div class="mr-2">
                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($msg->admin?->avatar): ?>
                    <img src="<?php echo e(Storage::disk('public')->url($msg->admin->avatar)); ?>"
                         class="w-8 h-8 rounded-full object-cover shadow"
                         alt="Admin avatar" />
                <?php else: ?>
                    <img src="<?php echo e(asset('images/admin-avatar.png')); ?>"
                         class="w-8 h-8 rounded-full object-cover shadow"
                         alt="Admin" />
                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
            </div>
        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

        
        <div class="max-w-[70%] px-4 py-2 rounded-xl shadow
            <?php echo e($msg->is_admin
                ? 'bg-sky-50 dark:bg-sky-900 dark:text-sky-200 rounded-tl-none'
                : 'bg-green-50 dark:bg-green-800 dark:text-green-100 rounded-tr-none'); ?>">

            
            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(!empty($msg->message)): ?>
                <p class="whitespace-pre-line text-sm">
                    <?php echo e($msg->message); ?>

                </p>
            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

            
            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(!empty($msg->attachments)): ?>
                <div class="mt-2 grid gap-2">
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $msg->attachments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $att): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?>
                        <?php
                            $extension = strtolower(pathinfo($att, PATHINFO_EXTENSION));
                        ?>

                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(in_array($extension, ['jpg', 'jpeg', 'png', 'webp'])): ?>
                            <a href="<?php echo e(asset('storage/' . $att)); ?>"
                               target="_blank"
                               class="block">
                                <img src="<?php echo e(asset('storage/' . $att)); ?>"
                                     class="w-28 h-28 object-cover rounded-lg shadow-md hover:scale-105 transition-transform cursor-pointer"
                                     alt="Attachment" />
                            </a>
                        <?php else: ?>
                            <a href="<?php echo e(asset('storage/' . $att)); ?>"
                               target="_blank"
                               class="text-blue-600 underline truncate max-w-xs block">
                                <?php echo e(basename($att)); ?>

                            </a>
                        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                </div>
            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

            
            <p class="mt-1 text-xs text-gray-500 text-right select-none">
                <?php echo e($msg->created_at->format('H:i')); ?>

            </p>
        </div>

        
        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if (! ($msg->is_admin)): ?>
            <div class="ml-2">
                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($msg->user?->profile?->profile_photo): ?>
                    <img src="<?php echo e(Storage::disk('public')->url($msg->user->profile->profile_photo)); ?>"
                         class="w-8 h-8 rounded-full object-cover shadow"
                         alt="<?php echo e($msg->user->name); ?>" />
                <?php else: ?>
                    <div class="w-8 h-8 rounded-full bg-gray-300 flex items-center justify-center text-sm font-semibold text-gray-700">
                        <?php echo e($msg->user?->initials() ?? 'U'); ?>

                    </div>
                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
            </div>
        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

    </div>
<?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>

</div>

        <form wire:submit.prevent="sendMessage"
            class="px-4 py-3 border-t border-gray-200 dark:border-gray-700 flex flex-col gap-3"
            enctype="multipart/form-data">

            
            <?php if (isset($component)) { $__componentOriginal4727f9fd7c3055c2cf9c658d89b16886 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal4727f9fd7c3055c2cf9c658d89b16886 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.textarea','data' => ['wire:model.defer' => 'newMessage','rows' => '2','placeholder' => 'Type your message...']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('textarea'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['wire:model.defer' => 'newMessage','rows' => '2','placeholder' => 'Type your message...']); ?>
<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey($component); ?>
 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal4727f9fd7c3055c2cf9c658d89b16886)): ?>
<?php $attributes = $__attributesOriginal4727f9fd7c3055c2cf9c658d89b16886; ?>
<?php unset($__attributesOriginal4727f9fd7c3055c2cf9c658d89b16886); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal4727f9fd7c3055c2cf9c658d89b16886)): ?>
<?php $component = $__componentOriginal4727f9fd7c3055c2cf9c658d89b16886; ?>
<?php unset($__componentOriginal4727f9fd7c3055c2cf9c658d89b16886); ?>
<?php endif; ?>

            
            <div x-data="{ uploading: false, progress: 0 }" x-on:livewire-upload-start="uploading = true"
                x-on:livewire-upload-finish="uploading = false" x-on:livewire-upload-cancel="uploading = false"
                x-on:livewire-upload-error="uploading = false"
                x-on:livewire-upload-progress="progress = $event.detail.progress" class="flex flex-col gap-2">

                <label
                    class="flex flex-col items-center justify-center p-4 border-2 border-dashed rounded-lg cursor-pointer hover:border-blue-500 text-center text-sm text-gray-400 dark:text-gray-500">
                    Click or drag files here
                    <span class="mt-1">JPG, PNG, WEBP, PDF, DOC (max 5MB each)</span>
                    <input type="file" multiple wire:model="replyImages"
                        accept="image/jpeg,image/jpg,image/png,image/webp,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                        class="hidden">

                </label>

                
                <div x-show="uploading" class="w-full">
                    <progress max="100" x-bind:value="progress"
                        class="w-full h-2 rounded bg-gray-200 dark:bg-gray-700"></progress>
                    <button type="button" wire:click="$cancelUpload('replyImages')"
                        class="mt-1 px-3 py-1 bg-red-600 text-white rounded text-sm">Cancel Upload</button>
                </div>

                
                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($replyImages): ?>
                    <div class="flex flex-wrap gap-2 mt-2">
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $replyImages; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $file): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?>
                            <div <?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processElementKey('reply_{{ $index }}', get_defined_vars()); ?>wire:key="reply_<?php echo e($index); ?>"
                                class="relative w-28 h-28 border rounded p-2 flex flex-col items-center justify-center">
                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(str_contains($file->getMimeType(), 'image')): ?>
                                    <img src="<?php echo e($file->temporaryUrl()); ?>" class="w-full h-full object-cover rounded">
                                <?php else: ?>
                                    <div class="text-xs text-center truncate w-full">
                                        <?php echo e($file->getClientOriginalName()); ?></div>
                                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                <button type="button" wire:click="removeAttachment(<?php echo e($index); ?>)"
                                    class="absolute top-1 right-1 bg-red-600 text-white w-5 h-5 flex items-center justify-center rounded-full">&times;</button>
                            </div>
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                    </div>
                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

                
                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__errorArgs = ['replyImages'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                    <p class="text-red-500 text-sm"><?php echo e($message); ?></p>
                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__errorArgs = ['replyImages.*'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                    <p class="text-red-500 text-sm"><?php echo e($message); ?></p>
                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
            </div>

            
            <div class="flex justify-end">
                <?php if (isset($component)) { $__componentOriginald0f1fd2689e4bb7060122a5b91fe8561 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.button','data' => ['type' => 'submit']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('button'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['type' => 'submit']); ?>
<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey($component); ?>

                    Send
                 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561)): ?>
<?php $attributes = $__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561; ?>
<?php unset($__attributesOriginald0f1fd2689e4bb7060122a5b91fe8561); ?>
<?php endif; ?>
<?php if (isset($__componentOriginald0f1fd2689e4bb7060122a5b91fe8561)): ?>
<?php $component = $__componentOriginald0f1fd2689e4bb7060122a5b91fe8561; ?>
<?php unset($__componentOriginald0f1fd2689e4bb7060122a5b91fe8561); ?>
<?php endif; ?>
            </div>
        </form>

    </div>

    
    <script>
        document.addEventListener('livewire:load', function() {
            const container = document.getElementById('messagesContainer');

            const scrollToBottom = () => container.scrollTop = container.scrollHeight;

            scrollToBottom();

            Livewire.hook('message.processed', () => {
                scrollToBottom();
            });
        });
    </script>


</div>
<?php /**PATH /Users/macuser/Herd/Novabank/resources/views/pages/user/support/⚡show.blade.php ENDPATH**/ ?>