@extends('layouts.admin')

@section('title', $application->full_name . ' — Başvuru')
@section('page-title', $application->full_name)
@section('page-subtitle', $application->jobPosting->title ?? '')

@section('content')

<div class="mt-2 space-y-5">

    {{-- Üst Bar --}}
    <div class="flex flex-wrap items-center gap-3">
        <a href="{{ route('admin.basvurular.index') }}" class="text-sm text-gray-500 hover:text-gray-700">
            ← Başvurulara Dön
        </a>
        <div class="flex-1"></div>
        @can('view interviews')
        <a href="{{ route('admin.gorusmeler.create', ['application_id' => $application->id]) }}"
           class="bg-primary text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-orange-600 transition-colors flex items-center gap-2">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
            Görüşme Planla
        </a>
        @endcan
        @can('view applications')
        @if($application->cv_path)
        {{-- CV Tarayıcıda Görüntüle --}}
        @php
            $ext = strtolower(pathinfo($application->cv_original_name, PATHINFO_EXTENSION));
            $canInline = in_array($ext, ['pdf', 'jpg', 'jpeg', 'png', 'gif', 'webp']);
        @endphp
        @if($canInline)
        <a href="{{ route('admin.basvurular.cv.view', $application) }}" target="_blank"
           class="bg-white border border-gray-300 text-gray-700 px-4 py-2 rounded-lg text-sm hover:bg-gray-50 transition-colors flex items-center gap-2">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
            CV Görüntüle
        </a>
        @endif
        <a href="{{ route('admin.basvurular.cv', $application) }}"
           class="bg-white border border-gray-300 text-gray-700 px-4 py-2 rounded-lg text-sm hover:bg-gray-50 transition-colors flex items-center gap-2">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
            CV İndir
        </a>
        @else
        <span class="bg-gray-100 text-gray-400 px-4 py-2 rounded-lg text-sm flex items-center gap-2 cursor-not-allowed" title="CV KVKK kapsamında silindi">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"/></svg>
            CV Silindi
        </span>
        @endif
        @endcan
    </div>

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

        {{-- Sol: Başvuru Bilgileri --}}
        <div class="lg:col-span-2 space-y-5">

            {{-- Kişisel Bilgiler --}}
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
                <h2 class="font-bold text-gray-800 mb-4 border-b border-gray-100 pb-3">Başvuran Bilgileri</h2>
                <div class="grid grid-cols-2 gap-4 text-sm">
                    <div>
                        <p class="text-gray-500 text-xs mb-0.5">Ad Soyad</p>
                        <p class="font-medium text-gray-800">{{ $application->full_name }}</p>
                    </div>
                    <div>
                        <p class="text-gray-500 text-xs mb-0.5">E-posta</p>
                        <a href="mailto:{{ $application->email }}" class="font-medium text-primary hover:underline">{{ $application->email }}</a>
                    </div>
                    <div>
                        <p class="text-gray-500 text-xs mb-0.5">Telefon</p>
                        <div class="flex items-center gap-2">
                            <a href="tel:{{ $application->phone }}" class="font-medium text-gray-800">{{ $application->phone }}</a>
                            {{-- WhatsApp Butonu --}}
                            @php
                                // Sadece rakamları al
                                $waPhone = preg_replace('/[^0-9]/', '', $application->phone ?? '');
                                // Başındaki sıfırları temizle (0090, 00090 gibi uluslararası prefix)
                                $waPhone = ltrim($waPhone, '0');
                                // Türkiye kodu yoksa ekle
                                if (!str_starts_with($waPhone, '90')) {
                                    $waPhone = '90' . $waPhone;
                                }
                                $waMessage = urlencode('Merhaba ' . $application->full_name . ', Markamama kariyer başvurunuzla ilgili görüşmek istiyoruz.');
                            @endphp
                            <a href="https://wa.me/{{ $waPhone }}?text={{ $waMessage }}" target="_blank"
                               class="inline-flex items-center gap-1 bg-green-500 text-white px-2.5 py-1 rounded-lg text-xs font-medium hover:bg-green-600 transition-colors">
                                <svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
                                WhatsApp
                            </a>
                        </div>
                    </div>
                    @if($application->linkedin_url)
                    <div>
                        <p class="text-gray-500 text-xs mb-0.5">LinkedIn</p>
                        @php
                            $liUrl = $application->linkedin_url;
                            $liSafe = (str_starts_with($liUrl, 'http://') || str_starts_with($liUrl, 'https://')) ? $liUrl : null;
                        @endphp
                        @if($liSafe)
                        <a href="{{ $liSafe }}" target="_blank" rel="noopener noreferrer" class="font-medium text-primary hover:underline truncate block">
                            Profili Gör ↗
                        </a>
                        @else
                        <span class="font-medium text-gray-400 text-xs">Geçersiz URL</span>
                        @endif
                    </div>
                    @endif
                    @if($application->source)
                    <div>
                        <p class="text-gray-500 text-xs mb-0.5">Kaynak</p>
                        <p class="font-medium text-gray-800">{{ $application->source }}</p>
                    </div>
                    @endif
                    <div>
                        <p class="text-gray-500 text-xs mb-0.5">Başvuru Tarihi</p>
                        <p class="font-medium text-gray-800">{{ $application->created_at->format('d.m.Y H:i') }}</p>
                    </div>
                    <div>
                        <p class="text-gray-500 text-xs mb-0.5">KVKK Onayı</p>
                        <p class="font-medium text-green-600">✓ {{ $application->kvkk_consent_at?->format('d.m.Y H:i') }}</p>
                        @if($application->kvkk_consent_ip)
                        <p class="text-xs text-gray-400 mt-0.5">IP: {{ $application->kvkk_consent_ip }}</p>
                        @endif
                    </div>
                    <div>
                        <p class="text-gray-500 text-xs mb-0.5">CV Dosyası</p>
                        <p class="font-medium text-gray-800 text-xs">{{ $application->cv_original_name }}</p>
                    </div>
                    {{-- CV Tarama Durumu --}}
                    <div>
                        <p class="text-gray-500 text-xs mb-0.5">CV Tarama</p>
                        @php
                            $scanColors = [
                                'pending'  => 'yellow',
                                'clean'    => 'green',
                                'infected' => 'red',
                                'failed'   => 'orange',
                                'skipped'  => 'gray',
                            ];
                            $scanLabels = [
                                'pending'  => '⏳ Taranıyor...',
                                'clean'    => '✓ Temiz',
                                'infected' => '⚠ Virüs Tespit Edildi',
                                'failed'   => '✗ Tarama Başarısız',
                                'skipped'  => '— Taranmadı',
                            ];
                            $sc = $application->cv_scan_status ?? 'pending';
                            $scColor = $scanColors[$sc] ?? 'gray';
                            $scLabel = $scanLabels[$sc] ?? $sc;
                        @endphp
                        <div class="flex items-center gap-2 flex-wrap">
                            <span id="cv-scan-badge"
                                  class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-{{ $scColor }}-100 text-{{ $scColor }}-700"
                                  data-status="{{ $sc }}">
                                {{ $scLabel }}
                            </span>
                            @if($application->cv_scanned_at)
                            <span id="cv-scan-time" class="text-xs text-gray-400">{{ $application->cv_scanned_at->format('d.m.Y H:i') }}</span>
                            @else
                            <span id="cv-scan-time" class="text-xs text-gray-400"></span>
                            @endif
                        </div>
                        {{-- Tekrar Analiz Yaptır --}}
                        @can('view applications')
                        <form method="POST" action="{{ route('admin.basvurular.rescan', $application) }}" class="mt-2">
                            @csrf
                            <button type="submit"
                                    class="text-xs text-primary hover:text-orange-600 underline flex items-center gap-1 transition-colors">
                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
                                </svg>
                                Tekrar Analiz Yaptır
                            </button>
                        </form>
                        @endcan
                    </div>
                </div>
            </div>

            {{-- Ön Yazı --}}
            @if($application->cover_letter)
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
                <h2 class="font-bold text-gray-800 mb-3">Ön Yazı</h2>
                <div class="text-sm text-gray-700 leading-relaxed whitespace-pre-line bg-gray-50 rounded-lg p-4">
                    {{ $application->cover_letter }}
                </div>
            </div>
            @endif

            {{-- Aktivite Logları --}}
            @if($activities->isNotEmpty())
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
                <h2 class="font-bold text-gray-800 mb-4">Aktivite Geçmişi</h2>
                <div class="space-y-3">
                    @foreach($activities as $activity)
                    <div class="flex items-start gap-3 text-sm">
                        <div class="w-2 h-2 bg-primary rounded-full mt-1.5 flex-shrink-0"></div>
                        <div class="flex-1">
                            <p class="text-gray-700">
                                <span class="font-medium">{{ $activity->causer?->name ?? 'Sistem' }}</span>
                                — {{ $activity->description }}
                            </p>
                            <p class="text-xs text-gray-400">{{ $activity->created_at->format('d.m.Y H:i') }}</p>
                        </div>
                    </div>
                    @endforeach
                </div>
            </div>
            @endif
        </div>

        {{-- Sağ: Durum & Notlar --}}
        <div class="space-y-5">

            {{-- Durum Güncelle --}}
            @can('edit application status')
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
                <h3 class="font-semibold text-gray-800 mb-3">Başvuru Durumu</h3>
                @php
                    $colors = ['yeni' => 'blue', 'incelendi' => 'yellow', 'görüşmeye_çağrıldı' => 'purple', 'reddedildi' => 'red', 'işe_alındı' => 'green'];
                    $color = $colors[$application->status] ?? 'gray';
                @endphp
                <div class="mb-3">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-{{ $color }}-100 text-{{ $color }}-700">
                        {{ $application->status_label }}
                    </span>
                </div>
                <form method="POST" action="{{ route('admin.basvurular.status', $application) }}">
                    @csrf
                    @method('PATCH')
                    <select name="status" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400 mb-2">
                        <option value="yeni" {{ $application->status == 'yeni' ? 'selected' : '' }}>Yeni</option>
                        <option value="incelendi" {{ $application->status == 'incelendi' ? 'selected' : '' }}>İncelendi</option>
                        <option value="görüşmeye_çağrıldı" {{ $application->status == 'görüşmeye_çağrıldı' ? 'selected' : '' }}>Görüşmeye Çağrıldı</option>
                        <option value="reddedildi" {{ $application->status == 'reddedildi' ? 'selected' : '' }}>Reddedildi</option>
                        <option value="işe_alındı" {{ $application->status == 'işe_alındı' ? 'selected' : '' }}>İşe Alındı</option>
                    </select>
                    <button type="submit" class="w-full bg-primary text-white py-2 rounded-lg text-sm font-medium hover:bg-orange-600 transition-colors">
                        Durumu Güncelle
                    </button>
                </form>
                @if($application->reviewer)
                <p class="text-xs text-gray-400 mt-2">Son inceleyen: {{ $application->reviewer->name }}</p>
                @endif
            </div>
            @endcan

            {{-- İç Notlar --}}
            @can('add application notes')
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
                <h3 class="font-semibold text-gray-800 mb-3">İç Notlar</h3>
                <form method="POST" action="{{ route('admin.basvurular.notes', $application) }}">
                    @csrf
                    @method('PATCH')
                    <textarea name="internal_notes" rows="5"
                              class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400 mb-2"
                              placeholder="Adayla ilgili notlarınız...">{{ $application->internal_notes }}</textarea>
                    <button type="submit" class="w-full bg-gray-700 text-white py-2 rounded-lg text-sm font-medium hover:bg-gray-800 transition-colors">
                        Notu Kaydet
                    </button>
                </form>
            </div>
            @endcan

            {{-- İlan Bilgisi --}}
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
                <h3 class="font-semibold text-gray-800 mb-3">Başvurulan Pozisyon</h3>
                @if($application->jobPosting)
                <p class="font-medium text-gray-800 text-sm">{{ $application->jobPosting->title }}</p>
                <p class="text-xs text-gray-500 mt-1">{{ $application->jobPosting->department }} · {{ $application->jobPosting->location }}</p>
                <a href="{{ route('admin.ilanlar.show', $application->jobPosting) }}"
                   class="mt-3 block text-center text-xs text-primary hover:underline">
                    İlanı Gör →
                </a>
                @endif
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script nonce="{{ app('csp-nonce') }}">
(function () {
    const badge = document.getElementById('cv-scan-badge');
    const timeEl = document.getElementById('cv-scan-time');
    if (!badge) return;

    const initialStatus = badge.dataset.status;
    if (initialStatus !== 'pending') return; // Zaten sonuçlanmış, polling gerekmez

    const statusUrl = '{{ route('admin.basvurular.cv-scan-status', $application) }}';

    const colorMap = {
        pending:  { bg: 'bg-yellow-100', text: 'text-yellow-700' },
        clean:    { bg: 'bg-green-100',  text: 'text-green-700'  },
        infected: { bg: 'bg-red-100',    text: 'text-red-700'    },
        failed:   { bg: 'bg-orange-100', text: 'text-orange-700' },
        skipped:  { bg: 'bg-gray-100',   text: 'text-gray-700'   },
    };

    const labelMap = {
        pending:  '⏳ Taranıyor...',
        clean:    '✓ Temiz',
        infected: '⚠ Virüs Tespit Edildi',
        failed:   '✗ Tarama Başarısız',
        skipped:  '— Taranmadı',
    };

    let intervalId = null;

    function updateBadge(data) {
        const colors = colorMap[data.status] || colorMap.skipped;
        const label  = labelMap[data.status] || data.status;

        // Renk sınıflarını temizle ve yenisini ekle
        badge.className = 'inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ' + colors.bg + ' ' + colors.text;
        badge.textContent = label;
        badge.dataset.status = data.status;

        if (data.scanned_at && timeEl) {
            timeEl.textContent = data.scanned_at;
        }
    }

    function poll() {
        fetch(statusUrl, {
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }
        })
        .then(r => r.json())
        .then(data => {
            updateBadge(data);
            if (data.is_final) {
                clearInterval(intervalId);
            }
        })
        .catch(() => { /* sessizce devam et */ });
    }

    // 5 saniyede bir kontrol et
    intervalId = setInterval(poll, 5000);
})();
</script>
@endpush

@endsection
