@extends('layout')

@section('title', __('store.ticket_details') . ' - #' . $ticket->id)

@section('content')
<div class="container py-5">
    <div class="row">
        <div class="col-md-12">
            @php
                $statusColor = 'secondary';
                if ($ticket->status && $ticket->status->is_closed) {
                    $statusColor = 'success';
                } elseif ($ticket->status && $ticket->status->slug === 'open') {
                    $statusColor = 'primary';
                } elseif ($ticket->status && $ticket->status->slug === 'answered') {
                    $statusColor = 'info';
                } elseif ($ticket->status && $ticket->status->slug === 'pending') {
                    $statusColor = 'warning';
                }
            @endphp
            <x-clientarea.page-header
                icon="fas fa-headset"
                :title="'#' . $ticket->id . ' — ' . $ticket->title"
                :subtitle="$ticket->department->name ?? ''"
            >
                <span class="badge bg-{{ $statusColor }} fs-6 align-self-center">
                    {{ $ticket->status->name ?? __('store.ticket_status_unknown') }}
                </span>
                <a href="{{ route('store.auth.tickets') }}" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-2"></i>{{ __('store.back_to_tickets') }}
                </a>
            </x-clientarea.page-header>

            @include('partials.support-banners', ['banners' => $supportBanners ?? []])

            
            @if($ticket->status && $ticket->status->is_closed && $hasAdminReply && !$ticket->rating)
                <div class="alert alert-warning border-0 shadow-sm mb-4 d-flex align-items-center">
                    <i class="fas fa-star fa-lg text-warning me-3"></i>
                    <div class="flex-grow-1">
                        <strong>{{ __('store.ticket_rating_banner_prompt') }}</strong>
                    </div>
                    <a href="#ticketRatingSection" class="btn btn-sm btn-warning ms-3">
                        <i class="fas fa-star me-1"></i>{{ __('store.ticket_rating_submit') }}
                    </a>
                </div>
            @endif

            <!-- Ticket Info Card -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header">
                    <h5 class="mb-0">{{ __('store.ticket_information') }}</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-borderless table-sm">
                                <tr>
                                    <td><strong>{{ __('store.ticket_title') }}:</strong></td>
                                    <td>{{ $ticket->title }}</td>
                                </tr>
                                <tr>
                                    <td><strong>{{ __('store.ticket_department') }}:</strong></td>
                                    <td>
                                        <span class="badge bg-info">
                                            {{ $ticket->department->name ?? __('store.ticket_general') }}
                                        </span>
                                    </td>
                                </tr>
                                <tr>
                                    <td><strong>{{ __('store.ticket_priority_text') }}:</strong></td>
                                    <td>
                                        <span class="badge bg-{{ $ticket->priority_badge_color }}">
                                            {{ $ticket->priority_label }}
                                        </span>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-borderless table-sm">
                                <tr>
                                    <td><strong>{{ __('store.ticket_created_date') }}:</strong></td>
                                    <td>{{ $ticket->created_at->format($dateTimeFormat) }}</td>
                                </tr>
                                <tr>
                                    <td><strong>{{ __('store.ticket_last_reply') }}:</strong></td>
                                    <td>
                                        @if($ticket->replies->count() > 0)
                                            {{ $ticket->replies->last()->created_at->format($dateTimeFormat) }}
                                        @else
                                            {{ __('store.ticket_no_replies') }}
                                        @endif
                                    </td>
                                </tr>
                                <tr>
                                    <td><strong>{{ __('store.ticket_total_replies') }}:</strong></td>
                                    <td>{{ $ticket->replies->count() }}</td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Replies -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header">
                    <h5 class="mb-0">{{ __('store.ticket_conversation') }}</h5>
                </div>
                <div class="card-body p-0">
                    @foreach($ticket->replies->sortBy('created_at') as $reply)
                        <div class="border-bottom p-4 {{ $reply->isFromAdmin() ? '' : '' }}">
                            <div class="d-flex justify-content-between align-items-start mb-3">
                                <div class="d-flex align-items-center">
                                    <div class="me-3">
                                        @if($reply->isFromAdmin())
                                            <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                <i class="fas fa-user-tie"></i>
                                            </div>
                                        @else
                                            <div class="bg-secondary text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                <i class="fas fa-user"></i>
                                            </div>
                                        @endif
                                    </div>
                                    <div>
                                        <h6 class="mb-1">
                                            @if($reply->isFromAdmin())
                                                {{ $reply->admin ? $reply->admin->name : __('store.ticket_admin') }}
                                                <span class="badge bg-primary ms-2">{{ __('store.ticket_support_team') }}</span>
                                            @else
                                                @php
                                                    $replyClient = $reply->client;
                                                    $mainClient = $ticket->client;
                                                @endphp
                                                @if($replyClient && $replyClient->id === $mainClient->id)
                                                    {{ trim($replyClient->first_name . ' ' . $replyClient->last_name) }}
                                                    <span class="badge bg-success ms-2">{{ __('store.ticket_account_owner') }}</span>
                                                @elseif($replyClient)
                                                    {{ trim($replyClient->first_name . ' ' . $replyClient->last_name) }}
                                                    <span class="badge bg-info ms-2">{{ __('store.ticket_authorized_user') }}</span>
                                                @else
                                                    {{ __('store.ticket_client') }}
                                                @endif
                                            @endif
                                        </h6>
                                        <small class="text-muted">{{ $reply->created_at->format($dateTimeFormat) }}</small>
                                    </div>
                                </div>
                            </div>
                            <div class="message-content ticket-rendered-content">
                                {!! app(\App\Services\Ticket\TicketContentFormatter::class)->render($reply->message, $reply->content_format ?? 'plain') !!}
                            </div>

                            
                            @if($reply->attachments && $reply->attachments->count() > 0)
                                <div class="attachments mt-3">
                                    <h6 class="text-muted mb-2">
                                        <i class="fas fa-paperclip me-1"></i>{{ __('store.ticket_attachments') }}
                                    </h6>
                                    <div class="attachment-list">
                                        @foreach($reply->attachments as $attachment)
                                            <div class="attachment-item d-flex align-items-center mb-2 p-2 border rounded ">
                                                <div class="attachment-icon me-2">
                                                    @php
                                                        $iconClass = 'fas fa-file';
                                                        if (str_contains($attachment->mime_type, 'image/')) {
                                                            $iconClass = 'fas fa-file-image text-success';
                                                        } elseif (str_contains($attachment->mime_type, 'pdf')) {
                                                            $iconClass = 'fas fa-file-pdf text-danger';
                                                        } elseif (str_contains($attachment->mime_type, 'word') || str_contains($attachment->mime_type, 'document')) {
                                                            $iconClass = 'fas fa-file-word text-primary';
                                                        } elseif (str_contains($attachment->mime_type, 'excel') || str_contains($attachment->mime_type, 'spreadsheet')) {
                                                            $iconClass = 'fas fa-file-excel text-success';
                                                        } elseif (str_contains($attachment->mime_type, 'zip') || str_contains($attachment->mime_type, 'archive')) {
                                                            $iconClass = 'fas fa-file-archive text-warning';
                                                        }
                                                    @endphp
                                                    <i class="{{ $iconClass }}"></i>
                                                </div>
                                                <div class="attachment-info flex-grow-1">
                                                    <div class="attachment-name fw-semibold">{{ $attachment->original_name }}</div>
                                                    <small class="text-muted">
                                                        {{ number_format($attachment->file_size / 1024, 1) }} KB
                                                        • {{ $attachment->created_at->format($dateTimeFormat) }}
                                                    </small>
                                                </div>
                                                <div class="attachment-actions">
                                                    <a href="{{ route('store.auth.tickets.attachment.download', [$ticket->id, $attachment->id]) }}"
                                                       class="btn btn-sm btn-outline-primary">
                                                        <i class="fas fa-download me-1"></i>{{ __('store.ticket_download') }}
                                                    </a>
                                                </div>
                                            </div>
                                        @endforeach
                                    </div>
                                </div>
                            @endif
                        </div>
                    @endforeach

                    @if($ticket->replies->count() === 0)
                        <div class="text-center py-5 text-muted">
                            <i class="fas fa-comments fa-3x mb-3"></i>
                            <p>{{ __('store.ticket_no_replies_yet') }}</p>
                        </div>
                    @endif
                </div>
            </div>

            <!-- Reply Form -->
            @if($canReplyTickets && $ticket->status && !$ticket->status->is_closed)
                <div class="card border-0 shadow-sm">
                    <div class="card-header">
                        <h5 class="mb-0">{{ __('store.ticket_add_reply') }}</h5>
                    </div>
                    <div class="card-body">
                        <form action="{{ route('store.auth.tickets.reply.store', $ticket->id) }}" method="POST" enctype="multipart/form-data" id="ticketReplyForm">
                            @csrf
                            <div class="mb-3">
                                <label for="message" class="form-label">{{ __('store.ticket_your_message') }} <span class="text-danger">*</span></label>
                                <textarea name="message" id="message" class="form-control @error('message') is-invalid @enderror" rows="6" placeholder="{{ __('store.ticket_message_placeholder') }}" required>{{ old('message') }}</textarea>
                                @error('message')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                                <div class="form-text">
                                    {{ __('store.ticket_message_help') }}
                                </div>
                            </div>

                            <div class="mb-3">
                                <label for="attachments" class="form-label">{{ __('store.ticket_attachments') }}</label>
                                <input type="file" name="attachments[]" id="attachments" class="form-control @error('attachments.*') is-invalid @enderror" multiple accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.txt,.zip,.rar">
                                @error('attachments.*')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                                <div class="form-text">
                                    {{ __('store.ticket_attachment_help') }}
                                </div>
                                <div id="attachmentPreview" class="mt-2"></div>
                            </div>

                            <div class="d-flex justify-content-between align-items-center">
                                <a href="{{ route('store.auth.tickets') }}" class="btn btn-outline-secondary">
                                    <i class="fas fa-arrow-left me-2"></i>{{ __('store.back_to_tickets') }}
                                </a>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-paper-plane me-2"></i>{{ __('store.ticket_send_reply') }}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            @elseif(!$canReplyTickets && $ticket->status && !$ticket->status->is_closed)
                <div class="card border-0 shadow-sm">
                    <div class="card-body text-center py-4">
                        <i class="fas fa-lock fa-2x text-muted mb-3"></i>
                        <h5>{{ __('store.no_permission') }}</h5>
                        <p class="text-muted">{{ __('store.ticket_reply_no_permission') }}</p>
                        <a href="{{ route('store.auth.tickets') }}" class="btn btn-outline-secondary mt-2">
                            <i class="fas fa-arrow-left me-2"></i>{{ __('store.back_to_tickets') }}
                        </a>
                    </div>
                </div>
            @else
                <div class="card border-0 shadow-sm">
                    <div class="card-body text-center py-4">
                        <i class="fas fa-lock fa-2x text-muted mb-3"></i>
                        <h5 class="text-muted">{{ __('store.ticket_closed_ticket') }}</h5>
                        <p class="text-muted">{{ __('store.ticket_closed_ticket_description') }}</p>
                        <a href="{{ route('store.auth.tickets') }}" class="btn btn-outline-primary">
                            <i class="fas fa-arrow-left me-2"></i>{{ __('store.back_to_tickets') }}
                        </a>
                    </div>
                </div>
            @endif

            <!-- Ticket Rating Section -->
            @if($ticket->status && $ticket->status->is_closed && $hasAdminReply)
                <div class="card border-0 shadow-sm mt-4" id="ticketRatingSection">
                    <div class="card-header border-0">
                        <h5 class="mb-0"><i class="fas fa-star text-warning me-2"></i>{{ __('store.ticket_rating_title') }}</h5>
                    </div>
                    <div class="card-body">
                        @if($ticket->rating)
                            
                            <div class="text-center py-3">
                                <p class="text-muted mb-2">{{ __('store.ticket_rating_your_rating') }}</p>
                                <div class="mb-2">
                                    @for($i = 1; $i <= 5; $i++)
                                        <i class="fas fa-star {{ $i <= $ticket->rating->rating ? 'text-warning' : 'text-muted' }}" style="font-size: 1.5rem;"></i>
                                    @endfor
                                    <span class="ms-2 fw-semibold">({{ $ticket->rating->rating }}/5)</span>
                                </div>
                                @if($ticket->rating->comment)
                                    <p class="mb-1"><strong>{{ __('store.ticket_rating_your_comment') }}:</strong></p>
                                    <p class="text-muted fst-italic mb-0">"{{ $ticket->rating->comment }}"</p>
                                @endif
                                <p class="text-success mt-2 mb-0"><i class="fas fa-check-circle me-1"></i>{{ __('store.ticket_rating_saved_successfully') }}</p>
                            </div>
                        @else
                            
                            <div class="text-center py-2" id="ratingFormContainer">
                                <p class="text-muted mb-3">{{ __('store.ticket_rating_description') }}</p>
                                <div class="rating-stars mb-1">
                                    @for($i = 1; $i <= 5; $i++)
                                        <i class="fas fa-star rating-star text-muted"
                                           data-rating="{{ $i }}"
                                           data-label="{{ __('store.ticket_rating_label_' . $i) }}"
                                           style="font-size: 2rem; cursor: pointer; transition: all 0.2s ease; display: inline-block;"
                                           title="{{ __('store.ticket_rating_label_' . $i) }}"></i>
                                    @endfor
                                </div>
                                <div id="ratingHoverLabel" class="text-muted mb-3" style="min-height: 1.5em; font-weight: 500;"></div>
                                <div class="mb-3 mx-auto" style="max-width: 500px;">
                                    <label for="ratingComment" class="form-label text-muted">{{ __('store.ticket_rating_comment_label') }}</label>
                                    <textarea id="ratingComment" class="form-control" rows="3" maxlength="500" placeholder="{{ __('store.ticket_rating_comment_placeholder') }}"></textarea>
                                </div>
                                <button type="button" id="submitRating" class="btn btn-warning" disabled>
                                    <i class="fas fa-paper-plane me-1"></i>{{ __('store.ticket_rating_submit') }}
                                </button>
                            </div>
                            
                            <div class="text-center py-3 d-none" id="ratingSuccessContainer">
                                <p class="text-muted mb-2">{{ __('store.ticket_rating_your_rating') }}</p>
                                <div class="mb-2" id="ratingSuccessStars"></div>
                                <p class="text-muted fst-italic mb-0 d-none" id="ratingSuccessComment"></p>
                                <p class="text-success mt-2 mb-0"><i class="fas fa-check-circle me-1"></i>{{ __('store.ticket_rating_saved_successfully') }}</p>
                            </div>
                        @endif
                    </div>
                </div>
            @endif
        </div>
    </div>
</div>
@endsection

@push('scripts')

<script>
// Settings from backend
window.ticketMaxFileSize = {{ App\Models\Setting::get('ticket_attachment_max_size', 5120) }};

// Translations for ticket reply JavaScript
window.translations = window.translations || {};
window.translations.ticket = {
    chars_remaining: '{{ __("store.ticket_chars_remaining") }}',
    selected_files: '{{ __("store.ticket_selected_files") }}',
    file_too_large: '{{ __("store.ticket_file_too_large") }}',
    max_files_error: '{{ __("store.ticket_max_files_error") }}',
    message_too_short: '{{ __("store.ticket_message_too_short") }}',
    message_too_long: '{{ __("store.ticket_message_too_long") }}',
    file_size_error: '{{ __("store.ticket_file_size_error") }}'
};

// Ticket rating configuration
window.ticketRatingConfig = {
    ticketId: {{ $ticket->id }},
    hasRating: {{ $ticket->rating ? 'true' : 'false' }},
    currentRating: {{ $ticket->rating?->rating ?? 0 }},
    currentComment: {!! json_encode($ticket->rating?->comment ?? '') !!},
    routes: {
        rate: '{{ route("store.auth.tickets.rate", $ticket) }}'
    },
    translations: {
        title: '{{ __("store.ticket_rate_ticket") }}',
        description: '{{ __("store.ticket_rating_description") }}',
        submit: '{{ __("store.ticket_rating_submit") }}',
        commentPlaceholder: '{{ __("store.ticket_rating_comment_placeholder") }}',
        success: '{{ __("store.ticket_rating_saved_successfully") }}',
        alreadyRated: '{{ __("store.ticket_rating_already_rated") }}',
        thankYou: '{{ __("store.ticket_rating_thanks") }}',
        yourRating: '{{ __("store.ticket_rating_your_rating") }}',
        poor: '{{ __("store.ticket_rating_poor") }}',
        fair: '{{ __("store.ticket_rating_fair") }}',
        good: '{{ __("store.ticket_rating_good") }}',
        veryGood: '{{ __("store.ticket_rating_very_good") }}',
        excellent: '{{ __("store.ticket_rating_excellent") }}',
        error: '{{ __("store.ticket_rating_error") }}'
    }
};
</script>
<script>
    // PRC-683 — WYSIWYG (Quill) yanıt editörü (starter theme).
    window.storeTicketEditor = {
        editors: [{ textarea: 'message', form: 'ticketReplyForm' }],
        placeholder: '{{ __('store.ticket_message_placeholder') }}'
    };
</script>
@vite(['resources/js/store/ticket-reply.js'])
@vite('resources/js/store/ticket-rating.js')
@vite('resources/js/store/tickets/reply-editor.js')
@endpush
