{{-- Dental procedures log widget. Reused by the appointment fragment (record
     during a visit) and the patient show fragment (history list). Receives
     $patient (ClcPatient) and optional $appointment (ClcAppointment). All CRUD
     is AJAX against the dental.procedures.* routes. --}}
@php
    $canProc = auth()->user()->can('dental.procedures.manage');
    $procWid = 'dentProc' . $patient->id;
    $procApptId = isset($appointment) && $appointment ? (int) $appointment->id : '';
@endphp
<div class="detail-row" style="display:block;" id="{{ $procWid }}"
     data-list-url="{{ route('dental.procedures.index', $patient->id) }}"
     data-store-url="{{ route('dental.procedures.store', $patient->id) }}"
     data-patient="{{ $patient->id }}"
     data-appt="{{ $procApptId }}"
     data-can-edit="{{ $canProc ? '1' : '0' }}">
    <span class="dk" style="display:block;margin-bottom:6px;">
        <i class="fas fa-notes-medical fa-fw"></i> {{ __('dentalClinic::lang.procedures_log') }}
        @if($canProc)
            <button type="button" class="dent-proc-add btn btn-xs btn-primary" style="float:right;font-size:10px;padding:2px 8px;">
                <i class="fa fa-plus"></i> {{ __('dentalClinic::lang.add_procedure') }}
            </button>
        @endif
    </span>

    @if($canProc)
    <form class="dent-proc-form" style="display:none;margin:6px 0;padding:8px;border:1px solid #e2e8f0;border-radius:6px;background:#f8fafc;">
        <input type="hidden" name="id" value="">
        <input type="hidden" name="appointment_id" value="{{ $procApptId }}">
        <div style="display:flex;flex-wrap:wrap;gap:6px;">
            <input name="procedure_name" class="form-control input-sm" placeholder="{{ __('dentalClinic::lang.procedure_name') }} *" style="flex:2;min-width:160px;" required>
            <input name="cdt_code" class="form-control input-sm" placeholder="{{ __('dentalClinic::lang.cdt_code') }}" style="flex:1;min-width:80px;">
            <input name="tooth_number" type="number" min="1" max="32" class="form-control input-sm" placeholder="{{ __('dentalClinic::lang.tooth') }}" style="width:70px;">
            <input name="surfaces" class="form-control input-sm" placeholder="{{ __('dentalClinic::lang.surfaces') }}" style="width:90px;">
        </div>
        <div style="display:flex;flex-wrap:wrap;gap:6px;margin-top:6px;">
            <input name="anesthesia_type" class="form-control input-sm" placeholder="{{ __('dentalClinic::lang.anesthesia') }}" style="flex:1;min-width:120px;">
            <input name="performed_at" type="datetime-local" class="form-control input-sm" style="flex:1;min-width:150px;">
        </div>
        <textarea name="complications" class="form-control input-sm" rows="1" placeholder="{{ __('dentalClinic::lang.complications') }}" style="margin-top:6px;"></textarea>
        <textarea name="post_op_instructions" class="form-control input-sm" rows="1" placeholder="{{ __('dentalClinic::lang.post_op_instructions') }}" style="margin-top:6px;"></textarea>
        <div style="margin-top:6px;">
            <button type="submit" class="btn btn-xs btn-success">Save</button>
            <button type="button" class="dent-proc-cancel btn btn-xs btn-default">Cancel</button>
        </div>
    </form>
    @endif

    <div class="dent-proc-list" style="font-size:11px;">
        <div class="text-muted">{{ __('dentalClinic::lang.no_procedures') }}</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 renderRow(root, p) {
        const canEdit = root.dataset.canEdit === '1';
        const bits = [];
        if (p.tooth_number) bits.push('T' + p.tooth_number + (p.surfaces ? ' (' + esc(p.surfaces) + ')' : ''));
        if (p.cdt_code) bits.push(esc(p.cdt_code));
        if (p.anesthesia_type) bits.push(esc(p.anesthesia_type));
        return '<div class="dent-proc-item" data-id="' + p.id + '" style="padding:5px 0;border-bottom:1px solid #f0f0f0;">'
            + '<strong>' + esc(p.procedure_name) + '</strong>'
            + (bits.length ? ' <span class="text-muted">— ' + bits.join(' · ') + '</span>' : '')
            + (p.performed_at ? ' <span class="text-muted" style="float:right;">' + esc(p.performed_at) + '</span>' : '')
            + (p.complications ? '<div class="text-danger" style="font-size:10px;">⚠ ' + esc(p.complications) + '</div>' : '')
            + (p.post_op_instructions ? '<div class="text-muted" style="font-size:10px;">' + esc(p.post_op_instructions) + '</div>' : '')
            + (canEdit ? '<div style="margin-top:2px;"><a href="#" class="dent-proc-del text-danger" style="font-size:10px;">delete</a></div>' : '')
            + '</div>';
    }

    function load(root) {
        fetch(root.dataset.listUrl, { headers: { 'Accept': 'application/json' } })
            .then(r => r.json()).then(d => {
                const list = root.querySelector('.dent-proc-list');
                if (!d.success || !d.data.length) { list.innerHTML = '<div class="text-muted">{{ __('dentalClinic::lang.no_procedures') }}</div>'; return; }
                list.innerHTML = d.data.map(p => renderRow(root, p)).join('');
            }).catch(() => {});
    }

    document.addEventListener('click', function (e) {
        const root = e.target.closest('[id^="dentProc"]');
        if (!root) return;

        if (e.target.closest('.dent-proc-add')) {
            const f = root.querySelector('.dent-proc-form'); if (f) { f.reset(); f.querySelector('[name=id]').value=''; f.querySelector('[name=appointment_id]').value = root.dataset.appt || ''; f.style.display = 'block'; }
            return;
        }
        if (e.target.closest('.dent-proc-cancel')) { root.querySelector('.dent-proc-form').style.display = 'none'; return; }
        const del = e.target.closest('.dent-proc-del');
        if (del) {
            e.preventDefault();
            const id = del.closest('.dent-proc-item').dataset.id;
            if (!confirm('Delete this procedure?')) 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.addEventListener('submit', function (e) {
        const f = e.target.closest('.dent-proc-form');
        if (!f) return;
        e.preventDefault();
        const root = f.closest('[id^="dentProc"]');
        const id = f.querySelector('[name=id]').value;
        const url = id ? (root.dataset.listUrl + '/' + id) : root.dataset.storeUrl;
        const payload = {};
        new FormData(f).forEach((v, k) => { if (k !== 'id') payload[k] = v; });
        fetch(url, {
            method: id ? 'PUT' : '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.style.display = 'none'; f.reset(); load(root); }
            else if (d.msg) alert(d.msg);
        }).catch(() => {});
    });

    document.querySelectorAll('[id^="dentProc"]').forEach(load);
})();
</script>
@endonce
