{{-- Rehber Kontrat Modalı (Faz 4) --}}
<div class="modal fade" id="contractModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content" style="border:none;border-radius:20px;overflow:hidden;">
            <div class="modal-header" style="background:linear-gradient(135deg,#334155,#1e293b);color:#fff;border:none;padding:18px 22px;">
                <div>
                    <h5 class="modal-title fw-800 mb-0"><i class="fas fa-file-signature me-2"></i>Kaynak Sözleşmesi</h5>
                    <div class="small" style="opacity:.8" id="rcResourceName">—</div>
                </div>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body p-4" style="background:#f8fafc;">
                {{-- ADIM 1: Şablon seç + üret --}}
                <div id="rcStepSetup">
                    {{-- Mevcut kontratlar --}}
                    <div id="rcExistingWrap" class="mb-4 d-none">
                        <div class="rc-label">Bu Atamaya Ait Kontratlar</div>
                        <div id="rcExistingList" class="d-flex flex-column gap-2"></div>
                        <hr class="my-3">
                    </div>

                    <div class="rc-label">Şablon Seç</div>
                    <select id="rcTemplate" class="form-select mb-3" style="border-radius:12px;"></select>

                    <div id="rcManualWrap" class="mb-3"></div>

                    <div id="rcNoTemplates" class="text-center text-muted py-4 d-none">
                        <i class="fas fa-folder-open fs-3 mb-2 d-block" style="opacity:.4"></i>
                        Bu kaynak için aktif sözleşme şablonu yok.<br>
                        <a href="{{ route('agency.settings.contracts.create') }}" target="_blank">Yeni bir kontrat şablonu oluşturun</a> (Bağlam: <strong>Rehber / Kaynak</strong>).
                    </div>

                    <button type="button" class="btn w-100 fw-700 text-white" id="rcGenerateBtn"
                        style="background:#334155;border-radius:12px;padding:12px;">
                        <i class="fas fa-wand-magic-sparkles me-1"></i> Kontratı Oluştur
                    </button>
                </div>

                {{-- ADIM 2: Düzenle --}}
                <div id="rcStepEdit" class="d-none">
                    <div class="d-flex align-items-center justify-content-between mb-2">
                        <button type="button" class="btn btn-sm btn-light fw-700" id="rcBackBtn" style="border-radius:10px;">
                            <i class="fas fa-arrow-left me-1"></i> Geri
                        </button>
                        <span class="rc-status-badge" id="rcStatusBadge">Taslak</span>
                    </div>
                    <input type="text" id="rcTitle" class="form-control fw-700 mb-2" style="border-radius:12px;" placeholder="Kontrat başlığı">
                    <div style="border:1px solid #cbd5e1;border-radius:12px;overflow:hidden;background:#fff;">
                        <div id="rcQuillEditor" style="height:340px;"></div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 mt-3">
                        <button type="button" class="btn fw-700 text-white" id="rcSaveBtn" style="background:#0ea5e9;border-radius:10px;">
                            <i class="fas fa-save me-1"></i> Kaydet
                        </button>
                        <button type="button" class="btn fw-700 text-white" id="rcSendBtn" style="background:#16a34a;border-radius:10px;">
                            <i class="fas fa-paper-plane me-1"></i> Gönder
                        </button>
                        <button type="button" class="btn fw-700" id="rcPreviewBtn" style="background:#e2e8f0;border-radius:10px;color:#334155;">
                            <i class="fas fa-eye me-1"></i> Ön İzleme
                        </button>
                        <button type="button" class="btn fw-700 ms-auto" id="rcDeleteBtn" style="background:#fee2e2;color:#dc2626;border-radius:10px;">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@push('styles')
<style>
    #contractModal .rc-label { font-size:.72rem;font-weight:800;text-transform:uppercase;letter-spacing:.03em;color:#94a3b8;margin-bottom:6px; }
    #contractModal .rc-status-badge { font-size:.7rem;font-weight:800;color:#fff;background:#64748b;border-radius:8px;padding:4px 10px; }
    #contractModal .rc-existing-item { display:flex;align-items:center;gap:10px;padding:10px 12px;border:1px solid #e2e8f0;border-radius:12px;background:#fff;transition:.15s; }
    #contractModal .rc-existing-item:hover { border-color:#94a3b8;background:#f8fafc; }
    #contractModal .rc-existing-item .flex-grow-1, #contractModal .rc-existing-item i.fa-file-lines { cursor:pointer; }
    #contractModal .rc-existing-del { width:30px;height:30px;border-radius:8px;border:1px solid #fecaca;background:#fff;color:#ef4444;cursor:pointer;flex-shrink:0;transition:.15s; }
    #contractModal .rc-existing-del:hover { background:#fee2e2; }
    #contractModal .rc-manual-field { margin-bottom:10px; }
    #contractModal .rc-manual-field label { font-size:.78rem;font-weight:700;color:#475569;margin-bottom:3px;display:block; }
    #contractModal .ql-toolbar.ql-snow { border:none;border-bottom:1px solid #e2e8f0;background:#f8fafc; }
    #contractModal .ql-container.ql-snow { border:none; }
</style>
@endpush

@push('scripts')
<script>
(function () {
    const CSRF = document.querySelector('meta[name="csrf-token"]').content;
    const OPS_BASE = @js(url('agency/operations'));
    const RC_BASE = @js(url('agency/resource-contracts'));
    const OPS_TYPE = @js($typeKey);
    const OPS_ID = {{ $id }};

    const modalEl = document.getElementById('contractModal');
    const modal = new bootstrap.Modal(modalEl);

    let currentSchedule = null;
    let currentContract = null;
    let optionsCache = null;
    let rcQuill = null;

    const $ = id => document.getElementById(id);

    // Geri bildirim: operasyon sayfasında toastr yok; SweetAlert2 (global) ile göster.
    function rcNotify(msg, ok) {
        if (window.Swal) {
            Swal.fire({ toast: true, position: 'top-end', timer: 2200, timerProgressBar: true,
                showConfirmButton: false, icon: ok === false ? 'error' : 'success', title: msg });
        } else if (typeof toastr !== 'undefined') {
            ok === false ? toastr.error(msg) : toastr.success(msg);
        } else {
            alert(msg);
        }
    }

    function initQuill() {
        if (rcQuill) return rcQuill;
        rcQuill = new Quill('#rcQuillEditor', {
            theme: 'snow',
            modules: { toolbar: [
                [{ 'header': [1, 2, 3, false] }],
                ['bold', 'italic', 'underline'],
                [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                [{ 'align': [] }], ['link', 'clean']
            ] }
        });
        return rcQuill;
    }

    function showStep(step) {
        $('rcStepSetup').classList.toggle('d-none', step !== 'setup');
        $('rcStepEdit').classList.toggle('d-none', step !== 'edit');
    }

    function renderManualFields() {
        const wrap = $('rcManualWrap');
        wrap.innerHTML = '';
        const tid = $('rcTemplate').value;
        const tpl = (optionsCache?.templates || []).find(t => String(t.id) === String(tid));
        if (!tpl || !tpl.manual_fields || !tpl.manual_fields.length) return;
        const head = document.createElement('div');
        head.className = 'rc-label';
        head.textContent = 'Manuel Alanlar';
        wrap.appendChild(head);
        tpl.manual_fields.forEach(f => {
            const div = document.createElement('div');
            div.className = 'rc-manual-field';
            div.innerHTML = `<label>${f.label}</label>
                <input type="text" class="form-control rc-manual-input" data-token="${f.token}" style="border-radius:10px;" placeholder="${f.label}">`;
            wrap.appendChild(div);
        });
    }

    function renderExisting() {
        const wrap = $('rcExistingWrap');
        const list = $('rcExistingList');
        const items = optionsCache?.existing || [];
        if (!items.length) { wrap.classList.add('d-none'); return; }
        wrap.classList.remove('d-none');
        list.innerHTML = '';
        items.forEach(c => {
            const div = document.createElement('div');
            div.className = 'rc-existing-item';
            div.innerHTML = `<i class="fas fa-file-lines" style="color:${c.status_color}"></i>
                <div class="flex-grow-1" style="min-width:0"><div class="fw-700 text-dark text-truncate" style="font-size:.9rem">${c.title}</div>
                <div class="small text-muted">${c.created_at || ''}</div></div>
                <span class="rc-status-badge" style="background:${c.status_color}">${c.status_label}</span>
                <button class="rc-existing-del" title="Sil"><i class="fas fa-trash"></i></button>`;
            div.querySelector('.flex-grow-1').addEventListener('click', () => openContract(c.id));
            div.querySelector('i.fa-file-lines').addEventListener('click', () => openContract(c.id));
            div.querySelector('.rc-existing-del').addEventListener('click', (e) => { e.stopPropagation(); deleteExisting(c.id); });
            list.appendChild(div);
        });
    }

    function deleteExisting(id) {
        if (!confirm('Bu kontrat silinsin mi? Rehbere gönderildiyse sohbette de "iptal edildi" olarak görünecek.')) return;
        fetch(`${RC_BASE}/${id}`, { method: 'DELETE', headers: { 'X-CSRF-TOKEN': CSRF } })
            .then(r => r.json()).then(d => {
                if (d.success) {
                    if (optionsCache) optionsCache.existing = (optionsCache.existing || []).filter(x => x.id !== id);
                    renderExisting();
                    if (currentContract && currentContract.id === id) { currentContract = null; showStep('setup'); }
                    rcNotify(d.message || 'Kontrat silindi.');
                } else { rcNotify(d.message || 'Silinemedi.', false); }
            }).catch(() => rcNotify('Bağlantı hatası.', false));
    }

    window.openContractModal = function (scheduleId, resourceName) {
        currentSchedule = scheduleId;
        currentContract = null;
        $('rcResourceName').textContent = resourceName || '';
        showStep('setup');
        $('rcManualWrap').innerHTML = '';
        $('rcTemplate').innerHTML = '<option>Yükleniyor…</option>';
        modal.show();

        fetch(`${OPS_BASE}/${OPS_TYPE}/${OPS_ID}/resources/${scheduleId}/contract/options`, {
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        }).then(r => r.json()).then(data => {
            optionsCache = data;
            const sel = $('rcTemplate');
            if (!data.templates || !data.templates.length) {
                sel.innerHTML = '';
                sel.classList.add('d-none');
                $('rcNoTemplates').classList.remove('d-none');
                $('rcGenerateBtn').classList.add('d-none');
            } else {
                sel.classList.remove('d-none');
                $('rcNoTemplates').classList.add('d-none');
                $('rcGenerateBtn').classList.remove('d-none');
                sel.innerHTML = data.templates.map(t => `<option value="${t.id}">${t.title}</option>`).join('');
                renderManualFields();
            }
            renderExisting();
        }).catch(() => { $('rcTemplate').innerHTML = '<option>Hata</option>'; });
    };

    $('rcTemplate').addEventListener('change', renderManualFields);

    $('rcGenerateBtn').addEventListener('click', function () {
        const tid = $('rcTemplate').value;
        if (!tid) return;
        const manual = {};
        document.querySelectorAll('.rc-manual-input').forEach(i => manual[i.dataset.token] = i.value);

        this.disabled = true;
        this.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Oluşturuluyor…';
        fetch(`${OPS_BASE}/${OPS_TYPE}/${OPS_ID}/resources/${currentSchedule}/contract`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
            body: JSON.stringify({ template_id: tid, manual })
        }).then(r => r.json()).then(d => {
            this.disabled = false;
            this.innerHTML = '<i class="fas fa-wand-magic-sparkles me-1"></i> Kontratı Oluştur';
            if (d.success) { loadIntoEditor(d.contract); if (typeof toastr !== 'undefined') toastr.success(d.message); }
        }).catch(() => { this.disabled = false; this.innerHTML = '<i class="fas fa-wand-magic-sparkles me-1"></i> Kontratı Oluştur'; });
    });

    function openContract(id) {
        fetch(`${RC_BASE}/${id}`, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(r => r.json()).then(d => { if (d.success) loadIntoEditor(d.contract); });
    }

    function loadIntoEditor(contract) {
        currentContract = contract;
        showStep('edit');
        $('rcTitle').value = contract.title || '';
        initQuill();
        rcQuill.root.innerHTML = contract.content || '';
        updateStatusBadge(contract);
    }

    function updateStatusBadge(contract) {
        const badge = $('rcStatusBadge');
        badge.textContent = contract.status_label || 'Taslak';
        badge.style.background = contract.status_color || '#64748b';
    }

    $('rcBackBtn').addEventListener('click', () => showStep('setup'));

    function saveContract() {
        return fetch(`${RC_BASE}/${currentContract.id}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
            body: JSON.stringify({ title: $('rcTitle').value, content: rcQuill.root.innerHTML })
        }).then(r => r.json());
    }

    $('rcSaveBtn').addEventListener('click', function () {
        if (!currentContract) { rcNotify('Önce bir kontrat oluşturun.', false); return; }
        const btn = this, orig = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Kaydediliyor…';
        saveContract().then(d => {
            btn.disabled = false;
            if (d.success) {
                currentContract = d.contract; updateStatusBadge(d.contract);
                btn.innerHTML = '<i class="fas fa-check me-1"></i> Kaydedildi';
                setTimeout(() => { btn.innerHTML = orig; }, 1600);
                rcNotify(d.message || 'Kontrat kaydedildi.');
            } else { btn.innerHTML = orig; rcNotify(d.message || 'Kaydedilemedi.', false); }
        }).catch(() => { btn.disabled = false; btn.innerHTML = orig; rcNotify('Bağlantı hatası, kaydedilemedi.', false); });
    });

    $('rcSendBtn').addEventListener('click', function () {
        if (!currentContract) { rcNotify('Önce bir kontrat oluşturun.', false); return; }
        const btn = this, orig = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Gönderiliyor…';
        // Önce güncel içeriği kaydet, sonra rehbere chat'ten dosya olarak gönder
        saveContract()
            .then(() => fetch(`${RC_BASE}/${currentContract.id}/send-to-guide`, { method: 'POST', headers: { 'X-CSRF-TOKEN': CSRF } }))
            .then(r => r.json()).then(d => {
                if (d.success) {
                    currentContract = d.contract; updateStatusBadge(d.contract);
                    rcNotify(d.message || 'Rehbere gönderildi.');
                    setTimeout(() => location.reload(), 1200);
                } else { btn.disabled = false; btn.innerHTML = orig; rcNotify(d.message || 'Gönderilemedi.', false); }
            }).catch(() => { btn.disabled = false; btn.innerHTML = orig; rcNotify('Bağlantı hatası.', false); });
    });

    $('rcPreviewBtn').addEventListener('click', function () {
        const w = window.open('', '_blank', 'width=800,height=900');
        w.document.write(`<html><head><title>${$('rcTitle').value}</title>
            <style>body{font-family:Inter,Arial,sans-serif;max-width:720px;margin:40px auto;padding:0 20px;line-height:1.7;color:#1e293b}</style>
            </head><body><h2>${$('rcTitle').value}</h2>${rcQuill.root.innerHTML}</body></html>`);
        w.document.close();
    });

    $('rcDeleteBtn').addEventListener('click', function () {
        if (!currentContract || !confirm('Bu kontrat silinsin mi?')) return;
        fetch(`${RC_BASE}/${currentContract.id}`, { method: 'DELETE', headers: { 'X-CSRF-TOKEN': CSRF } })
            .then(r => r.json()).then(d => { if (d.success) { rcNotify(d.message || 'Kontrat silindi.'); setTimeout(() => location.reload(), 800); } });
    });
})();
</script>
@endpush
