{{-- Dental treatment-plan builder. Receives $patient (ClcPatient). Build a plan
     of rows (procedure + tooth + urgency + est. cost), see a running total,
     print a patient-friendly copy, and convert the plan into a shared ClinicCore
     treatment plan. AJAX against dental.plan.* routes. --}}
@php
    $canPlan = auth()->user()->can('dental.treatment_plan.manage');
    $planWid = 'dentPlan' . $patient->id;
    $urgencies = [
        'elective'  => __('dentalClinic::lang.urgency_elective'),
        'soon'      => __('dentalClinic::lang.urgency_soon'),
        'urgent'    => __('dentalClinic::lang.urgency_urgent'),
        'emergency' => __('dentalClinic::lang.urgency_emergency'),
    ];
@endphp
<div class="detail-row" style="display:block;" id="{{ $planWid }}"
     data-list-url="{{ route('dental.plan.index', $patient->id) }}"
     data-store-url="{{ route('dental.plan.store', $patient->id) }}"
     data-convert-url="{{ route('dental.plan.convert', $patient->id) }}"
     data-print-url="{{ route('dental.plan.print', $patient->id) }}"
     data-can-edit="{{ $canPlan ? '1' : '0' }}">
    <span class="dk" style="display:block;margin-bottom:6px;">
        <i class="fas fa-clipboard-list fa-fw"></i> {{ __('dentalClinic::lang.plan_builder') }}
    </span>

    @if($canPlan)
    <form class="dent-plan-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="plan_name" class="form-control input-sm" placeholder="{{ __('dentalClinic::lang.plan_name') }}" value="Treatment plan" style="flex:1;min-width:120px;">
            <input name="procedure_name" class="form-control input-sm" placeholder="{{ __('dentalClinic::lang.procedure_name') }} *" style="flex:2;min-width:150px;" required>
            <input name="cdt_code" class="form-control input-sm" placeholder="{{ __('dentalClinic::lang.cdt_code') }}" style="width:80px;">
            <input name="tooth_number" type="number" min="1" max="32" class="form-control input-sm" placeholder="{{ __('dentalClinic::lang.tooth') }}" style="width:70px;">
            <select name="urgency" class="form-control input-sm" style="width:110px;">
                @foreach($urgencies as $val => $lbl)<option value="{{ $val }}">{{ $lbl }}</option>@endforeach
            </select>
            <input name="estimated_cost" type="number" step="0.01" min="0" class="form-control input-sm" placeholder="{{ __('dentalClinic::lang.estimated_cost') }}" style="width:100px;">
            <button type="submit" class="btn btn-xs btn-success">{{ __('dentalClinic::lang.add_plan_item') }}</button>
        </div>
    </form>
    @endif

    <div class="dent-plan-list" style="font-size:11px;">
        <div class="text-muted">{{ __('dentalClinic::lang.no_plan_items') }}</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 money(v) { return (v == null || v === '') ? '' : Number(v).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); }

    function render(root, plans) {
        const canEdit = root.dataset.canEdit === '1';
        const list = root.querySelector('.dent-plan-list');
        if (!plans || !plans.length) { list.innerHTML = '<div class="text-muted">{{ __('dentalClinic::lang.no_plan_items') }}</div>'; return; }
        list.innerHTML = plans.map(function (pl) {
            const rows = pl.items.map(function (it) {
                return '<tr data-id="' + it.id + '">'
                    + '<td>' + (it.tooth_number ? 'T' + it.tooth_number : '—') + '</td>'
                    + '<td>' + esc(it.procedure_name) + (it.cdt_code ? ' <small class="text-muted">' + esc(it.cdt_code) + '</small>' : '') + '</td>'
                    + '<td>' + esc(it.urgency) + '</td>'
                    + '<td style="text-align:right;">' + money(it.estimated_cost) + '</td>'
                    + '<td>' + esc(it.status) + '</td>'
                    + (canEdit && !it.clc_treatment_plan_id ? '<td><a href="#" class="dent-plan-del text-danger">×</a></td>' : '<td></td>')
                    + '</tr>';
            }).join('');
            const convertBtn = (canEdit && !pl.converted)
                ? '<button type="button" class="btn btn-xs btn-primary dent-plan-convert" data-plan="' + esc(pl.plan_name) + '"><i class="fa fa-exchange-alt"></i> {{ __('dentalClinic::lang.convert_to_clc') }}</button>'
                : (pl.converted ? '<span class="label label-success">Converted</span>' : '');
            return '<div style="margin-bottom:10px;">'
                + '<div style="font-weight:700;margin-bottom:2px;">' + esc(pl.plan_name) + '</div>'
                + '<table class="table table-condensed" style="margin-bottom:4px;"><thead><tr>'
                + '<th>{{ __('dentalClinic::lang.tooth') }}</th><th>{{ __('dentalClinic::lang.procedure_name') }}</th><th>{{ __('dentalClinic::lang.urgency') }}</th>'
                + '<th style="text-align:right;">{{ __('dentalClinic::lang.estimated_cost') }}</th><th>{{ __('dentalClinic::lang.status') }}</th><th></th></tr></thead><tbody>'
                + rows + '</tbody></table>'
                + '<div style="display:flex;justify-content:space-between;align-items:center;gap:8px;">'
                + '<span>{{ __('dentalClinic::lang.total_estimate') }}: <strong>' + money(pl.total_estimate) + '</strong></span>'
                + '<span>' + convertBtn
                + ' <a class="btn btn-xs btn-default" target="_blank" href="' + root.dataset.printUrl + '?plan_name=' + encodeURIComponent(pl.plan_name) + '"><i class="fa fa-print"></i> {{ __('dentalClinic::lang.print_plan') }}</a></span>'
                + '</div></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.plans); }).catch(() => {});
    }

    document.addEventListener('submit', function (e) {
        const f = e.target.closest('.dent-plan-form');
        if (!f) return;
        e.preventDefault();
        const root = f.closest('[id^="dentPlan"]');
        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.querySelector('[name=procedure_name]').value = ''; f.querySelector('[name=cdt_code]').value=''; f.querySelector('[name=tooth_number]').value=''; f.querySelector('[name=estimated_cost]').value=''; load(root); }
            else if (d.msg) alert(d.msg);
        }).catch(() => {});
    });

    document.addEventListener('click', function (e) {
        const root = e.target.closest('[id^="dentPlan"]');
        if (!root) return;
        const del = e.target.closest('.dent-plan-del');
        if (del) {
            e.preventDefault();
            const id = del.closest('tr').dataset.id;
            if (!confirm('Remove this item?')) return;
            fetch(root.dataset.listUrl + '/' + id, { method: 'DELETE', headers: { 'X-CSRF-TOKEN': csrf(), 'Accept': 'application/json' } })
                .then(r => r.json()).then(() => load(root)).catch(() => {});
            return;
        }
        const conv = e.target.closest('.dent-plan-convert');
        if (conv) {
            const planName = conv.dataset.plan;
            if (!confirm('Convert "' + planName + '" into a ClinicCore treatment plan?')) return;
            fetch(root.dataset.convertUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf(), 'Accept': 'application/json' },
                body: JSON.stringify({ plan_name: planName })
            }).then(r => r.json()).then(d => { if (d.msg) alert(d.msg); load(root); }).catch(() => {});
        }
    });

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