{{-- Dental recall widget. Receives $patient (ClcPatient). Schedule recalls
     (cleaning, perio maintenance, review…) with a due date + interval. A daily
     console command fires MedNotify 'dental.recall_due' for due rows. AJAX
     against dental.recalls.* routes. --}}
@php
    $canRecall = auth()->user()->can('dental.treatment_plan.manage');
    $recWid = 'dentRecall' . $patient->id;
    $recStatuses = [
        'due'       => __('dentalClinic::lang.recall_status_due'),
        'scheduled' => __('dentalClinic::lang.recall_status_scheduled'),
        'done'      => __('dentalClinic::lang.recall_status_done'),
        'cancelled' => __('dentalClinic::lang.recall_status_cancelled'),
    ];
@endphp
<div class="detail-row" style="display:block;" id="{{ $recWid }}"
     data-list-url="{{ route('dental.recalls.index', $patient->id) }}"
     data-store-url="{{ route('dental.recalls.store', $patient->id) }}"
     data-due-url="{{ route('dental.recalls.due') }}"
     data-can-edit="{{ $canRecall ? '1' : '0' }}">
    <span class="dk" style="display:block;margin-bottom:6px;">
        <i class="fas fa-bell fa-fw"></i> {{ __('dentalClinic::lang.recall_system') }}
    </span>

    {{-- Clinic-wide currently-due recalls (dental.recalls.due). Collapsed by
         default; expands the compact list of due rows across all patients. --}}
    @if($canRecall)
    <details class="dent-recall-due" style="margin-bottom:6px;font-size:11px;">
        <summary style="cursor:pointer;color:#b45309;">
            <i class="fas fa-clock fa-fw"></i> {{ __('dentalClinic::lang.due_recalls') }}
            <span class="dent-recall-due-count label label-warning" style="display:none;"></span>
        </summary>
        <div class="dent-recall-due-list" style="margin-top:4px;">
            <div class="text-muted">{{ __('dentalClinic::lang.loading') }}</div>
        </div>
    </details>
    @endif

    @if($canRecall)
    <form class="dent-recall-form" style="margin:6px 0;padding:8px;border:1px solid #e2e8f0;border-radius:6px;background:#f8fafc;">
        <div style="display:flex;flex-wrap:wrap;gap:6px;">
            <input name="due_date" type="date" class="form-control input-sm" style="width:140px;" required>
            <input name="reason" class="form-control input-sm" placeholder="{{ __('dentalClinic::lang.reason') }} (e.g. cleaning)" style="flex:1;min-width:120px;">
            <input name="interval_months" type="number" min="0" max="120" class="form-control input-sm" placeholder="{{ __('dentalClinic::lang.interval_months') }}" style="width:110px;">
            <select name="status" class="form-control input-sm" style="width:110px;">
                @foreach($recStatuses as $val => $lbl)<option value="{{ $val }}">{{ $lbl }}</option>@endforeach
            </select>
            <button type="submit" class="btn btn-xs btn-success">{{ __('dentalClinic::lang.add_recall') }}</button>
        </div>
    </form>
    @endif

    <div class="dent-recall-list" style="font-size:11px;">
        <div class="text-muted">{{ __('dentalClinic::lang.no_recalls') }}</div>
    </div>
</div>

@once
<script>
(function () {
    function csrf() { return document.querySelector('meta[name="csrf-token"]') ? document.querySelector('meta[name="csrf-token"]').getAttribute('content') : '{{ csrf_token() }}'; }
    function esc(s) { const d = document.createElement('div'); d.textContent = (s == null ? '' : s); return d.innerHTML; }

    function render(root, rows) {
        const canEdit = root.dataset.canEdit === '1';
        const list = root.querySelector('.dent-recall-list');
        if (!rows || !rows.length) { list.innerHTML = '<div class="text-muted">{{ __('dentalClinic::lang.no_recalls') }}</div>'; return; }
        list.innerHTML = rows.map(function (r) {
            const cls = r.status === 'due' ? 'label-warning' : (r.status === 'done' ? 'label-success' : (r.status === 'cancelled' ? 'label-default' : 'label-info'));
            return '<div class="dent-recall-item" data-id="' + r.id + '" style="padding:5px 0;border-bottom:1px solid #f0f0f0;">'
                + '<span class="label ' + cls + '">' + esc(r.status) + '</span> '
                + '<strong>' + esc(r.due_date) + '</strong>'
                + (r.reason ? ' — ' + esc(r.reason) : '')
                + (r.interval_months ? ' <span class="text-muted">(every ' + r.interval_months + 'mo)</span>' : '')
                + (canEdit ? ' <a href="#" class="dent-recall-del text-danger" style="float:right;font-size:10px;">delete</a>' : '')
                + '</div>';
        }).join('');
    }

    function load(root) {
        fetch(root.dataset.listUrl, { headers: { 'Accept': 'application/json' } })
            .then(r => r.json()).then(d => { if (d.success) render(root, d.data); }).catch(() => {});
    }

    function loadDue(root) {
        const box = root.querySelector('.dent-recall-due-list');
        if (!box || !root.dataset.dueUrl) return;
        fetch(root.dataset.dueUrl, { headers: { 'Accept': 'application/json' } })
            .then(r => r.json()).then(function (d) {
                if (!d.success) return;
                const rows = d.data || [];
                const badge = root.querySelector('.dent-recall-due-count');
                if (badge) { badge.textContent = rows.length; badge.style.display = rows.length ? '' : 'none'; }
                if (!rows.length) { box.innerHTML = '<div class="text-muted">{{ __('dentalClinic::lang.no_due_recalls') }}</div>'; return; }
                box.innerHTML = rows.map(function (r) {
                    return '<div style="padding:3px 0;border-bottom:1px solid #f0f0f0;">'
                        + '<strong>' + esc(r.due_date) + '</strong>'
                        + (r.patient_name ? ' — ' + esc(r.patient_name) : '')
                        + (r.reason ? ' <span class="text-muted">(' + esc(r.reason) + ')</span>' : '')
                        + '</div>';
                }).join('');
            }).catch(() => {});
    }

    document.addEventListener('submit', function (e) {
        const f = e.target.closest('.dent-recall-form');
        if (!f) return;
        e.preventDefault();
        const root = f.closest('[id^="dentRecall"]');
        const payload = {};
        new FormData(f).forEach((v, k) => payload[k] = v);
        fetch(root.dataset.storeUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf(), 'Accept': 'application/json' },
            body: JSON.stringify(payload)
        }).then(r => r.json()).then(d => { if (d.success) { f.reset(); load(root); } else if (d.msg) alert(d.msg); }).catch(() => {});
    });

    document.addEventListener('click', function (e) {
        const del = e.target.closest('.dent-recall-del');
        if (!del) return;
        e.preventDefault();
        const root = del.closest('[id^="dentRecall"]');
        const id = del.closest('.dent-recall-item').dataset.id;
        if (!confirm('Delete this recall?')) return;
        fetch(root.dataset.listUrl + '/' + id, { method: 'DELETE', headers: { 'X-CSRF-TOKEN': csrf(), 'Accept': 'application/json' } })
            .then(r => r.json()).then(() => load(root)).catch(() => {});
    });

    document.querySelectorAll('[id^="dentRecall"]').forEach(function (root) { load(root); loadDue(root); });
})();
</script>
@endonce
