@extends('layouts.admin')

@section('title', 'Yeni Görüşme Planla')
@section('page-title', 'Yeni Görüşme Planla')

@section('content')
<div class="mt-4">

    {{-- Üst Bar --}}
    <div class="mb-4">
        <a href="{{ route('admin.gorusmeler.index') }}"
           class="inline-flex items-center gap-1.5 text-sm text-gray-500 hover:text-primary transition-colors">
            <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 19l-7-7 7-7"/></svg>
            Görüşmelere Dön
        </a>
    </div>

    <div class="flex gap-4 items-start">

        {{-- Sol: Form --}}
        <div class="flex-1 min-w-0">
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">

                @if($application)
                <div class="bg-orange-50 border border-orange-200 rounded-lg p-4 mb-5">
                    <p class="text-sm font-medium text-orange-800">Başvuran: {{ $application->full_name }}</p>
                    <p class="text-xs text-orange-600 mt-0.5">{{ $application->jobPosting->title ?? 'Genel Başvuru' }} — {{ $application->email }}</p>
                </div>
                @endif

                <form method="POST" action="{{ route('admin.gorusmeler.store') }}">
                    @csrf

                    @if($application)
                    <input type="hidden" name="job_application_id" value="{{ $application->id }}">
                    @else
                    <div class="mb-5">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Başvuru <span class="text-xs text-gray-400 font-normal">(opsiyonel)</span></label>

                        {{-- Seçili başvuru gösterimi --}}
                        <div id="selected_application_display" class="hidden mb-2 bg-orange-50 border border-orange-200 rounded-lg p-3 flex items-center justify-between">
                            <div>
                                <p id="selected_app_name" class="text-sm font-medium text-orange-800"></p>
                                <p id="selected_app_detail" class="text-xs text-orange-600 mt-0.5"></p>
                            </div>
                            <button type="button" onclick="clearApplicationSelection()"
                                    class="text-orange-400 hover:text-orange-600 ml-3 flex-shrink-0">
                                <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="M6 18L18 6M6 6l12 12"/></svg>
                            </button>
                        </div>

                        <input type="hidden" name="job_application_id" id="job_application_id" value="{{ old('job_application_id') }}">

                        <button type="button" id="open_application_modal_btn"
                                onclick="openApplicationModal()"
                                class="w-full border border-dashed border-gray-300 rounded-lg px-3 py-2.5 text-sm text-gray-500 hover:border-orange-400 hover:text-orange-500 hover:bg-orange-50 transition-colors flex items-center gap-2 @error('job_application_id') border-red-400 @enderror">
                            <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="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
                            Başvuru Seç...
                        </button>
                        @error('job_application_id')<p class="text-xs text-red-500 mt-1">{{ $message }}</p>@enderror
                    </div>

                    {{-- Manuel kişi bilgisi — başvuru seçilmediğinde görünür --}}
                    <div id="manual_candidate_fields" class="mb-5 p-4 bg-gray-50 border border-gray-200 rounded-lg">
                        <p class="text-xs font-medium text-gray-500 mb-3 flex items-center gap-1.5">
                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>
                            Görüşülecek Kişi <span class="text-gray-400 font-normal">(başvuru seçilmezse doldurabilirsiniz)</span>
                        </p>
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <label class="block text-xs font-medium text-gray-600 mb-1">Ad Soyad</label>
                                <input type="text" name="candidate_name" id="candidate_name"
                                       value="{{ old('candidate_name') }}"
                                       placeholder="Örn: Ahmet Yılmaz"
                                       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">
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-gray-600 mb-1">E-posta</label>
                                <input type="email" name="candidate_email" id="candidate_email"
                                       value="{{ old('candidate_email') }}"
                                       placeholder="ornek@email.com"
                                       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">
                            </div>
                        </div>
                    </div>
                    @endif

                    <div class="space-y-5">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Görüşme Başlığı <span class="text-red-500">*</span></label>
                            <input type="text" name="title" id="interview_title" value="{{ old('title', $application ? '1. Mülakat — ' . $application->full_name : '') }}" required
                                   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 @error('title') border-red-400 @enderror">
                            @error('title')<p class="text-xs text-red-500 mt-1">{{ $message }}</p>@enderror
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Tarih & Saat <span class="text-red-500">*</span></label>
                                <input type="datetime-local" name="scheduled_at" id="scheduledAt"
                                       value="{{ old('scheduled_at', $prefilledDate ?? '') }}" required
                                       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">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Süre (dakika)</label>
                                <select name="duration_minutes" 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">
                                    <option value="30">30 dakika</option>
                                    <option value="45">45 dakika</option>
                                    <option value="60" selected>60 dakika</option>
                                    <option value="90">90 dakika</option>
                                    <option value="120">2 saat</option>
                                </select>
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Görüşmeci</label>
                            <select name="interviewer_id" 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">
                                <option value="">Seçin (varsayılan: siz)</option>
                                @foreach($interviewers as $interviewer)
                                <option value="{{ $interviewer->id }}" {{ old('interviewer_id') == $interviewer->id ? 'selected' : '' }}>
                                    {{ $interviewer->name }}
                                </option>
                                @endforeach
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Konum</label>
                            <input type="text" name="location" value="{{ old('location') }}"
                                   placeholder="Ofis adresi veya oda adı"
                                   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">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Online Toplantı Linki</label>
                            <input type="url" name="meeting_link" value="{{ old('meeting_link') }}"
                                   placeholder="https://meet.google.com/..."
                                   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">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Notlar</label>
                            <textarea name="notes" rows="3"
                                      placeholder="Görüşme hakkında notlar..."
                                      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">{{ old('notes') }}</textarea>
                        </div>
                    </div>

                    <div class="flex items-center gap-3 mt-6 pt-5 border-t border-gray-100">
                        <button type="submit"
                                class="bg-primary text-white px-5 py-2 rounded-lg text-sm font-medium hover:bg-orange-600 transition-colors">
                            Görüşme Planla
                        </button>
                        <a href="{{ route('admin.gorusmeler.index') }}"
                           class="text-sm text-gray-500 hover:text-gray-700">İptal</a>
                    </div>
                </form>
            </div>
        </div>

        {{-- Sağ: O Günün Görüşmeleri --}}
        <div class="w-72 flex-shrink-0">
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 sticky top-4">
                <div class="px-4 py-3 border-b border-gray-100">
                    <h3 class="font-semibold text-gray-700 text-sm flex items-center gap-2">
                        <svg class="w-4 h-4 text-primary" 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>
                        O Günün Görüşmeleri
                    </h3>
                    <p id="dayPanelDate" class="text-xs text-gray-400 mt-0.5">Tarih seçin</p>
                </div>
                <div id="dayPanelContent" class="p-4">
                    <p class="text-xs text-gray-400 text-center py-4">Tarih & Saat alanından bir tarih seçin.</p>
                </div>
            </div>
        </div>

    </div>
</div>

@push('modals')
{{-- Başvuru Seçim Modalı --}}
<div id="application_modal" style="position:fixed;top:0;left:0;right:0;bottom:0;z-index:9999;display:none;">
    {{-- Backdrop --}}
    <div style="position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.45);" onclick="closeApplicationModal()"></div>

    {{-- Modal kutusu --}}
    <div style="position:absolute;top:0;left:0;right:0;bottom:0;display:flex;align-items:center;justify-content:center;padding:1rem;pointer-events:none;">
        <div style="background:#fff;border-radius:0.75rem;box-shadow:0 20px 60px rgba(0,0,0,0.25);width:100%;max-width:42rem;max-height:80vh;display:flex;flex-direction:column;pointer-events:auto;">
            {{-- Header --}}
            <div style="padding:1rem 1.25rem;border-bottom:1px solid #f3f4f6;display:flex;align-items:center;justify-content:space-between;flex-shrink:0;">
                <h3 style="font-weight:600;color:#1f2937;font-size:0.9375rem;">Başvuru Seç</h3>
                <button type="button" onclick="closeApplicationModal()" style="color:#9ca3af;background:none;border:none;cursor:pointer;padding:0.25rem;">
                    <svg style="width:1.25rem;height:1.25rem;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                </button>
            </div>

            {{-- Arama --}}
            <div style="padding:0.75rem 1.25rem;border-bottom:1px solid #f3f4f6;flex-shrink:0;">
                <div style="position:relative;">
                    <svg style="width:1rem;height:1rem;position:absolute;left:0.75rem;top:50%;transform:translateY(-50%);color:#9ca3af;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
                    <input type="text" id="application_search_input"
                           placeholder="Ad, e-posta veya pozisyon ara..."
                           style="width:100%;padding:0.5rem 0.75rem 0.5rem 2.25rem;border:1px solid #d1d5db;border-radius:0.5rem;font-size:0.875rem;outline:none;box-sizing:border-box;"
                           oninput="searchApplications(this.value)">
                </div>
            </div>

            {{-- Liste --}}
            <div id="application_list" style="flex:1;overflow-y:auto;padding:0.75rem;">
                <p style="font-size:0.75rem;color:#9ca3af;text-align:center;padding:2rem 0;">Yükleniyor...</p>
            </div>

            {{-- Footer: Başvuru olmadan devam et --}}
            <div style="padding:0.75rem 1.25rem;border-top:1px solid #f3f4f6;flex-shrink:0;display:flex;align-items:center;justify-content:space-between;">
                <p style="font-size:0.75rem;color:#9ca3af;">Başvuru bulunamadı mı?</p>
                <button type="button" onclick="skipApplicationSelection()"
                        style="font-size:0.8125rem;color:#ff7b00;background:none;border:1px solid #ff7b00;border-radius:0.5rem;padding:0.375rem 0.875rem;cursor:pointer;font-weight:500;">
                    Başvuru olmadan devam et
                </button>
            </div>
        </div>
    </div>
</div>
@endpush

<script nonce="{{ app('csp-nonce') }}">
const byDateUrl = '{{ route("admin.gorusmeler.by-date") }}';
const searchAppUrl = '{{ route("admin.gorusmeler.search-applications") }}';

// ─── Tarih paneli ────────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', function () {
    const input = document.getElementById('scheduledAt');
    if (!input) return;

    if (!input.value) {
        const params = new URLSearchParams(window.location.search);
        const dateParam = params.get('date');
        if (dateParam) input.value = dateParam;
    }

    if (input.value) fetchDayInterviews(input.value.slice(0, 10));

    input.addEventListener('change', function () {
        if (this.value) fetchDayInterviews(this.value.slice(0, 10));
    });
    input.addEventListener('input', function () {
        if (this.value) fetchDayInterviews(this.value.slice(0, 10));
    });
});

function fetchDayInterviews(dateStr) {
    const panel  = document.getElementById('dayPanelContent');
    const dateEl = document.getElementById('dayPanelDate');

    const parts  = dateStr.split('-');
    const months = ['Ocak','Şubat','Mart','Nisan','Mayıs','Haziran','Temmuz','Ağustos','Eylül','Ekim','Kasım','Aralık'];
    if (parts.length === 3) {
        dateEl.textContent = parseInt(parts[2]) + ' ' + months[parseInt(parts[1]) - 1] + ' ' + parts[0];
    }

    panel.innerHTML = '<p class="text-xs text-gray-400 text-center py-4">Yükleniyor...</p>';

    fetch(byDateUrl + '?date=' + encodeURIComponent(dateStr), {
        headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }
    })
    .then(r => r.json())
    .then(data => {
        if (!data || data.length === 0) {
            panel.innerHTML = '<p class="text-xs text-gray-400 text-center py-6">Bu günde görüşme yok.</p>';
            return;
        }
        const statusColors  = { scheduled:'bg-blue-100 text-blue-700', completed:'bg-green-100 text-green-700', rescheduled:'bg-amber-100 text-amber-700', cancelled:'bg-gray-100 text-gray-500' };
        const statusLabels  = { scheduled:'Planlandı', completed:'Tamamlandı', rescheduled:'Yeniden Planlandı', cancelled:'İptal' };

        const dayContainer = document.createElement('div');
        dayContainer.className = 'space-y-2';

        data.forEach(iv => {
            const sc = statusColors[iv.status] || 'bg-gray-100 text-gray-500';
            const sl = statusLabels[iv.status] || iv.status;

            const link = document.createElement('a');
            link.href = iv.url;
            link.className = 'block p-3 rounded-lg border border-gray-100 hover:border-orange-200 hover:bg-orange-50 transition-colors group';

            const row1 = document.createElement('div');
            row1.className = 'flex items-start justify-between gap-2';

            const left = document.createElement('div');
            left.className = 'min-w-0';

            const titleEl = document.createElement('p');
            titleEl.className = 'text-xs font-semibold text-gray-800 truncate group-hover:text-primary';
            titleEl.textContent = iv.title;

            const nameEl = document.createElement('p');
            nameEl.className = 'text-xs text-gray-500 mt-0.5';
            nameEl.textContent = iv.applicant_name;

            left.appendChild(titleEl);
            left.appendChild(nameEl);

            const timeEl = document.createElement('span');
            timeEl.className = 'text-xs font-bold text-primary whitespace-nowrap';
            timeEl.textContent = iv.scheduled_at;

            row1.appendChild(left);
            row1.appendChild(timeEl);

            const row2 = document.createElement('div');
            row2.className = 'flex items-center justify-between mt-1.5';

            const durEl = document.createElement('span');
            durEl.className = 'text-xs text-gray-400';
            durEl.textContent = iv.duration + ' dk';

            const badgeEl = document.createElement('span');
            badgeEl.className = 'text-xs px-1.5 py-0.5 rounded-full font-medium ' + sc;
            badgeEl.textContent = sl;

            row2.appendChild(durEl);
            row2.appendChild(badgeEl);

            link.appendChild(row1);
            link.appendChild(row2);
            dayContainer.appendChild(link);
        });

        panel.innerHTML = '';
        panel.appendChild(dayContainer);
    })
    .catch(() => {
        panel.innerHTML = '<p class="text-xs text-red-400 text-center py-4">Yüklenemedi.</p>';
    });
}

// ─── Başvuru Seçim Modalı ────────────────────────────────────────────────────
let searchTimeout = null;

function openApplicationModal() {
    var modal = document.getElementById('application_modal');
    // Modal'ı body'ye taşı (overflow:hidden olan container'dan kurtulmak için)
    if (modal.parentElement !== document.body) {
        document.body.appendChild(modal);
    }
    modal.style.display = 'block';
    document.body.style.overflow = 'hidden';
    document.getElementById('application_search_input').value = '';
    searchApplications('');
    setTimeout(() => document.getElementById('application_search_input').focus(), 100);
}

function closeApplicationModal() {
    var modal = document.getElementById('application_modal');
    modal.style.display = 'none';
    document.body.style.overflow = '';
}

function searchApplications(q) {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => {
        const list = document.getElementById('application_list');
        list.innerHTML = '<p class="text-xs text-gray-400 text-center py-8">Yükleniyor...</p>';

        fetch(searchAppUrl + '?q=' + encodeURIComponent(q), {
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }
        })
        .then(r => r.json())
        .then(data => {
            if (!data || data.length === 0) {
                list.innerHTML = '<p class="text-xs text-gray-400 text-center py-8">Başvuru bulunamadı.</p>';
                return;
            }

            const statusColors = {
                pending:     'bg-yellow-100 text-yellow-700',
                reviewing:   'bg-blue-100 text-blue-700',
                shortlisted: 'bg-green-100 text-green-700',
            };
            const statusLabels = {
                pending:     'Bekliyor',
                reviewing:   'İnceleniyor',
                shortlisted: 'Kısa Liste',
            };

            const container = document.createElement('div');
            container.className = 'space-y-1';

            data.forEach(app => {
                const sc = statusColors[app.status] || 'bg-gray-100 text-gray-500';
                const sl = statusLabels[app.status] || app.status;

                const btn = document.createElement('button');
                btn.type = 'button';
                btn.className = 'w-full text-left px-4 py-3 rounded-lg hover:bg-orange-50 hover:border-orange-200 border border-transparent transition-colors group';
                // Veriyi data attribute olarak sakla (XSS-safe)
                btn.dataset.appId       = app.id;
                btn.dataset.appName     = app.full_name;
                btn.dataset.appPosition = app.position;
                btn.dataset.appEmail    = app.email;

                const inner = document.createElement('div');
                inner.className = 'flex items-center justify-between gap-3';

                const left = document.createElement('div');
                left.className = 'min-w-0';

                const nameEl = document.createElement('p');
                nameEl.className = 'text-sm font-medium text-gray-800 group-hover:text-primary truncate';
                nameEl.textContent = app.full_name;

                const detailEl = document.createElement('p');
                detailEl.className = 'text-xs text-gray-500 truncate';
                detailEl.textContent = app.position + ' · ' + app.email;

                left.appendChild(nameEl);
                left.appendChild(detailEl);

                const right = document.createElement('div');
                right.className = 'flex items-center gap-2 flex-shrink-0';

                const badge = document.createElement('span');
                badge.className = 'text-xs px-1.5 py-0.5 rounded-full font-medium ' + sc;
                badge.textContent = sl;

                const dateEl = document.createElement('span');
                dateEl.className = 'text-xs text-gray-400';
                dateEl.textContent = app.created_at;

                right.appendChild(badge);
                right.appendChild(dateEl);

                inner.appendChild(left);
                inner.appendChild(right);
                btn.appendChild(inner);

                btn.addEventListener('click', function () {
                    selectApplication(
                        this.dataset.appId,
                        this.dataset.appName,
                        this.dataset.appPosition,
                        this.dataset.appEmail
                    );
                });

                container.appendChild(btn);
            });

            list.innerHTML = '';
            list.appendChild(container);
        })
        .catch(() => {
            list.innerHTML = '<p class="text-xs text-red-400 text-center py-8">Yüklenemedi.</p>';
        });
    }, 300);
}

function selectApplication(id, name, position, email) {
    document.getElementById('job_application_id').value = id;
    document.getElementById('selected_app_name').textContent = name;
    document.getElementById('selected_app_detail').textContent = position + ' — ' + email;
    document.getElementById('selected_application_display').classList.remove('hidden');
    document.getElementById('open_application_modal_btn').classList.add('hidden');

    // Başvuru seçilince manuel kişi alanlarını gizle ve temizle
    const manualFields = document.getElementById('manual_candidate_fields');
    if (manualFields) {
        manualFields.style.display = 'none';
        document.getElementById('candidate_name').value = '';
        document.getElementById('candidate_email').value = '';
    }

    // Başlık otomatik doldur (boşsa)
    const titleInput = document.getElementById('interview_title');
    if (!titleInput.value) {
        titleInput.value = '1. Mülakat — ' + name;
    }

    closeApplicationModal();
}

function clearApplicationSelection() {
    document.getElementById('job_application_id').value = '';
    document.getElementById('selected_application_display').classList.add('hidden');
    document.getElementById('open_application_modal_btn').classList.remove('hidden');

    // Başvuru temizlenince manuel kişi alanlarını tekrar göster
    const manualFields = document.getElementById('manual_candidate_fields');
    if (manualFields) {
        manualFields.style.display = 'block';
    }
}

function skipApplicationSelection() {
    // Başvuru seçimini temizle ve modalı kapat — başvurusuz devam
    document.getElementById('job_application_id').value = '';
    document.getElementById('selected_application_display').classList.add('hidden');
    document.getElementById('open_application_modal_btn').classList.remove('hidden');

    // Manuel kişi alanlarını göster
    const manualFields = document.getElementById('manual_candidate_fields');
    if (manualFields) {
        manualFields.style.display = 'block';
    }

    closeApplicationModal();
}

// ESC ile modal kapat
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closeApplicationModal();
});
</script>
@endsection