@extends('agency.layouts.app')

@section('title', 'Tedarikçi Düzenle')
@section('page_title', 'Tedarikçi Düzenle')

@push('styles')
<style>
.form-page {
    max-width: 880px;
    margin: 0 auto;
}
.form-card {
    background: #fff; border-radius: 20px;
    border: 1px solid #f1f5f9;
    box-shadow: 0 2px 12px rgba(0,0,0,.05);
    overflow: hidden; margin-bottom: 1.25rem;
}
.form-section-header {
    display: flex; align-items: center; gap: .75rem;
    padding: 1.1rem 1.5rem;
    border-bottom: 1px solid #f1f5f9;
    background: #fafbff;
}
.form-section-icon {
    width: 36px; height: 36px; border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 15px; flex-shrink: 0;
}
.form-section-title { font-size: .9rem; font-weight: 700; color: #0f172a; }
.form-section-body { padding: 1.5rem; }

/* Field */
.field-group { margin-bottom: 1.25rem; }
.field-label {
    display: block; font-size: .78rem; font-weight: 700;
    color: #64748b; text-transform: uppercase; letter-spacing: .4px;
    margin-bottom: .4rem;
}
.field-label .req { color: #ef4444; margin-left: 2px; }
.field-input {
    width: 100%; border: 1.5px solid #e2e8f0; border-radius: 10px;
    padding: .65rem .9rem; font-size: .875rem; color: #0f172a;
    background: #f8fafc; transition: all .2s;
    height: 44px;
}
.field-input:focus {
    outline: none; border-color: #2563eb;
    box-shadow: 0 0 0 3px rgba(37,99,235,.1);
    background: #fff;
}
textarea.field-input { height: auto; resize: vertical; }
select.field-input { cursor: pointer; }
.field-help { font-size: .75rem; color: #94a3b8; margin-top: .3rem; }

/* Grid */
.fg-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
.fg-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 1rem; }
@media(max-width:640px) { .fg-2,.fg-3 { grid-template-columns: 1fr; } }

/* Sticky footer */
.form-footer {
    position: sticky; bottom: 0; z-index: 10;
    background: #fff; border-top: 1px solid #f1f5f9;
    padding: 1rem 1.5rem; display: flex; justify-content: space-between;
    align-items: center; border-radius: 0 0 20px 20px;
    box-shadow: 0 -4px 20px rgba(0,0,0,.05);
}

.field-error { border-color: #ef4444 !important; background:#fff5f5 !important; }
.error-msg { font-size:.75rem;color:#ef4444;margin-top:.25rem; }

/* Dynamic lists */
.dynamic-list { display: flex; flex-direction: column; gap: .5rem; }
.dynamic-item { display: flex; gap: .5rem; align-items: center; }
.btn-add-item { 
    background: #eff6ff; color: #2563eb; border: none; 
    width: 38px; height: 38px; border-radius: 8px; 
    cursor: pointer; transition: all .2s;
    display: flex; align-items: center; justify-content: center;
}
.btn-add-item:hover { background: #2563eb; color: #fff; }
.btn-remove-item {
    background: #fff1f2; color: #ef4444; border: none;
    width: 38px; height: 38px; border-radius: 8px;
    cursor: pointer; transition: all .2s;
    display: flex; align-items: center; justify-content: center;
}
.btn-remove-item:hover { background: #ef4444; color: #fff; }

.type-pill {
    display: block; padding: .45rem 1rem; font-size: .82rem; font-weight: 600;
    color: #64748b; background: transparent; transition: all .2s;
    cursor: pointer;
}
input[type=radio]:checked + .type-pill {
    background: #2563eb; color: #fff;
}
</style>
@endpush

@section('content')
<div class="container-fluid">
<div class="form-page">

{{-- Back link --}}
<div class="d-flex align-items-center gap-2 mb-3" style="font-size:.83rem;color:#94a3b8">
    <a href="{{ route('agency.suppliers.index') }}" style="color:#2563eb;text-decoration:none;font-weight:600">
        <i class="fas fa-chevron-left me-1"></i>Tedarikçiler
    </a>
    <i class="fas fa-chevron-right" style="font-size:10px"></i>
    <span style="color:#0f172a;font-weight:600">{{ $supplier->full_name }}</span>
</div>

@if(session('error'))
    <div class="alert alert-danger border-0 shadow-sm" style="border-radius:12px; font-size:.85rem">
        <i class="fas fa-exclamation-circle me-2"></i>{{ session('error') }}
    </div>
@endif

@if($errors->any())
    <div class="alert alert-danger border-0 shadow-sm" style="border-radius:12px; font-size:.85rem">
        <ul class="mb-0">
            @foreach($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<form method="POST" action="{{ route('agency.suppliers.update', $supplier) }}" id="supplierForm">
@csrf
@method('PUT')

{{-- ─── TEMEL BİLGİLER ─── --}}
<div class="form-card">
    <div class="form-section-header">
        <div class="form-section-icon" style="background:#eff6ff;color:#2563eb"><i class="fas fa-handshake"></i></div>
        <div>
            <div class="form-section-title">Temel Tedarikçi Bilgileri</div>
        </div>
        {{-- Type selector --}}
        <div class="ms-auto d-flex rounded-pill overflow-hidden" style="border:1.5px solid #e2e8f0">
            <label style="cursor:pointer">
                <input type="radio" name="type" value="individual" {{ old('type', $supplier->type) === 'individual' ? 'checked' : '' }} class="d-none type-radio">
                <span class="type-pill" data-val="individual">👤 Kişi</span>
            </label>
            <label style="cursor:pointer">
                <input type="radio" name="type" value="corporate" {{ old('type', $supplier->type) === 'corporate' ? 'checked' : '' }} class="d-none type-radio">
                <span class="type-pill" data-val="corporate">🏢 Şirket</span>
            </label>
        </div>
    </div>
    <div class="form-section-body">
        <div class="fg-2">
            <div class="field-group">
                <label class="field-label">Tedarikçi Tipi (Hizmet Alanı) <span class="req">*</span> <small class="text-muted" style="font-weight:500">— birden fazla seçebilirsiniz</small></label>
                @include('agency.suppliers._type-chips', ['selected' => old('supplier_types', $supplier->type_codes)])
                @error('supplier_types') <div class="error-msg">{{ $message }}</div> @enderror
                @error('supplier_types.*') <div class="error-msg">{{ $message }}</div> @enderror
            </div>

            <div class="field-group">
                <label class="field-label">Durum<span class="req">*</span></label>
                <select name="status" class="field-input">
                    <option value="active"    {{ old('status', $supplier->status) === 'active'    ? 'selected' : '' }}>✅ Aktif</option>
                    <option value="potential" {{ old('status', $supplier->status) === 'potential' ? 'selected' : '' }}>🔔 Potansiyel</option>
                    <option value="inactive"  {{ old('status', $supplier->status) === 'inactive'  ? 'selected' : '' }}>⏸ Pasif</option>
                    <option value="blocked"   {{ old('status', $supplier->status) === 'blocked'   ? 'selected' : '' }}>🚫 Engellenmiş</option>
                </select>
            </div>
        </div>

        {{-- Individual Fields --}}
        <div class="fg-2" id="individualFields" style="{{ old('type', $supplier->type) === 'individual' ? '' : 'display:none' }}">
            <div class="field-group">
                <label class="field-label">Ad<span class="req">*</span></label>
                <input type="text" name="first_name" value="{{ old('first_name', $supplier->first_name) }}"
                       class="field-input {{ $errors->has('first_name') ? 'field-error' : '' }}" placeholder="Ad">
                @error('first_name') <div class="error-msg">{{ $message }}</div> @enderror
            </div>
            <div class="field-group">
                <label class="field-label">Soyad<span class="req">*</span></label>
                <input type="text" name="last_name" value="{{ old('last_name', $supplier->last_name) }}"
                       class="field-input {{ $errors->has('last_name') ? 'field-error' : '' }}" placeholder="Soyad">
                @error('last_name') <div class="error-msg">{{ $message }}</div> @enderror
            </div>
        </div>

        {{-- Corporate Fields --}}
        <div id="corporateFields" style="{{ old('type', $supplier->type) === 'corporate' ? '' : 'display:none' }}">
            <div class="fg-3">
                <div class="field-group col-md-12" style="grid-column: span 3">
                    <label class="field-label">Firma Adı<span class="req">*</span></label>
                    <input type="text" name="company_name" value="{{ old('company_name', $supplier->company_name) }}"
                           class="field-input {{ $errors->has('company_name') ? 'field-error' : '' }}" placeholder="Firma Adı">
                    @error('company_name') <div class="error-msg">{{ $message }}</div> @enderror
                </div>
            </div>
            <div class="fg-2">
                <div class="field-group">
                    <label class="field-label">Vergi No</label>
                    <input type="text" name="company_tax_number" value="{{ old('company_tax_number', $supplier->company_tax_number) }}" class="field-input" placeholder="Vergi No">
                </div>
                <div class="field-group">
                    <label class="field-label">Vergi Dairesi</label>
                    <input type="text" name="company_tax_office" value="{{ old('company_tax_office', $supplier->company_tax_office) }}" class="field-input" placeholder="Vergi Dairesi">
                </div>
            </div>
        </div>
    </div>
</div>

{{-- ─── SORUMLU KİŞİ BİLGİLERİ (Şirketler için Ekstra) ─── --}}
<div class="form-card" id="responsiblePersonCard" style="{{ old('type', $supplier->type) === 'corporate' ? '' : 'display:none' }}">
    <div class="form-section-header">
        <div class="form-section-icon" style="background:#ede9fe;color:#8b5cf6"><i class="fas fa-user-tie"></i></div>
        <div class="form-section-title">Sorumlu Kişi Bilgileri</div>
    </div>
    <div class="form-section-body">
        <div class="fg-3">
            <div class="field-group">
                <label class="field-label">Sorumlu Adı</label>
                <input type="text" name="responsible_person_first_name" value="{{ old('responsible_person_first_name', $supplier->responsible_person_first_name) }}" class="field-input" placeholder="Ad">
            </div>
            <div class="field-group">
                <label class="field-label">Sorumlu Soyadı</label>
                <input type="text" name="responsible_person_last_name" value="{{ old('responsible_person_last_name', $supplier->responsible_person_last_name) }}" class="field-input" placeholder="Soyad">
            </div>
            <div class="field-group">
                <label class="field-label">Cinsiyet</label>
                <select name="responsible_person_gender" class="field-input">
                    @php $rpGender = old('responsible_person_gender', $supplier->responsible_person_gender); @endphp
                    <option value="">Belirtilmedi</option>
                    <option value="male"   {{ $rpGender === 'male'   ? 'selected' : '' }}>Erkek</option>
                    <option value="female" {{ $rpGender === 'female' ? 'selected' : '' }}>Kadın</option>
                    <option value="other"  {{ $rpGender === 'other'  ? 'selected' : '' }}>Diğer</option>
                </select>
            </div>
        </div>
        <div class="fg-2">
            <div class="field-group">
                <label class="field-label">Sorumlu Telefon</label>
                <input type="text" name="responsible_person_phone" value="{{ old('responsible_person_phone', $supplier->responsible_person_phone) }}" class="field-input" placeholder="+90 5xx xxx xx xx">
            </div>
            <div class="field-group">
                <label class="field-label">Sorumlu E-posta</label>
                <input type="email" name="responsible_person_email" value="{{ old('responsible_person_email', $supplier->responsible_person_email) }}" class="field-input" placeholder="sorumlu@firma.com">
            </div>
        </div>
    </div>
</div>

{{-- ─── İLETİŞİM BİLGİLERİ ─── --}}
<div class="form-card">
    <div class="form-section-header">
        <div class="form-section-icon" style="background:#eef2ff;color:#6366f1"><i class="fas fa-envelope"></i></div>
        <div class="form-section-title">İletişim Bilgileri</div>
    </div>
    <div class="form-section-body">
        <div class="fg-2">
            <div class="field-group">
                <label class="field-label">E-posta Adresleri</label>
                <div class="dynamic-list" id="emailList">
                    @php $oldEmails = old('emails', $supplier->emails ?: ['']); @endphp
                    @foreach($oldEmails as $index => $oldEmail)
                        <div class="dynamic-item">
                            <input type="email" name="emails[]" value="{{ $oldEmail }}" class="field-input" placeholder="ornek@firma.com">
                            @if($loop->first)
                                <button type="button" class="btn-add-item" id="btnAddEmail"><i class="fas fa-plus"></i></button>
                            @else
                                <button type="button" class="btn-remove-item remove-email"><i class="fas fa-trash"></i></button>
                            @endif
                        </div>
                    @endforeach
                </div>
            </div>
            <div class="field-group">
                <label class="field-label">Telefon Numaraları</label>
                <div class="dynamic-list" id="phoneList">
                    @php $oldPhones = old('phones', $supplier->phones ?: ['']); @endphp
                    @foreach($oldPhones as $index => $oldPhone)
                        <div class="dynamic-item">
                            <input type="text" name="phones[]" value="{{ $oldPhone }}" class="field-input" placeholder="+90 xxx xxx xx xx">
                            @if($loop->first)
                                <button type="button" class="btn-add-item" id="btnAddPhone"><i class="fas fa-plus"></i></button>
                            @else
                                <button type="button" class="btn-remove-item remove-phone"><i class="fas fa-trash"></i></button>
                            @endif
                        </div>
                    @endforeach
                </div>
            </div>
        </div>
        <div class="fg-2">
            <div class="field-group">
                <label class="field-label">Birincil Sabit Telefon</label>
                <input type="text" name="phone" value="{{ old('phone', $supplier->phone) }}" class="field-input" placeholder="+90 212 xxx xx xx">
            </div>
            <div class="field-group">
                <label class="field-label">Web Sitesi</label>
                <input type="text" name="website" value="{{ old('website', $supplier->website) }}" class="field-input" placeholder="www.firma.com">
            </div>
        </div>
    </div>
</div>

{{-- ─── ADRES BİLGİLERİ ─── --}}
<div class="form-card">
    <div class="form-section-header">
        <div class="form-section-icon" style="background:#d1fae5;color:#10b981"><i class="fas fa-map-marker-alt"></i></div>
        <div class="form-section-title">Adres & Konum</div>
    </div>
    <div class="form-section-body">
        <div class="fg-3">
            <div class="field-group">
                <label class="field-label">Şehir</label>
                <input type="text" name="city" value="{{ old('city', $supplier->city) }}" class="field-input" placeholder="Şehir">
            </div>
            <div class="field-group">
                <label class="field-label">İlçe</label>
                <input type="text" name="district" value="{{ old('district', $supplier->district) }}" class="field-input" placeholder="İlçe">
            </div>
            <div class="field-group">
                <label class="field-label">Ülke</label>
                <input type="text" name="country" value="{{ old('country', $supplier->country ?: 'TR') }}" class="field-input" maxlength="2" placeholder="TR">
            </div>
        </div>
        <div class="fg-2">
            <div class="field-group">
                <label class="field-label">Adres</label>
                <input type="text" name="address" value="{{ old('address', $supplier->address) }}" class="field-input" placeholder="Açık adres...">
            </div>
            <div class="field-group">
                <label class="field-label">Posta Kodu</label>
                <input type="text" name="postal_code" value="{{ old('postal_code', $supplier->postal_code) }}" class="field-input" maxlength="10" placeholder="Posta Kodu">
            </div>
        </div>
    </div>
</div>

{{-- ─── FATURA BİLGİLERİ (Şirketler için Ekstra) ─── --}}
<div class="form-card" id="billingFieldsCard" style="{{ old('type', $supplier->type) === 'corporate' ? '' : 'display:none' }}">
    <div class="form-section-header">
        <div class="form-section-icon" style="background:#fee2e2;color:#ef4444"><i class="fas fa-file-invoice-dollar"></i></div>
        <div class="form-section-title">Fatura Bilgileri</div>
    </div>
    <div class="form-section-body">
        <div class="field-group">
            <label class="field-label">Fatura Adresi</label>
            <textarea name="billing_address" class="field-input" rows="2" placeholder="Fatura Adresi">{{ old('billing_address', $supplier->billing_address) }}</textarea>
        </div>
        <div class="fg-3">
            <div class="field-group">
                <label class="field-label">Fatura Şehir</label>
                <input type="text" name="billing_city" value="{{ old('billing_city', $supplier->billing_city) }}" class="field-input">
            </div>
            <div class="field-group">
                <label class="field-label">Fatura İlçe</label>
                <input type="text" name="billing_district" value="{{ old('billing_district', $supplier->billing_district) }}" class="field-input">
            </div>
            <div class="field-group">
                <label class="field-label">Fatura E-posta</label>
                <input type="email" name="billing_email" value="{{ old('billing_email', $supplier->billing_email) }}" class="field-input" placeholder="muhasebe@firma.com">
            </div>
        </div>
        <div class="fg-2 mt-2 mb-0">
            <div class="field-group mb-0">
                <label class="field-label">Fatura Vergi No</label>
                <input type="text" name="billing_tax_number" value="{{ old('billing_tax_number', $supplier->billing_tax_number) }}" class="field-input">
            </div>
            <div class="field-group mb-0">
                <label class="field-label">Fatura Vergi Dairesi</label>
                <input type="text" name="billing_tax_office" value="{{ old('billing_tax_office', $supplier->billing_tax_office) }}" class="field-input">
            </div>
        </div>
    </div>
</div>

{{-- ─── NOTLAR ─── --}}
<div class="form-card">
    <div class="form-section-header">
        <div class="form-section-icon" style="background:#fef3c7;color:#f59e0b"><i class="fas fa-sticky-note"></i></div>
        <div class="form-section-title">Notlar & Not Defteri</div>
    </div>
    <div class="form-section-body">
        <div class="rte-wrap">
            <div id="notesEditor">{!! old('notes', $supplier->notes) !!}</div>
        </div>
        <textarea name="notes" id="notesInput" class="d-none">{{ old('notes', $supplier->notes) }}</textarea>
        <div class="field-help">Bu notlar yalnızca acente yöneticilerine ve personelinize görünecektir. Kalın, liste ve başlık gibi zengin biçimlendirme kullanabilirsiniz.</div>
    </div>
</div>

{{-- ─── FOOTER ─── --}}
<div class="form-footer">
    <a href="{{ route('agency.suppliers.index') }}" class="btn btn-outline-secondary" style="border-radius:10px">
        <i class="fas fa-times me-1"></i>İptal
    </a>
    <button type="submit" class="btn text-white" style="background:linear-gradient(135deg,#2563eb,#1e40af);border-radius:10px;padding:.65rem 2rem;font-weight:600">
        <i class="fas fa-check me-1"></i>Tedarikçiyi Kaydet
    </button>
</div>

</form>
</div>
</div>
@endsection

@push('scripts')
<script>
// Toggle Person / Company fields
document.querySelectorAll('.type-radio').forEach(r => {
    r.addEventListener('change', function() {
        const isCorp = this.value === 'corporate';
        document.getElementById('corporateFields').style.display = isCorp ? '' : 'none';
        document.getElementById('individualFields').style.display = isCorp ? 'none' : '';
        document.getElementById('responsiblePersonCard').style.display = isCorp ? '' : 'none';
        document.getElementById('billingFieldsCard').style.display = isCorp ? '' : 'none';
    });
});

// Dynamic Email list
const emailList = document.getElementById('emailList');
const btnAddEmail = document.getElementById('btnAddEmail');
btnAddEmail.addEventListener('click', function() {
    const newItem = document.createElement('div');
    newItem.className = 'dynamic-item';
    newItem.innerHTML = `
        <input type="email" name="emails[]" class="field-input" placeholder="ikincil@firma.com">
        <button type="button" class="btn-remove-item remove-email"><i class="fas fa-trash"></i></button>
    `;
    emailList.appendChild(newItem);
});
emailList.addEventListener('click', function(e) {
    if (e.target.closest('.remove-email')) {
        e.target.closest('.dynamic-item').remove();
    }
});

// Dynamic Phone list
const phoneList = document.getElementById('phoneList');
const btnAddPhone = document.getElementById('btnAddPhone');
btnAddPhone.addEventListener('click', function() {
    const newItem = document.createElement('div');
    newItem.className = 'dynamic-item';
    newItem.innerHTML = `
        <input type="text" name="phones[]" class="field-input" placeholder="+90 xxx xxx xx xx">
        <button type="button" class="btn-remove-item remove-phone"><i class="fas fa-trash"></i></button>
    `;
    phoneList.appendChild(newItem);
});
phoneList.addEventListener('click', function(e) {
    if (e.target.closest('.remove-phone')) {
        e.target.closest('.dynamic-item').remove();
    }
});

// Zengin metin (Quill) — Notlar
let notesQuill = null;
if (typeof Quill !== 'undefined' && document.getElementById('notesEditor')) {
    notesQuill = new Quill('#notesEditor', {
        theme: 'snow',
        placeholder: 'Tedarikçi hakkında dahili detaylar, anlaşma notları...',
        modules: {
            toolbar: [
                ['bold', 'italic', 'underline'],
                [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                [{ 'header': [3, 4, false] }],
                ['link', 'clean']
            ]
        }
    });
    document.getElementById('supplierForm').addEventListener('submit', function() {
        const html = notesQuill.getText().trim().length ? notesQuill.root.innerHTML : '';
        document.getElementById('notesInput').value = html;
    });
}
</script>
@endpush
