@extends('agency.layouts.app')

@section('title', 'Site Talepleri')
@section('page_title', 'Web Sitesi Talepleri')

@push('styles')
<link rel="stylesheet" href="{{ asset('assets/agency/css/site-studio.css') }}?v={{ filemtime(public_path('assets/agency/css/site-studio.css')) }}">
@endpush

@php
    $labels = [
        'name' => 'Ad Soyad', 'phone' => 'Telefon', 'email' => 'E-posta', 'subject' => 'Konu',
        'message' => 'Mesaj', 'note' => 'Not', 'tour_name' => 'Tur', 'tour_url' => 'Tur Linki',
        'date_label' => 'Tarih', 'adult_count' => 'Yetişkin', 'child_count' => 'Çocuk',
        'infant_count' => 'Bebek', 'room_type' => 'Oda Tipi', 'people' => 'Kişi',
    ];
    $formIcons = [
        'contact' => 'fa-envelope-open-text',
        'callback' => 'fa-phone-volume',
        'reservation' => 'fa-calendar-check',
        'chat_offline' => 'fa-comment-slash',
    ];
    $activeFilter = request('status') === 'new' ? 'new' : (request('form_key') ?: 'all');
@endphp

@section('content')
<x-site-studio active="submissions">
    <div class="sx-card">
        <div class="sx-card__top">
            <span class="sx-card__t"><i class="fas fa-inbox"></i> Gelen Talepler</span>
            <span class="sx-card__hint">{{ $submissions->total() }} kayıt</span>
        </div>

        <div class="sx-card__body" style="padding-bottom:.55rem">
            <div class="sx-seg">
                <a href="{{ route('agency.site.submissions.index') }}" class="{{ $activeFilter === 'all' ? 'on' : '' }}">Tümü</a>
                <a href="{{ route('agency.site.submissions.index', ['status' => 'new']) }}" class="{{ $activeFilter === 'new' ? 'on' : '' }}">
                    <i class="fas fa-circle" style="font-size:.4rem;color:var(--sx-acc)"></i> Yeni
                </a>
                @foreach($formKeys as $key => $label)
                    <a href="{{ route('agency.site.submissions.index', ['form_key' => $key]) }}"
                       class="{{ $activeFilter === $key ? 'on' : '' }}">{{ $label }}</a>
                @endforeach
            </div>
        </div>

        @if($submissions->isEmpty())
            <div class="sx-empty">
                <span class="sx-empty__ic"><i class="fas fa-inbox"></i></span>
                <span class="sx-empty__t">Bu filtrede talep yok</span>
                <span class="sx-empty__s">
                    Sitenizdeki iletişim formu, "biz sizi arayalım" ve rezervasyon talepleri
                    buraya düşer; tek tıkla potansiyel müşteri kaydına dönüşür.
                </span>
            </div>
        @else
            <div class="sx-list">
                @foreach($submissions as $submission)
                    @php
                        $payload = $submission->payload ?? [];
                        $who = trim((string) ($payload['name'] ?? '')) ?: ($payload['phone'] ?? $payload['email'] ?? 'Web ziyaretçisi');
                    @endphp
                    <div class="sx-sub {{ $submission->status === 'new' ? 'new' : '' }}" id="sub-{{ $submission->id }}">
                        <div class="sx-sub__h">
                            <span class="sx-li__ic"><i class="fas {{ $formIcons[$submission->form_key] ?? 'fa-file-lines' }}"></i></span>
                            <span class="sx-sub__who">{{ $who }}</span>
                            <span class="sx-tag sx-tag--acc">{{ $submission->form_label }}</span>
                            @if($submission->status === 'new')
                                <span class="sx-tag sx-tag--hot">Yeni</span>
                            @elseif($submission->status === 'converted')
                                <span class="sx-tag sx-tag--ok">Müşteri</span>
                            @endif
                            <span class="sx-sub__time">
                                {{ $submission->created_at->format('d.m.Y H:i') }}
                                @if($submission->visitor_ip) · {{ $submission->visitor_ip }} @endif
                            </span>

                            <span class="sx-sub__a">
                                @if($submission->status === 'new')
                                    <button type="button" class="sx-chip" data-act="read" data-id="{{ $submission->id }}">
                                        <i class="fas fa-check"></i> Okundu
                                    </button>
                                @endif
                                @if($submission->customer_id)
                                    <button type="button" class="sx-chip" onclick="openCustomerDrawer({{ $submission->customer_id }})">
                                        <i class="fas fa-address-card"></i> Müşteri kartı
                                    </button>
                                @else
                                    <button type="button" class="sx-chip" data-act="convert" data-id="{{ $submission->id }}">
                                        <i class="fas fa-user-plus"></i> Müşteriye dönüştür
                                    </button>
                                @endif
                            </span>
                        </div>

                        <dl class="sx-kv">
                            @foreach($payload as $field => $value)
                                @continue($value === null || $value === '' || $field === 'name')
                                <div>
                                    <dt>{{ $labels[$field] ?? Str::headline($field) }}</dt>
                                    <dd class="{{ in_array($field, ['message', 'note'], true) ? 'long' : '' }}">
                                        @if($field === 'tour_url')
                                            <a href="{{ $value }}" target="_blank" rel="noopener">
                                                Turu aç <i class="fas fa-arrow-up-right-from-square" style="font-size:.6rem"></i>
                                            </a>
                                        @elseif($field === 'phone')
                                            <a href="tel:{{ $value }}">{{ $value }}</a>
                                        @elseif($field === 'email')
                                            <a href="mailto:{{ $value }}">{{ $value }}</a>
                                        @else
                                            {{ is_array($value) ? implode(', ', $value) : $value }}
                                        @endif
                                    </dd>
                                </div>
                            @endforeach
                        </dl>
                    </div>
                @endforeach
            </div>

            @if($submissions->hasPages())
                <div class="sx-card__foot">
                    {{ $submissions->onEachSide(1)->links() }}
                </div>
            @endif
        @endif
    </div>
</x-site-studio>
@endsection

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

    document.addEventListener('click', async (event) => {
        const button = event.target.closest('[data-act]');
        if (!button || !button.dataset.id) return;

        const action = button.dataset.act;
        if (action === 'convert') {
            const ok = await appConfirm({
                title: 'Müşteri kaydı oluşturulsun mu?',
                text: 'Formdaki ad, telefon ve e-posta ile potansiyel müşteri kaydı açılır.',
                confirmButtonText: 'Oluştur',
            });
            if (!ok) return;
        }

        button.disabled = true;
        try {
            const data = await sxApi('POST', '{{ url('agency/site/submissions') }}/' + button.dataset.id + '/' + action);
            appToast({ icon: 'success', title: data.message || 'İşlem tamamlandı.' });
            setTimeout(() => window.location.reload(), 600);
        } catch (error) {
            button.disabled = false;
            appToast({ icon: 'error', title: error.message });
        }
    });
})();
</script>
@endpush
