
<?php
    $mailIcon = fn ($m) => $m->direction() === 'outbound' ? 'fa-arrow-up-right-from-square' : 'fa-inbox';
    $mailColor = fn ($m) => $m->direction() === 'outbound' ? '#2563eb' : '#f59e0b';

    // Dışa aktarma biçimleri tek kaynaktan gelir (MailExportService::formats)
    $mailFormats = \App\Services\Mail\MailExportService::formats();
?>

<div class="pfx mlx" data-mail-root
     data-show-url="<?php echo e(route('agency.customers.mails.show', [$customer, 0])); ?>"
     data-detach-url="<?php echo e(route('agency.customers.mails.detach', [$customer, 0])); ?>">

    <div class="pfx-top">
        <span class="pfx-top-t"><i class="fas fa-envelopes-bulk"></i> Yazışmalar</span>
        <span class="flw-stat"><?php echo e($mails->count()); ?> ileti</span>
        <?php if($mails->where('is_seen', false)->where('folder.type', 'inbox')->count()): ?>
            <span class="flw-stat danger"><?php echo e($mails->where('is_seen', false)->where('folder.type', 'inbox')->count()); ?> okunmamış</span>
        <?php endif; ?>
        <button type="button" class="pfx-chip" onclick="qvMailCompose(this)">
            <i class="fas fa-pen-to-square"></i> Yeni E-posta
        </button>

        <?php if($mails->isNotEmpty()): ?>
            
            <div class="mlx-xp">
                <button type="button" class="pfx-chip" onclick="qvMailExportMenu(this)" title="Yazışmaları dışa aktar">
                    <i class="fas fa-file-export"></i> Dışa Aktar
                </button>
                <form class="mlx-xp-menu" method="POST" action="<?php echo e(route('agency.mail.export.run')); ?>" target="_blank" hidden>
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="scope" value="customer">
                    <input type="hidden" name="customer_id" value="<?php echo e($customer->id); ?>">
                    <input type="hidden" name="format" value="">
                    <div class="mlx-xp-h">Biçim seçin</div>
                    <?php $__currentLoopData = $mailFormats; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $meta): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <button type="submit" class="mlx-xp-o" value="<?php echo e($key); ?>" onclick="this.form.format.value='<?php echo e($key); ?>'">
                            <i class="fas <?php echo e($meta['icon']); ?>"></i>
                            <span><b><?php echo e($meta['label']); ?></b><?php echo e($meta['note']); ?></span>
                        </button>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </form>
            </div>
        <?php endif; ?>
    </div>

    <?php if($mails->isEmpty()): ?>
        <div class="flw-empty">
            <i class="fas fa-envelope-open-text"></i>
            <b>Henüz yazışma yok</b>
            <span>
                <?php if($mailAccounts->isEmpty()): ?>
                    Önce Mail modülünden bir e-posta hesabı bağlayın.
                <?php else: ?>
                    Bu müşterinin adresine gönderilen ve ondan gelen postalar burada toplanır.
                <?php endif; ?>
            </span>
        </div>
    <?php else: ?>
        <div class="mlx-filters">
            <button type="button" class="mlx-chip on" data-mail-filter="">Tümü <b><?php echo e($mails->count()); ?></b></button>
            <button type="button" class="mlx-chip" data-mail-filter="inbound">Gelen <b><?php echo e($mails->filter(fn($m) => $m->direction() === 'inbound')->count()); ?></b></button>
            <button type="button" class="mlx-chip" data-mail-filter="outbound">Giden <b><?php echo e($mails->filter(fn($m) => $m->direction() === 'outbound')->count()); ?></b></button>
            <button type="button" class="mlx-chip" data-mail-filter="attachments"><i class="fas fa-paperclip"></i> Ekli <b><?php echo e($mails->where('has_attachments', true)->count()); ?></b></button>
        </div>

        <div class="mlx-list">
            <?php $__currentLoopData = $mails; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $mail): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <?php
                    $dir = $mail->direction();
                    $party = $mail->counterparty();
                    $isUnread = ! $mail->is_seen && $dir === 'inbound';
                ?>
                <div class="mlx-i <?php echo e($isUnread ? 'unread' : ''); ?>"
                     data-mail-id="<?php echo e($mail->id); ?>"
                     data-mail-dir="<?php echo e($dir); ?>"
                     data-mail-att="<?php echo e($mail->has_attachments ? '1' : '0'); ?>"
                     style="--fc: <?php echo e($mailColor($mail)); ?>;">

                    <div class="mlx-h" onclick="qvMailToggle(this)">
                        <span class="mlx-ic"><i class="fas <?php echo e($mailIcon($mail)); ?>"></i></span>

                        <div class="mlx-t">
                            <div class="mlx-s"><?php echo e($mail->subject ?: '(konu yok)'); ?></div>
                            <p class="mlx-p">
                                <?php echo e($dir === 'outbound' ? 'Kime:' : 'Kimden:'); ?>

                                <?php echo e($party['name']); ?><?php echo e($party['email'] && $party['email'] !== $party['name'] ? ' · '.$party['email'] : ''); ?>

                            </p>
                            <?php if($mail->snippet): ?>
                                <p class="mlx-sn"><?php echo e($mail->snippet); ?></p>
                            <?php endif; ?>
                        </div>

                        <div class="mlx-r">
                            <span class="mlx-time" title="<?php echo e(optional($mail->date_at)->translatedFormat('d F Y, H:i')); ?>">
                                <?php echo e(optional($mail->date_at)->diffForHumans(short: true)); ?>

                            </span>
                            <span class="mlx-tags">
                                <?php if($mail->has_attachments): ?>
                                    <span class="mlx-tag"><i class="fas fa-paperclip"></i></span>
                                <?php endif; ?>
                                <span class="mlx-tag acc" style="--acc: <?php echo e($mail->account?->color ?: '#2563eb'); ?>"><?php echo e($mail->account?->name); ?></span>
                            </span>
                        </div>
                    </div>

                    <div class="mlx-body"><div class="mlx-load"><i class="fas fa-spinner fa-spin"></i> Yükleniyor…</div></div>
                </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </div>
    <?php endif; ?>
</div>

<?php echo $__env->make('components.quick-view.mail-ui', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

<?php if (! $__env->hasRenderedOnce('7c0284de-cbf0-4fe0-8c06-d1fb7ac51e3f')): $__env->markAsRenderedOnce('7c0284de-cbf0-4fe0-8c06-d1fb7ac51e3f'); ?>
<script>
/**
 * E-posta satırını açar/kapatır. Gövde ilk açılışta sunucudan istenir ve
 * satırda saklanır; ikinci açılışta ağ isteği yapılmaz.
 */
function qvMailToggle(head) {
    const item = head.closest('.mlx-i');
    const root = head.closest('[data-mail-root]');
    if (!item || !root) return;

    if (item.classList.contains('open')) {
        item.classList.remove('open');
        return;
    }

    // Aynı anda tek okuyucu açık kalsın — liste okunur kalır
    root.querySelectorAll('.mlx-i.open').forEach(n => n.classList.remove('open'));
    item.classList.add('open');
    item.classList.remove('unread');

    const box = item.querySelector('.mlx-body');
    if (item.dataset.loaded === '1') return;

    const url = root.dataset.showUrl.replace(/\/0$/, '/' + item.dataset.mailId);

    fetch(url, { headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' } })
        .then(r => r.ok ? r.json() : Promise.reject(new Error('İleti alınamadı')))
        .then(d => {
            item.dataset.loaded = '1';
            item.dataset.reply = JSON.stringify(d.reply || {});
            box.innerHTML = qvMailFrame(d);
            qvMailMountBody(box.querySelector('.mlx-html'), d.body_html);
        })
        .catch(e => {
            box.innerHTML = '<div class="mlx-err"><i class="fas fa-triangle-exclamation"></i> ' + e.message + '</div>';
        });
}

/**
 * İleti gövdesini yalıtılmış bir iframe içine yerleştirir.
 *
 * Gövde güvenilmez içeriktir: sunucudaki temizleyici (MailHtmlSanitizer)
 * script ve olay özniteliklerini söker, burası ikinci katmanı ekler. Çerçeveye
 * allow-same-origin verilmez — içindeki hiçbir şey panelin DOM'una, çerezine
 * ya da depolamasına erişemez. allow-scripts yalnızca yüksekliği bildiren
 * küçük betik içindir ve ayrıksı (opaque) bir kaynakta çalışır.
 */
function qvMailMountBody(host, html) {
    if (!host) return;

    const css = 'html,body{margin:0;padding:0;background:transparent}'
        + 'body{font:13px/1.6 -apple-system,"Segoe UI",Inter,Roboto,sans-serif;color:#1f2937;'
        + 'word-break:break-word;overflow-x:auto}'
        + 'img{max-width:100%;height:auto}table{max-width:100%}a{color:#2563eb}'
        + '.mail-plain{white-space:pre-wrap;font-family:inherit}'
        + '.mail-blocked-img{min-width:18px;min-height:18px;background:#f1f5f9;'
        + 'border:1px dashed #cbd5e1;border-radius:4px}';

    const js = '(function(){var last=0;function r(){'
        + 'var h=Math.max(document.documentElement.scrollHeight,document.body?document.body.scrollHeight:0);'
        + 'if(h!==last){last=h;parent.postMessage({source:"qv-mail-frame",height:h},"*");}}'
        + 'r();window.addEventListener("load",r);'
        + 'if(window.ResizeObserver){new ResizeObserver(r).observe(document.documentElement);}'
        + 'setTimeout(r,300);setTimeout(r,1200);})();';

    const frame = document.createElement('iframe');
    frame.className = 'mlx-frame-body';
    frame.setAttribute('sandbox', 'allow-scripts allow-popups allow-popups-to-escape-sandbox');
    frame.setAttribute('referrerpolicy', 'no-referrer');
    frame.setAttribute('title', 'İleti içeriği');

    host.textContent = '';
    host.appendChild(frame);

    frame.srcdoc = '<!doctype html><html lang="tr"><head><meta charset="utf-8">'
        + '<meta name="referrer" content="no-referrer"><base target="_blank">'
        + '<style>' + css + '</style></head><body>'
        + (html || '<span style="color:#b6c2d2">(boş ileti)</span>')
        + '<' + 'script>' + js + '<' + '/script></body></html>';
}

// Çerçeveden gelen yükseklik bildirimi — gönderen doğrulanır
if (!window.__qvMailFrameBound) {
window.__qvMailFrameBound = true;
window.addEventListener('message', function (event) {
    const data = event.data;
    if (!data || data.source !== 'qv-mail-frame' || typeof data.height !== 'number') return;

    document.querySelectorAll('iframe.mlx-frame-body').forEach(function (frame) {
        if (frame.contentWindow === event.source) {
            frame.style.height = Math.max(40, Math.min(20000, data.height)) + 'px';
        }
    });
});
}

/** Okuyucu çerçevesi: başlıklar, gövde, ekler ve eylemler. */
function qvMailFrame(d) {
    const esc = (s) => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));

    let head = '<div class="mlx-frame-h">'
        + '<span><b>Kimden</b>' + esc(d.from.name || d.from.email) + '</span>'
        + (d.to ? '<span><b>Kime</b>' + esc(d.to) + '</span>' : '')
        + (d.cc ? '<span><b>Bilgi</b>' + esc(d.cc) + '</span>' : '')
        + '<span><b>Tarih</b>' + esc(d.date_full) + '</span>'
        + '</div>';

    let atts = '';
    if (d.attachments && d.attachments.length) {
        atts = '<div class="mlx-atts">' + d.attachments.map(a =>
            '<a class="mlx-att" href="' + esc(a.download_url) + '" title="' + esc(a.filename) + '">'
            + '<i class="fas ' + esc(a.icon) + '"></i><span>' + esc(a.filename) + '</span><b>' + esc(a.size) + '</b></a>'
        ).join('') + '</div>';
    }

    return '<div class="mlx-frame">' + head
        + (d.error ? '<div class="mlx-err">' + esc(d.error) + '</div>' : '')
        + '<div class="mlx-html"></div>'
        + atts + '</div>'
        + '<div class="mlx-acts">'
        + '<button type="button" class="mlx-act" onclick="qvMailReply(this)"><i class="fas fa-reply"></i> Yanıtla</button>'
        + '<button type="button" class="mlx-act danger" onclick="qvMailDetach(this)"><i class="fas fa-link-slash"></i> Karttan çıkar</button>'
        + '</div>';
}

/** Dışa aktarma biçim menüsünü açar/kapatır. */
function qvMailExportMenu(btn) {
    const menu = btn.parentNode.querySelector('.mlx-xp-menu');
    if (!menu) return;

    const open = menu.hidden;
    document.querySelectorAll('.mlx-xp-menu').forEach(m => { m.hidden = true; });
    menu.hidden = !open;

    if (open) {
        // Dışarı tıklanınca kapansın — tek seferlik dinleyici
        setTimeout(() => document.addEventListener('click', function close(e) {
            if (!menu.parentNode.contains(e.target)) {
                menu.hidden = true;
                document.removeEventListener('click', close);
            }
        }), 0);
    }
}

/** Yanıt: özet sekmesindeki yazma kutusunu e-posta kipinde doldurur. */
function qvMailReply(btn) {
    const item = btn.closest('.mlx-i');
    let reply = {};
    try { reply = JSON.parse(item.dataset.reply || '{}'); } catch (e) {}
    qvMailCompose(btn, reply);
}

/** Yanlış eşleşen postayı karttan koparır. */
function qvMailDetach(btn) {
    const item = btn.closest('.mlx-i');
    const root = btn.closest('[data-mail-root]');
    const url = root.dataset.detachUrl.replace(/\/0$/, '/' + item.dataset.mailId);

    const go = () => fetch(url, {
        method: 'DELETE',
        headers: {
            'Accept': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
        },
    })
    .then(r => r.json())
    .then(d => {
        if (d.success) {
            item.remove();
            if (typeof Swal !== 'undefined') {
                Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 1800 })
                    .fire({ icon: 'success', title: d.message });
            }
        }
    });

    if (typeof Swal === 'undefined') return go();

    Swal.fire({
        title: 'Yazışmayı çıkar?',
        text: 'Posta silinmez, yalnızca bu müşteri kartıyla bağı kaldırılır.',
        icon: 'question', showCancelButton: true,
        confirmButtonColor: '#dc2626', confirmButtonText: 'Çıkar', cancelButtonText: 'Vazgeç',
    }).then(r => { if (r.isConfirmed) go(); });
}

/* Süzgeç çipleri — gelen / giden / ekli.
   Kart her açılışta yeniden çizildiği için dinleyici bir kez bağlanır. */
if (!window.__qvMailFilterBound) {
window.__qvMailFilterBound = true;
document.addEventListener('click', function (e) {
    const chip = e.target.closest('.mlx-chip');
    if (!chip) return;

    const root = chip.closest('[data-mail-root]');
    if (!root) return;

    root.querySelectorAll('.mlx-chip').forEach(c => c.classList.remove('on'));
    chip.classList.add('on');

    const f = chip.dataset.mailFilter;
    root.querySelectorAll('.mlx-i').forEach(function (item) {
        const ok = !f
            || (f === 'attachments' ? item.dataset.mailAtt === '1' : item.dataset.mailDir === f);
        item.classList.toggle('hide', !ok);
    });
});
}
</script>
<?php endif; ?>
<?php /**PATH C:\xampp\htdocs\acente\resources\views/agency/customers/partials/qv-mails.blade.php ENDPATH**/ ?>