@extends('client.layouts.app')

@section('title', $order->order_number)
@section('page_title', $order->title)

@section('content')

<div class="grid lg:grid-cols-3 gap-6">

    <div class="lg:col-span-2 space-y-6">

        {{-- Үндсэн мэдээлэл --}}
        <div class="bg-white rounded-2xl border border-gray-100 p-6">
            <div class="flex items-center justify-between mb-4">
                <div>
                    <div class="text-xs text-gray-500 mb-1">{{ $order->order_number }}</div>
                    <h2 class="text-xl font-bold">{{ $order->title }}</h2>
                </div>
                <span class="text-xs px-3 py-1 rounded-full bg-{{ $order->statusColor() }}-100 text-{{ $order->statusColor() }}-700">{{ $order->statusLabel() }}</span>
            </div>

            <div class="prose prose-sm max-w-none mb-4">
                {!! nl2br(e($order->description)) !!}
            </div>

            <dl class="grid grid-cols-2 gap-4 text-sm pt-4 border-t border-gray-100">
                @if($order->service)<div><dt class="text-xs text-gray-500">Үйлчилгээ</dt><dd class="font-semibold">{{ $order->service->title }}</dd></div>@endif
                <div><dt class="text-xs text-gray-500">Илгээсэн</dt><dd class="font-semibold">{{ $order->created_at->format('Y-m-d') }}</dd></div>
                @if($order->deadline)<div><dt class="text-xs text-gray-500">Эцсийн өдөр</dt><dd class="font-semibold">{{ $order->deadline->format('Y-m-d') }}</dd></div>@endif
                @if($order->budget)<div><dt class="text-xs text-gray-500">Төсөв</dt><dd class="font-semibold">{{ number_format($order->budget) }} ₮</dd></div>@endif
            </dl>

            @if($order->attachmentUrls())
            <div class="mt-4 pt-4 border-t border-gray-100">
                <h4 class="text-xs font-semibold text-gray-500 mb-2">Хавсралтууд</h4>
                <div class="flex flex-wrap gap-2">
                    @foreach($order->attachmentUrls() as $a)
                        <a href="{{ $a['url'] }}" target="_blank" class="text-sm text-nsma-red hover:underline flex items-center gap-1">
                            📎 {{ $a['name'] }}
                        </a>
                    @endforeach
                </div>
            </div>
            @endif
        </div>

        {{-- Чат --}}
        <div class="bg-white rounded-2xl border border-gray-100 p-6">
            <h3 class="font-bold mb-4">Захидал харилцаа</h3>

            <div id="messages-list" class="space-y-3 mb-4 max-h-96 overflow-y-auto">
                @forelse($visibleMessages as $m)
                    @php $isAdmin = $m->sender_type === \App\Models\User::class; @endphp
                    <div class="flex {{ $isAdmin ? 'justify-start' : 'justify-end' }}">
                        <div class="max-w-md p-3 rounded-2xl {{ $isAdmin ? 'bg-gray-100 text-gray-900' : 'bg-nsma-red text-white' }}">
                            <div class="flex items-center justify-between mb-1 text-xs {{ $isAdmin ? 'text-gray-500' : 'text-white/80' }}">
                                <span class="font-semibold">{{ $isAdmin ? 'NSMA баг' : 'Та' }}</span>
                                <span class="ml-3">{{ $m->created_at->format('Y-m-d H:i') }}</span>
                            </div>
                            <div class="text-sm whitespace-pre-wrap">{{ $m->message }}</div>
                            @if($m->attachmentUrls())
                                <div class="mt-2 space-y-1">
                                    @foreach($m->attachmentUrls() as $a)
                                        <a href="{{ $a['url'] }}" target="_blank" class="text-xs underline {{ $isAdmin ? 'text-nsma-red' : 'text-white' }} block">📎 {{ $a['name'] ?? 'хавсралт' }}</a>
                                    @endforeach
                                </div>
                            @endif
                        </div>
                    </div>
                @empty
                    <p class="text-sm text-gray-500 text-center py-6">Зурвас байхгүй байна.</p>
                @endforelse
            </div>

            {{-- Шинэ зурвас --}}
            <form id="message-form" enctype="multipart/form-data" class="border-t border-gray-100 pt-4">
                <textarea name="message" rows="3" required placeholder="Зурвас бичих..." class="w-full px-3 py-2 border border-gray-200 rounded-lg outline-none text-sm"></textarea>
                <div class="flex items-center justify-between mt-2">
                    <input type="file" name="attachments[]" multiple class="text-xs">
                    <button type="submit" class="bg-nsma-red text-white font-semibold px-4 py-2 rounded-lg text-sm hover:bg-red-600">Илгээх</button>
                </div>
            </form>
        </div>
    </div>

    {{-- Sidebar --}}
    <div class="space-y-6">
        {{-- Хариуцагч --}}
        @if($order->assignedUser)
        <div class="bg-white rounded-2xl border border-gray-100 p-6">
            <h3 class="font-bold mb-3">Хариуцагч</h3>
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-full bg-nsma-red/10 flex items-center justify-center text-nsma-red font-bold">{{ substr($order->assignedUser->name, 0, 1) }}</div>
                <div>
                    <div class="font-semibold text-sm">{{ $order->assignedUser->name }}</div>
                    <div class="text-xs text-gray-500">NSMA баг</div>
                </div>
            </div>
        </div>
        @endif

        {{-- Статус түүх --}}
        <div class="bg-white rounded-2xl border border-gray-100 p-6">
            <h3 class="font-bold mb-3">Явц</h3>
            <div class="space-y-3 text-sm">
                @foreach($order->statusHistory as $h)
                    <div class="flex items-start gap-3 pb-3 border-b border-gray-100 last:border-0">
                        <span class="w-2 h-2 rounded-full bg-nsma-red mt-1.5 flex-shrink-0"></span>
                        <div class="flex-1 min-w-0">
                            <div class="font-medium">{{ ucfirst($h->to_status) }}</div>
                            @if($h->comment)<div class="text-xs text-gray-600 mt-0.5">{{ $h->comment }}</div>@endif
                            <div class="text-xs text-gray-400 mt-1">{{ $h->created_at->diffForHumans() }}</div>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>

        {{-- Цуцлах --}}
        @if(in_array($order->status, ['submitted', 'reviewing']))
        <form action="{{ route('client.orders.cancel', $order) }}" method="POST" onsubmit="return confirm('Захиалгаа цуцлах уу?')">
            @csrf
            <button class="w-full bg-red-50 text-red-700 font-semibold py-2 rounded-lg hover:bg-red-100">Захиалга цуцлах</button>
        </form>
        @endif
    </div>
</div>

@push('scripts')
<script>
    document.getElementById('message-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const form = e.target;
        const r = await window.ajaxJson('{{ route('client.orders.messages', $order) }}', {
            method: 'POST',
            body: new FormData(form),
        });
        if (r.ok) {
            form.reset();
            window.showToast('Зурвас илгээгдлээ.');
            setTimeout(() => location.reload(), 600);
        } else {
            window.showToast(r.data.message || 'Алдаа гарлаа.', 'error');
        }
    });
</script>
@endpush

@endsection
