<?php $__env->startSection('title', 'Görev Atama Kuralları'); ?>
<?php $__env->startSection('page_title', 'Görev Atama Kuralları'); ?>

<?php
    $breadcrumbs = [
        ['title' => 'Dashboard', 'url' => route('agency.dashboard')],
        ['title' => 'Personel ve Yetki', 'url' => '#'],
        ['title' => 'Görev Atama Kuralları', 'url' => ''],
    ];

    $groupIcons = ['operasyon' => 'fa-route', 'satis' => 'fa-cart-shopping', 'odeme' => 'fa-credit-card', 'takip' => 'fa-bell'];
    $groupColors = ['operasyon' => '#6366f1', 'satis' => '#10b981', 'odeme' => '#f59e0b', 'takip' => '#f43f5e'];
?>

<?php $__env->startSection('content'); ?>
<div class="tr-page">

    
    <div class="tr-intro">
        <div class="tr-intro-ico"><i class="fas fa-robot"></i></div>
        <div class="tr-intro-body">
            <h5>Otomatik Görev Atama Kuralları</h5>
            <p>Sistemde gerçekleşen olaylar (kesin kalkış, yeni rezervasyon, ödeme gecikmesi vb.) için otomatik görev oluşturulmasını buradan yapılandırırsınız.
               Bir kuralı açıp hedef <b>rolleri ve/veya kullanıcıları</b> seçtiğinizde, olay gerçekleştiğinde görev bu kişilere otomatik atanır.</p>
            <div class="tr-note">
                <i class="fas fa-circle-info"></i>
                <span><b>Zamanlanmış</b> etiketli tetikleyiciler periyodik taramayla çalışır — sunucuda zamanlayıcının
                (<code>php artisan schedule:work</code> veya cron) aktif olması gerekir. <b>Anlık</b> tetikleyiciler olay anında çalışır.</span>
            </div>
        </div>
    </div>

    <?php $__currentLoopData = $groups; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $groupKey => $group): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
        <?php if(empty($group['triggers'])) continue; ?>
        <section class="tr-group">
            <header class="tr-group-head" style="--gc: <?php echo e($groupColors[$groupKey] ?? '#64748b'); ?>;">
                <i class="fas <?php echo e($groupIcons[$groupKey] ?? 'fa-folder'); ?>"></i>
                <h6><?php echo e($group['label']); ?></h6>
                <span><?php echo e(count($group['triggers'])); ?> tetikleyici</span>
            </header>

            <div class="tr-rows">
                <?php $__currentLoopData = $group['triggers']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $def): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <?php
                        $rule = $rules->get($key);
                        $enabled = (bool) ($rule->is_enabled ?? false);
                        $ruleRoleIds = collect($rule->role_ids ?? []);
                        $ruleUserIds = collect($rule->user_ids ?? []);
                    ?>

                    <div class="tr-row <?php echo e($enabled ? 'on' : ''); ?>" data-trigger="<?php echo e($key); ?>" data-url="<?php echo e(route('agency.staff-management.task-rules.update', $key)); ?>">
                        <div class="tr-row-head" onclick="trToggleExpand(this)">
                            <label class="tr-switch" onclick="event.stopPropagation()">
                                <input type="checkbox" class="tr-enabled" <?php echo e($enabled ? 'checked' : ''); ?>>
                                <span class="tr-switch-track"><span class="tr-switch-thumb"></span></span>
                            </label>

                            <div class="tr-row-info">
                                <div class="tr-row-title">
                                    <?php echo e($def['label']); ?>

                                    <span class="tr-kind <?php echo e($def['kind']); ?>">
                                        <i class="fas <?php echo e($def['kind'] === 'event' ? 'fa-bolt' : 'fa-clock-rotate-left'); ?>"></i>
                                        <?php echo e($def['kind'] === 'event' ? 'Anlık' : 'Zamanlanmış'); ?>

                                    </span>
                                </div>
                                <div class="tr-row-desc"><?php echo e($def['description']); ?></div>
                            </div>

                            <div class="tr-row-summary">
                                <span class="tr-target-count" data-role="summary">
                                    <?php if($enabled): ?>
                                        <?php echo e($ruleRoleIds->count()); ?> rol · <?php echo e($ruleUserIds->count()); ?> kullanıcı
                                    <?php else: ?>
                                        Kapalı
                                    <?php endif; ?>
                                </span>
                                <i class="fas fa-chevron-down tr-chev"></i>
                            </div>
                        </div>

                        <div class="tr-row-config">
                            <?php if(!empty($def['when'])): ?>
                                <div class="tr-when">
                                    <i class="fas fa-clock"></i>
                                    <div>
                                        <b>Ne zaman çalışır?</b>
                                        <span><?php echo e($def['when']); ?></span>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <div class="tr-cfg-grid">
                                <div class="tr-cfg-block">
                                    <label>Hedef Roller</label>
                                    <div class="tr-chips">
                                        <?php $__currentLoopData = $roles; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $role): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <?php $memberCount = (int) ($roleMemberCounts[$role->id] ?? 0); ?>
                                            <label class="tr-chip" title="<?php echo e($memberCount); ?> kullanıcı bu role sahip">
                                                <input type="checkbox" class="tr-role" value="<?php echo e($role->id); ?>" data-members="<?php echo e($memberCount); ?>" <?php echo e($ruleRoleIds->contains($role->id) ? 'checked' : ''); ?>>
                                                <span><i class="fas fa-key"></i> <?php echo e($role->ui_name ?? $role->name); ?> <em class="tr-chip-count <?php echo e($memberCount === 0 ? 'zero' : ''); ?>"><?php echo e($memberCount); ?></em></span>
                                            </label>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </div>
                                </div>

                                <div class="tr-cfg-block">
                                    <label>Hedef Kullanıcılar</label>
                                    <div class="tr-chips">
                                        <?php $__currentLoopData = $staff; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $user): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <label class="tr-chip">
                                                <input type="checkbox" class="tr-user" value="<?php echo e($user->id); ?>" <?php echo e($ruleUserIds->contains($user->id) ? 'checked' : ''); ?>>
                                                <span><i class="fas fa-user"></i> <?php echo e($user->full_name); ?></span>
                                            </label>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </div>
                                </div>
                            </div>

                            
                            <div class="tr-cfg-block tr-tpl-block">
                                <label>Görev Başlığı Şablonu <small>(boş bırakılırsa varsayılan kullanılır)</small></label>
                                <div class="tr-tpl-wrap">
                                    <textarea class="tr-input tr-title-tpl" rows="2" maxlength="500"
                                              placeholder="<?php echo e($def['title_template']); ?>"><?php echo e($rule->title_template ?? ''); ?></textarea>
                                    <button type="button" class="tr-varbtn" data-tpl-target="title" onclick="trOpenVarModal(this)">
                                        <i class="fas fa-wand-magic-sparkles"></i> Alan Ekle
                                    </button>
                                </div>
                            </div>

                            <div class="tr-cfg-block tr-tpl-block">
                                <label>Görev Açıklaması Şablonu <small>(boş bırakılırsa varsayılan açıklama kullanılır)</small></label>
                                <div class="tr-tpl-wrap">
                                    <div class="tr-desc-editwrap">
                                        <div class="tr-desc-editor" data-placeholder="<?php echo e($def['description']); ?>"></div>
                                        <textarea class="tr-desc-tpl d-none"><?php echo e($rule->description_template ?? ''); ?></textarea>
                                    </div>
                                    <button type="button" class="tr-varbtn" data-tpl-target="desc" onclick="trOpenVarModal(this)">
                                        <i class="fas fa-wand-magic-sparkles"></i> Alan Ekle
                                    </button>
                                </div>
                            </div>

                            <div class="tr-cfg-grid three">
                                <div class="tr-cfg-block">
                                    <label>Atama Şekli</label>
                                    <select class="tr-input tr-mode">
                                        <option value="shared" <?php echo e(($rule->assignment_mode ?? 'shared') === 'shared' ? 'selected' : ''); ?>>Tek görev — tüm hedeflere ortak atama</option>
                                        <option value="individual" <?php echo e(($rule->assignment_mode ?? '') === 'individual' ? 'selected' : ''); ?>>Kişi başına ayrı görev</option>
                                    </select>
                                </div>
                                <div class="tr-cfg-block">
                                    <label>Öncelik <small>(varsayılan: <?php echo e($priorities[$def['default_priority']]['label']); ?>)</small></label>
                                    <select class="tr-input tr-priority">
                                        <option value="">Varsayılan</option>
                                        <?php $__currentLoopData = $priorities; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $pKey => $pMeta): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($pKey); ?>" <?php echo e(($rule->priority_override ?? '') === $pKey ? 'selected' : ''); ?>><?php echo e($pMeta['label']); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                                <div class="tr-cfg-block">
                                    <label>Termin <small>(saat, varsayılan: <?php echo e($def['due_offset_hours']); ?>)</small></label>
                                    <input type="number" class="tr-input tr-due" min="1" max="720" placeholder="<?php echo e($def['due_offset_hours']); ?>"
                                           value="<?php echo e($rule->due_offset_hours_override ?? ''); ?>">
                                </div>
                            </div>

                            <div class="tr-cfg-foot">
                                <span class="tr-cfg-hint">
                                    <i class="fas fa-circle-info"></i>
                                    "Tek görev" modunda bir kişi tamamlayınca görev herkes için kapanır; "kişi başına" modda her hedef kullanıcıya ayrı görev düşer.
                                </span>
                                <button type="button" class="tr-save" onclick="trSaveRule(this)">
                                    <i class="fas fa-check"></i> Kaydet
                                </button>
                            </div>
                        </div>
                    </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </div>
        </section>
    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
</div>


<div class="modal fade" id="trVarModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content trv">
            <div class="trv-top">
                <div class="trv-head">
                    <div class="trv-head-ico"><i class="fas fa-wand-magic-sparkles"></i></div>
                    <div class="trv-head-tx">
                        <h5>Değişken Kütüphanesi</h5>
                        <p>Seçtiğiniz alan imleç konumuna eklenir; görev oluşturulurken ilişkili kayıttan <strong>otomatik doldurulur</strong>.</p>
                    </div>
                    <button type="button" class="trv-x" data-bs-dismiss="modal" aria-label="Kapat"><i class="fas fa-xmark"></i></button>
                </div>
                <div class="trv-search">
                    <i class="fas fa-magnifying-glass"></i>
                    <input type="text" id="trvSearch" placeholder="Değişken ara… (örn. telefon, tur adı, tarih)" autocomplete="off">
                    <span class="trv-kbd"><i class="fas fa-keyboard me-1"></i>Ctrl + tıkla → pencere açık kalır</span>
                </div>
            </div>
            <div class="trv-body">
                <aside class="trv-rail" id="trvRail"></aside>
                <div class="trv-grid-wrap">
                    <div class="trv-grid" id="trvGrid"></div>
                    <div class="trv-empty" id="trvEmpty" style="display:none">
                        <i class="fas fa-magnifying-glass-minus"></i>
                        <p>Aramanızla eşleşen değişken yok.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('styles'); ?>
<style>
    .tr-page { max-width: 1080px; }

    .tr-intro {
        display: flex; gap: 1.1rem; background: linear-gradient(135deg, #fffbeb, #fff);
        border: 1px solid #fde68a; border-radius: 18px; padding: 1.35rem 1.5rem; margin-bottom: 1.4rem;
    }
    .tr-intro-ico {
        width: 52px; height: 52px; border-radius: 15px; flex-shrink: 0;
        background: linear-gradient(135deg, #f59e0b, #d97706); color: #fff;
        display: flex; align-items: center; justify-content: center; font-size: 1.3rem;
        box-shadow: 0 10px 22px -8px rgba(217,119,6,.55);
    }
    .tr-intro-body h5 { font-weight: 800; color: #0f172a; letter-spacing: -0.02em; margin-bottom: .3rem; }
    .tr-intro-body p { font-size: .85rem; color: #64748b; font-weight: 500; margin-bottom: .7rem; max-width: 760px; }
    .tr-note {
        display: flex; align-items: flex-start; gap: .5rem; font-size: .78rem; color: #92400e; font-weight: 600;
        background: #fef3c7; border-radius: 10px; padding: .55rem .8rem; max-width: 760px;
    }
    .tr-note i { margin-top: .15rem; }
    .tr-note code { background: #fff; border-radius: 5px; padding: .05rem .35rem; color: #b45309; font-size: .74rem; }

    .tr-group { margin-bottom: 1.5rem; }
    .tr-group-head { display: flex; align-items: center; gap: .6rem; margin-bottom: .6rem; padding: 0 .25rem; }
    .tr-group-head i { width: 30px; height: 30px; border-radius: 9px; background: color-mix(in srgb, var(--gc) 12%, #fff); color: var(--gc); display: inline-flex; align-items: center; justify-content: center; font-size: .82rem; }
    .tr-group-head h6 { margin: 0; font-size: .95rem; font-weight: 800; color: #0f172a; letter-spacing: -0.01em; }
    .tr-group-head span { margin-left: auto; font-size: .72rem; font-weight: 700; color: #94a3b8; }

    .tr-rows { display: flex; flex-direction: column; gap: .55rem; }
    .tr-row { background: #fff; border: 1px solid #e9edf3; border-radius: 14px; overflow: hidden; transition: border-color .2s ease, box-shadow .2s ease; }
    .tr-row.on { border-color: #fde68a; box-shadow: 0 2px 12px -6px rgba(217,119,6,.18); }
    .tr-row.expanded { box-shadow: 0 12px 30px -12px rgba(15,23,42,.18); }

    .tr-row-head { display: flex; align-items: center; gap: 1rem; padding: .85rem 1.1rem; cursor: pointer; }
    .tr-row-info { flex: 1; min-width: 0; }
    .tr-row-title { font-size: .88rem; font-weight: 800; color: #1e293b; display: flex; align-items: center; gap: .55rem; flex-wrap: wrap; }
    .tr-row-desc { font-size: .76rem; color: #94a3b8; font-weight: 600; margin-top: .15rem; }
    .tr-kind { display: inline-flex; align-items: center; gap: .3rem; font-size: .62rem; font-weight: 800; padding: .14rem .5rem; border-radius: 999px; text-transform: uppercase; letter-spacing: .03em; }
    .tr-kind.event { background: #ecfdf5; color: #059669; }
    .tr-kind.scheduled { background: #eff6ff; color: #2563eb; }

    .tr-row-summary { display: flex; align-items: center; gap: .7rem; flex-shrink: 0; }
    .tr-target-count { font-size: .74rem; font-weight: 800; color: #94a3b8; }
    .tr-row.on .tr-target-count { color: #b45309; }
    .tr-chev { color: #cbd5e1; font-size: .74rem; transition: transform .25s ease; }
    .tr-row.expanded .tr-chev { transform: rotate(180deg); }

    /* Anahtar (switch) */
    .tr-switch { margin: 0; cursor: pointer; flex-shrink: 0; }
    .tr-switch input { display: none; }
    .tr-switch-track {
        display: inline-block; width: 42px; height: 24px; border-radius: 999px; background: #e2e8f0;
        position: relative; transition: background .2s ease;
    }
    .tr-switch-thumb {
        position: absolute; top: 3px; left: 3px; width: 18px; height: 18px; border-radius: 50%;
        background: #fff; box-shadow: 0 1px 4px rgba(15,23,42,.25); transition: transform .2s ease;
    }
    .tr-switch input:checked + .tr-switch-track { background: linear-gradient(135deg, #f59e0b, #d97706); }
    .tr-switch input:checked + .tr-switch-track .tr-switch-thumb { transform: translateX(18px); }

    /* Genişleyen yapılandırma */
    .tr-row-config { display: none; border-top: 1px dashed #eef1f6; padding: 1rem 1.1rem 1.1rem; background: #fcfdfe; }
    .tr-row.expanded .tr-row-config { display: block; animation: trSlide .25s ease; }
    @keyframes trSlide { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: translateY(0); } }

    .tr-cfg-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1rem; }
    .tr-cfg-grid.three { grid-template-columns: 1.4fr 1fr 1fr; }
    .tr-cfg-block label { display: block; font-size: .68rem; font-weight: 800; color: #64748b; text-transform: uppercase; letter-spacing: .05em; margin-bottom: .4rem; }
    .tr-cfg-block label small { text-transform: none; letter-spacing: 0; color: #b6c2d2; font-weight: 700; }
    .tr-input { width: 100%; border: 1px solid #e2e8f0; border-radius: 10px; padding: .45rem .65rem; font-size: .8rem; font-weight: 600; color: #334155; background: #fff; }
    .tr-input:focus { outline: none; border-color: #fbbf24; box-shadow: 0 0 0 3px rgba(251,191,36,.18); }

    .tr-chips { display: flex; flex-wrap: wrap; gap: .35rem; max-height: 120px; overflow-y: auto; padding: .1rem; }
    .tr-chip { margin: 0; cursor: pointer; }
    .tr-chip input { display: none; }
    .tr-chip span {
        display: inline-flex; align-items: center; gap: .35rem; font-size: .74rem; font-weight: 700; color: #64748b;
        border: 1.5px solid #e2e8f0; border-radius: 999px; padding: .26rem .65rem; transition: all .15s ease;
    }
    .tr-chip span i { font-size: .62rem; opacity: .6; }
    .tr-chip input:checked + span { color: #92400e; border-color: #d97706; background: #fffbeb; }
    .tr-chip input:checked + span i { opacity: 1; color: #d97706; }
    .tr-chip-count {
        font-style: normal; font-size: .62rem; font-weight: 800; line-height: 1;
        background: #eef1f6; color: #64748b; border-radius: 999px; padding: .12rem .4rem;
    }
    .tr-chip-count.zero { background: #fee2e2; color: #dc2626; }
    .tr-chip input:checked + span .tr-chip-count { background: #fde68a; color: #92400e; }
    .tr-chip input:checked + span .tr-chip-count.zero { background: #fee2e2; color: #dc2626; }

    .tr-cfg-foot { display: flex; align-items: center; justify-content: space-between; gap: 1rem; }
    .tr-cfg-hint { font-size: .72rem; color: #94a3b8; font-weight: 600; max-width: 620px; }
    .tr-cfg-hint i { margin-right: .25rem; }
    .tr-save {
        display: inline-flex; align-items: center; gap: .45rem; border: none; cursor: pointer; flex-shrink: 0;
        background: linear-gradient(135deg, #f59e0b, #d97706); color: #fff;
        font-weight: 800; font-size: .8rem; padding: .5rem 1rem; border-radius: 10px;
        box-shadow: 0 6px 14px -6px rgba(217,119,6,.5); transition: all .15s ease;
    }
    .tr-save:hover { transform: translateY(-1px); filter: brightness(1.05); }
    .tr-save:disabled { opacity: .6; }

    /* "Ne zaman çalışır?" bilgi şeridi */
    .tr-when {
        display: flex; gap: .65rem; align-items: flex-start;
        background: #eff6ff; border: 1px solid #bfdbfe; border-radius: 11px;
        padding: .65rem .85rem; margin-bottom: 1rem;
    }
    .tr-when > i { color: #2563eb; font-size: .82rem; margin-top: .18rem; flex-shrink: 0; }
    .tr-when b { display: block; font-size: .72rem; font-weight: 800; color: #1d4ed8; text-transform: uppercase; letter-spacing: .04em; margin-bottom: .15rem; }
    .tr-when span { font-size: .78rem; font-weight: 600; color: #334155; line-height: 1.45; }

    /* Şablon alanları */
    .tr-tpl-block { margin-bottom: 1rem; }
    .tr-tpl-wrap { display: flex; gap: .5rem; align-items: flex-start; }
    .tr-tpl-wrap .tr-input { flex: 1; font-family: 'SFMono-Regular', Consolas, monospace; font-size: .76rem; }
    .tr-tpl-wrap .tr-title-tpl { resize: vertical; min-height: 58px; }

    /* Açıklama: Quill zengin metin editörü */
    .tr-desc-editwrap { flex: 1; min-width: 0; }
    .tr-desc-editwrap .ql-toolbar { border-radius: 10px 10px 0 0; border-color: #e2e8f0; background: #fafbfc; }
    .tr-desc-editwrap .ql-container { border-radius: 0 0 10px 10px; border-color: #e2e8f0; font-size: .8rem; background: #fff; }
    .tr-desc-editwrap .ql-editor { min-height: 96px; }
    .tr-desc-editwrap .ql-editor.ql-blank::before { color: #b6c2d2; font-style: normal; font-size: .76rem; }
    .tr-varbtn {
        display: inline-flex; align-items: center; gap: .4rem; flex-shrink: 0; cursor: pointer;
        border: 1px solid #fde68a; background: #fffbeb; color: #92400e;
        font-size: .72rem; font-weight: 800; padding: .45rem .7rem; border-radius: 9px; transition: all .15s ease;
    }
    .tr-varbtn:hover { background: #fef3c7; border-color: #fcd34d; transform: translateY(-1px); }

    /* Değişken kütüphanesi modalı */
    .trv { border: none; border-radius: 18px; overflow: hidden; }
    .trv-top { border-bottom: 1px solid #f1f5f9; }
    .trv-head { display: flex; align-items: flex-start; gap: .9rem; padding: 1.2rem 1.4rem .9rem; }
    .trv-head-ico {
        width: 44px; height: 44px; border-radius: 13px; flex-shrink: 0;
        background: linear-gradient(135deg, #f59e0b, #d97706); color: #fff;
        display: flex; align-items: center; justify-content: center; font-size: 1.05rem;
        box-shadow: 0 8px 18px -8px rgba(217,119,6,.6);
    }
    .trv-head-tx h5 { margin: 0 0 .15rem; font-weight: 800; color: #0f172a; letter-spacing: -0.02em; }
    .trv-head-tx p { margin: 0; font-size: .78rem; color: #94a3b8; font-weight: 600; }
    .trv-x { margin-left: auto; border: none; background: #f1f5f9; color: #64748b; width: 32px; height: 32px; border-radius: 9px; cursor: pointer; }
    .trv-x:hover { background: #fee2e2; color: #dc2626; }
    .trv-search { position: relative; padding: 0 1.4rem .9rem; display: flex; align-items: center; gap: .75rem; }
    .trv-search > i { position: absolute; left: 2.15rem; color: #94a3b8; font-size: .78rem; }
    .trv-search input {
        flex: 1; border: 1px solid #e2e8f0; border-radius: 10px; padding: .5rem .75rem .5rem 2.2rem; font-size: .82rem;
    }
    .trv-search input:focus { outline: none; border-color: #fbbf24; box-shadow: 0 0 0 3px rgba(251,191,36,.18); }
    .trv-kbd { font-size: .68rem; font-weight: 700; color: #b6c2d2; white-space: nowrap; }

    .trv-body { display: grid; grid-template-columns: 190px 1fr; max-height: 55vh; }
    .trv-rail { border-right: 1px solid #f1f5f9; padding: .7rem .5rem; overflow-y: auto; display: flex; flex-direction: column; gap: .2rem; background: #fcfdfe; }
    .trv-cat {
        display: flex; align-items: center; gap: .5rem; width: 100%; text-align: left; cursor: pointer;
        border: none; background: transparent; color: #64748b; font-size: .76rem; font-weight: 700;
        padding: .42rem .6rem; border-radius: 9px; transition: all .13s ease;
    }
    .trv-cat i { width: 16px; text-align: center; font-size: .7rem; color: #94a3b8; }
    .trv-cat b { margin-left: auto; font-size: .64rem; background: #eef1f6; color: #64748b; border-radius: 999px; padding: .1rem .45rem; }
    .trv-cat:hover { background: #f1f5f9; color: #1e293b; }
    .trv-cat.active { background: #fffbeb; color: #92400e; }
    .trv-cat.active i { color: #d97706; }
    .trv-cat.active b { background: #fde68a; color: #92400e; }

    .trv-grid-wrap { overflow-y: auto; padding: .8rem; }
    .trv-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: .5rem; }
    .trv-item {
        text-align: left; cursor: pointer; border: 1px solid #e9edf3; background: #fff; border-radius: 11px;
        padding: .6rem .7rem; transition: all .14s ease; display: flex; flex-direction: column; gap: .25rem;
    }
    .trv-item:hover { border-color: #fbbf24; background: #fffdf5; transform: translateY(-1px); box-shadow: 0 6px 14px -8px rgba(217,119,6,.35); }
    .trv-item-label { font-size: .76rem; font-weight: 800; color: #1e293b; }
    .trv-item-token { font-family: 'SFMono-Regular', Consolas, monospace; font-size: .68rem; color: #b45309; background: #fffbeb; border-radius: 6px; padding: .12rem .4rem; align-self: flex-start; }
    .trv-empty { text-align: center; padding: 2rem; color: #b6c2d2; }
    .trv-empty i { font-size: 1.4rem; margin-bottom: .4rem; }
    .trv-empty p { font-size: .8rem; font-weight: 700; margin: 0; }

    @media (max-width: 768px) {
        .tr-cfg-grid, .tr-cfg-grid.three { grid-template-columns: 1fr; }
        .tr-row-summary .tr-target-count { display: none; }
        .trv-body { grid-template-columns: 1fr; }
        .trv-rail { flex-direction: row; flex-wrap: wrap; border-right: none; border-bottom: 1px solid #f1f5f9; }
        .trv-grid { grid-template-columns: 1fr; }
    }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
    function trToggleExpand(headEl) {
        const row = headEl.closest('.tr-row');
        row.classList.toggle('expanded');
        if (row.classList.contains('expanded')) trInitDescEditor(row);
    }

    // Açıklama editörünü (Quill) satır ilk açıldığında başlat
    function trInitDescEditor(row) {
        const holder = row.querySelector('.tr-desc-editor');
        if (!holder || holder.__quill || !window.Quill) return;

        const q = new Quill(holder, {
            theme: 'snow',
            placeholder: holder.dataset.placeholder || '',
            modules: { toolbar: [['bold', 'italic', 'underline'], [{ list: 'ordered' }, { list: 'bullet' }], ['clean']] }
        });

        const initial = row.querySelector('.tr-desc-tpl').value;
        if (initial) q.clipboard.dangerouslyPasteHTML(initial);
        holder.__quill = q;
    }

    function trCollect(row) {
        // Açıklama: Quill başlatıldıysa HTML içeriği (boşsa null), değilse ham textarea
        const descHolder = row.querySelector('.tr-desc-editor');
        let descTpl;
        if (descHolder && descHolder.__quill) {
            const q = descHolder.__quill;
            descTpl = q.getText().trim() !== '' ? q.root.innerHTML : null;
        } else {
            descTpl = (row.querySelector('.tr-desc-tpl').value || '').trim() || null;
        }

        return {
            is_enabled: row.querySelector('.tr-enabled').checked,
            assignment_mode: row.querySelector('.tr-mode').value,
            title_template: (row.querySelector('.tr-title-tpl').value || '').trim() || null,
            description_template: descTpl,
            role_ids: [...row.querySelectorAll('.tr-role:checked')].map(i => parseInt(i.value, 10)),
            user_ids: [...row.querySelectorAll('.tr-user:checked')].map(i => parseInt(i.value, 10)),
            priority_override: row.querySelector('.tr-priority').value || null,
            due_offset_hours_override: row.querySelector('.tr-due').value ? parseInt(row.querySelector('.tr-due').value, 10) : null,
        };
    }

    function trToast(icon, msg) {
        appToast({ icon: icon, title: msg, timer: 3400 });
    }

    function trSave(row, btn = null) {
        const payload = trCollect(row);
        if (btn) btn.disabled = true;

        return fetch(row.dataset.url, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify(payload)
        })
        .then(r => { if (!r.ok) throw new Error(); return r.json(); })
        .then(data => {
            row.classList.toggle('on', payload.is_enabled);
            const summary = row.querySelector('[data-role="summary"]');
            if (payload.is_enabled) {
                summary.textContent = `${payload.role_ids.length} rol · ${payload.user_ids.length} kullanıcı`;
                const hasTargets = payload.role_ids.length > 0 || payload.user_ids.length > 0;

                if (data.resolved_user_count > 0) {
                    trToast('success', `Kaydedildi — ${data.resolved_user_count} kullanıcıya atanacak`);
                } else if (hasTargets) {
                    // Kural geçerli; seçilen rollerde şu an üye yok — rol atanınca görevler oluşmaya başlar
                    trToast('info', 'Kaydedildi — seçilen rollerde henüz kullanıcı yok. Personele bu rol atandığında görevler oluşmaya başlayacak.');
                } else {
                    trToast('warning', 'Kural açık ama hedef seçilmedi — en az bir rol veya kullanıcı seçin.');
                }
            } else {
                summary.textContent = 'Kapalı';
                trToast('success', 'Kural kapatıldı');
            }
        })
        .catch(() => trToast('error', 'Kaydedilemedi'))
        .finally(() => { if (btn) btn.disabled = false; });
    }

    function trSaveRule(btn) {
        trSave(btn.closest('.tr-row'), btn);
    }

    // Anahtar değişince otomatik kaydet; açılıyorsa yapılandırmayı da genişlet
    document.querySelectorAll('.tr-enabled').forEach(sw => {
        sw.addEventListener('change', function () {
            const row = this.closest('.tr-row');
            if (this.checked) { row.classList.add('expanded'); trInitDescEditor(row); }
            trSave(row);
        });
    });

    // ═══ Değişken Kütüphanesi ═══
    const TPL_CATALOGS = <?php echo json_encode($templateCatalogs); ?>;
    const TRV_CAT_ICONS = { 'Müşteri': 'fa-user', 'Satış': 'fa-cart-shopping', 'Tur / Kalkış': 'fa-route', 'Görev': 'fa-list-check', 'Tetikleyici': 'fa-bolt', 'Acente': 'fa-briefcase', 'Genel': 'fa-shapes' };
    const TOKEN_OPEN = '{' + '{', TOKEN_CLOSE = '}' + '}';
    let trvInput = null;   // token'ın ekleneceği input/textarea
    let trvItems = [];     // aktif tetikleyicinin değişkenleri
    let trvCat = '*';

    function trOpenVarModal(btn) {
        const row = btn.closest('.tr-row');
        if (btn.dataset.tplTarget === 'title') {
            trvInput = row.querySelector('.tr-title-tpl');
        } else {
            trInitDescEditor(row);
            trvInput = row.querySelector('.tr-desc-editor') || row.querySelector('.tr-desc-tpl');
        }
        trvItems = TPL_CATALOGS[row.dataset.trigger] || [];
        trvCat = '*';
        document.getElementById('trvSearch').value = '';
        trvRender();
        bootstrap.Modal.getOrCreateInstance(document.getElementById('trVarModal')).show();
    }

    function trvRender() {
        const rail = document.getElementById('trvRail');
        const grid = document.getElementById('trvGrid');
        const empty = document.getElementById('trvEmpty');
        const term = (document.getElementById('trvSearch').value || '').toLocaleLowerCase('tr');

        // Kategori rayı
        const cats = [...new Set(trvItems.map(i => i.group))];
        rail.innerHTML = '';
        const mkCat = (key, label, icon, count) => {
            const b = document.createElement('button');
            b.type = 'button';
            b.className = 'trv-cat' + (trvCat === key ? ' active' : '');
            b.innerHTML = `<i class="fas ${icon}"></i><span></span><b>${count}</b>`;
            b.querySelector('span').textContent = label;
            b.addEventListener('click', () => { trvCat = key; trvRender(); });
            rail.appendChild(b);
        };
        mkCat('*', 'Tümü', 'fa-layer-group', trvItems.length);
        cats.forEach(c => mkCat(c, c, TRV_CAT_ICONS[c] || 'fa-tag', trvItems.filter(i => i.group === c).length));

        // Değişken kartları
        const filtered = trvItems.filter(i =>
            (trvCat === '*' || i.group === trvCat) &&
            (!term || (i.label + ' ' + i.token + ' ' + i.group).toLocaleLowerCase('tr').includes(term))
        );

        grid.innerHTML = '';
        filtered.forEach(i => {
            const item = document.createElement('button');
            item.type = 'button';
            item.className = 'trv-item';
            item.innerHTML = `<span class="trv-item-label"></span><span class="trv-item-token"></span>`;
            item.querySelector('.trv-item-label').textContent = i.label;
            item.querySelector('.trv-item-token').textContent = TOKEN_OPEN + i.token + TOKEN_CLOSE;
            item.addEventListener('click', (e) => trvInsert(i.token, e.ctrlKey || e.metaKey));
            grid.appendChild(item);
        });

        empty.style.display = filtered.length ? 'none' : 'block';
    }

    function trvInsert(token, keepOpen) {
        if (!trvInput) return;
        const text = TOKEN_OPEN + token + TOKEN_CLOSE;

        if (trvInput.__quill) {
            // Zengin metin (Quill): imleç konumuna ekle
            const q = trvInput.__quill;
            const range = q.getSelection(true) || { index: q.getLength(), length: 0 };
            if (range.length > 0) q.deleteText(range.index, range.length);
            q.insertText(range.index, text);
            q.setSelection(range.index + text.length);
        } else {
            const start = trvInput.selectionStart ?? trvInput.value.length;
            const end = trvInput.selectionEnd ?? start;
            trvInput.value = trvInput.value.slice(0, start) + text + trvInput.value.slice(end);
            trvInput.focus();
            trvInput.selectionStart = trvInput.selectionEnd = start + text.length;
        }

        if (!keepOpen) {
            bootstrap.Modal.getInstance(document.getElementById('trVarModal'))?.hide();
        }
    }

    document.getElementById('trvSearch').addEventListener('input', trvRender);
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('agency.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\acente\resources\views/agency/staff-management/task-rules/index.blade.php ENDPATH**/ ?>