@extends('layouts.app')
@section('title', isset($prescription) ? __('clinicCore::lang.edit') : __('clinicCore::lang.add_new'))

@section('css')
@include('clinicCore::partials._mobile_responsive')
@endsection

@section('content')
<section class="content-header">
    <h1><i class="fas fa-prescription-bottle-alt"></i>
        {{ isset($prescription) ? __('clinicCore::lang.edit') . ' Prescription' : 'New Prescription' }}
    </h1>
</section>

<section class="content">
    <form method="POST"
          action="{{ isset($prescription) ? route('clinic.prescriptions.update', $prescription->id) : route('clinic.prescriptions.store') }}">
        @csrf

        {{-- SIFA P3-T5 — server-side safety warnings (confirm-required banner).
             Shown when the store flow blocked on a severe allergy match. --}}
        @if(session('rx_safety'))
        @php $rxSafety = session('rx_safety'); $rxBlocking = collect($rxSafety)->contains(fn($w) => !empty($w['block'])); @endphp
        <div class="alert {{ $rxBlocking ? 'alert-danger' : 'alert-warning' }}" style="border-left-width:4px;">
            <h4 style="margin-top:0;"><i class="fa fa-shield-alt"></i> @lang('clinicCore::lang.rx_safety_warnings')</h4>
            <ul style="margin-bottom:8px;">
                @foreach($rxSafety as $w)
                <li>
                    <strong>[{{ ucfirst(str_replace('_',' ', $w['type'] ?? '')) }} · {{ $w['severity'] ?? '' }}]</strong>
                    {{ $w['message'] ?? '' }}
                </li>
                @endforeach
            </ul>
            @if($rxBlocking)
            <label style="font-weight:600;">
                <input type="checkbox" name="rx_safety_confirmed" value="1" required>
                @lang('clinicCore::lang.rx_safety_confirm')
            </label>
            @else
            <input type="hidden" name="rx_safety_confirmed" value="1">
            @endif
        </div>
        @endif

        <div class="row">
            <div class="col-md-8">
                @component('components.widget', ['class' => 'box-primary', 'title' => 'Prescription Details'])
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.pet_owner') <span class="text-danger">*</span></label>
                                @if(isset($prescription))
                                    {{-- Edit mode: read-only display --}}
                                    <input type="hidden" name="contact_id" value="{{ $prescription->contact_id }}">
                                    @php
                                        $ownerDetailId = \Modules\ClinicCore\Entities\ClcPatientContactDetail::where('contact_id', $prescription->contact_id)->value('id');
                                    @endphp
                                    <div class="form-control bg-gray" style="height:auto;min-height:34px;display:flex;align-items:center;gap:8px;">
                                        <i class="fa fa-user text-muted"></i>
                                        @if(isset($ownerContact) && $ownerContact)
                                            @if($ownerDetailId)
                                                <a href="{{ route('clinic.patient-contacts.show', $ownerDetailId) }}" target="_blank" style="font-weight:600;">{{ $ownerContact->name }}</a>
                                            @else
                                                <strong>{{ $ownerContact->name }}</strong>
                                            @endif
                                            @if($ownerContact->mobile)
                                                <small class="text-muted"><i class="fa fa-phone"></i> {{ $ownerContact->mobile }}</small>
                                            @endif
                                        @else
                                            <span class="text-muted">Owner #{{ $prescription->contact_id }}</span>
                                        @endif
                                    </div>
                                @else
                                    {{-- Create mode: AJAX search --}}
                                    <select name="contact_id" id="rx_contact_id" class="form-control" style="width:100%" required>
                                        @if(request('contact_id'))
                                            <option value="{{ request('contact_id') }}" selected>{{ optional(\App\Contact::find(request('contact_id')))->name }}</option>
                                        @endif
                                    </select>
                                @endif
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Patient <span class="text-danger">*</span></label>
                                @if(isset($prescription))
                                    {{-- Edit mode: read-only display --}}
                                    <input type="hidden" name="patient_id" value="{{ $prescription->patient_id }}">
                                    <div class="form-control bg-gray" style="height:auto;min-height:34px;display:flex;align-items:center;gap:8px;">
                                        <i class="fa fa-notes-medical text-muted"></i>
                                        @if(isset($patientRecord) && $patientRecord)
                                            <a href="{{ route('clinic.patients.show', $patientRecord->id) }}" target="_blank" style="font-weight:600;">{{ $patientRecord->patient_name }}</a>
                                            @if(config('cliniccore.show_animal_fields', false) && $patientRecord->species)
                                                <small class="text-muted">· {{ ucfirst($patientRecord->species) }}</small>
                                            @endif
                                        @else
                                            <span class="text-muted">Patient #{{ $prescription->patient_id }}</span>
                                        @endif
                                    </div>
                                @else
                                    {{-- Create mode: dynamic select (populated by contact selection) --}}
                                    <select name="patient_id" id="rx_patient_id" class="form-control" style="width:100%" required>
                                        @if(request('patient_id'))
                                            <option value="{{ request('patient_id') }}" selected>{{ optional(\Modules\ClinicCore\Entities\ClcPatient::find(request('patient_id')))->patient_name }}</option>
                                        @endif
                                    </select>
                                @endif
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.doctor')</label>
                                <select name="doctor_id" class="form-control select2" style="width:100%">
                                    <option value="">— None —</option>
                                    @foreach($doctors as $doc)
                                    <option value="{{ $doc->id }}" {{ old('doctor_id', isset($prescription) ? $prescription->doctor_id : '') == $doc->id ? 'selected' : '' }}>
                                        {{ $doc->name }}{{ $doc->specialization ? ' (' . $doc->specialization . ')' : '' }}
                                    </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            @php
                                $linkedAptId = isset($prescription) ? $prescription->appointment_id : request('appointment_id');
                            @endphp
                            @if($linkedAptId)
                            <div class="form-group">
                                <label>Linked Appointment</label>
                                <input type="hidden" name="appointment_id" value="{{ $linkedAptId }}">
                                @if(isset($prescription) && $prescription->appointment)
                                <a href="{{ route('clinic.appointments.show', $linkedAptId) }}"
                                   target="_blank"
                                   class="btn btn-default btn-sm" style="width:100%;text-align:left;">
                                    <i class="fa fa-calendar" style="color:#2980b9;"></i>
                                    {{ $prescription->appointment->ref_no }}
                                    <small class="text-muted" style="float:right;margin-top:2px;">
                                        {{ \Carbon\Carbon::parse($prescription->appointment->appointment_date)->format(session('business.date_format','d M Y')) }}
                                    </small>
                                </a>
                                @else
                                <a href="{{ route('clinic.appointments.show', $linkedAptId) }}"
                                   target="_blank" class="btn btn-default btn-sm" style="width:100%;">
                                    <i class="fa fa-calendar" style="color:#2980b9;"></i> View Appointment
                                </a>
                                @endif
                            </div>
                            @endif
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.prescribed_date') <span class="text-danger">*</span></label>
                                <input type="date" name="prescribed_date" class="form-control"
                                    value="{{ old('prescribed_date', isset($prescription) ? $prescription->prescribed_date->format('Y-m-d') : date('Y-m-d')) }}" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            @if(isset($prescription))
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.status')</label>
                                <select name="status" class="form-control">
                                    @foreach(['active','completed','cancelled'] as $s)
                                    <option value="{{ $s }}" {{ $prescription->status == $s ? 'selected' : '' }}>{{ ucfirst($s) }}</option>
                                    @endforeach
                                </select>
                            </div>
                            @endif
                        </div>
                    </div>

                    {{-- SIFA P3-T5 — prescription type (outpatient / discharge) --}}
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.rx_type')</label>
                                <select name="rx_type" class="form-control">
                                    <option value="">—</option>
                                    @foreach(['outpatient','discharge'] as $rt)
                                    <option value="{{ $rt }}" {{ old('rx_type', isset($prescription) ? $prescription->rx_type : '') == $rt ? 'selected' : '' }}>
                                        @lang('clinicCore::lang.rx_type_'.$rt)
                                    </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>@lang('clinicCore::lang.diagnosis')</label>
                        <textarea name="diagnosis" class="form-control" rows="2">{{ old('diagnosis', isset($prescription) ? $prescription->diagnosis : '') }}</textarea>
                    </div>
                    <div class="form-group">
                        <label>@lang('clinicCore::lang.notes')</label>
                        <textarea name="notes" class="form-control" rows="2">{{ old('notes', isset($prescription) ? $prescription->notes : '') }}</textarea>
                    </div>
                @endcomponent

                @component('components.widget', ['class' => 'box-default', 'title' => 'Medicines'])
                    <table class="table table-bordered" id="rx_items_table">
                        <thead>
                            <tr>
                                <th style="width:24%">Medicine</th>
                                <th style="width:12%">Dosage</th>
                                <th style="width:16%">Frequency</th>
                                <th style="width:8%">Days</th>
                                <th>Instructions</th>
                                <th style="width:150px;">@lang('clinicCore::lang.refills') / @lang('clinicCore::lang.prn')</th>
                                <th style="width:40px;"></th>
                            </tr>
                        </thead>
                        <tbody id="rx_items_body">
                            @if(isset($prescription) && $prescription->items->count())
                                @foreach($prescription->items as $i => $item)
                                <tr class="rx-item-row">
                                    <td style="position:relative;">
                                        <input type="hidden" name="items[{{ $i }}][medicine_id]" class="medicine-id-input" value="{{ $item->medicine_id }}">
                                        <input type="text" class="form-control medicine-search" placeholder="Search medicine..." value="{{ $item->medicine_name }}" autocomplete="off">
                                        <input type="hidden" name="items[{{ $i }}][medicine_name]" class="medicine-name-input" value="{{ $item->medicine_name }}">
                                        <div class="medicine-suggestions" style="display:none;position:absolute;z-index:999;background:#fff;border:1px solid #ddd;max-height:150px;overflow-y:auto;width:200px;"></div>
                                    </td>
                                    <td><input type="text" name="items[{{ $i }}][dosage]" class="form-control" value="{{ $item->dosage }}" placeholder="e.g. 250mg"></td>
                                    <td>
                                        <select name="items[{{ $i }}][frequency]" class="form-control freq-select" data-selected="{{ $item->frequency }}">
                                            <option value="{{ $item->frequency }}">{{ $item->frequency ?: '— Select —' }}</option>
                                        </select>
                                    </td>
                                    <td><input type="number" name="items[{{ $i }}][duration_days]" class="form-control" value="{{ $item->duration_days }}" min="1"></td>
                                    <td><input type="text" name="items[{{ $i }}][instructions]" class="form-control" value="{{ $item->instructions }}" placeholder="Special instructions"></td>
                                    <td>
                                        <input type="number" name="items[{{ $i }}][refills_allowed]" class="form-control input-sm" value="{{ $item->refills_allowed ?? 0 }}" min="0" title="@lang('clinicCore::lang.refills_allowed')" style="margin-bottom:4px;">
                                        <label style="font-size:11px;font-weight:400;margin:0;display:block;"><input type="checkbox" name="items[{{ $i }}][prn]" value="1" {{ !empty($item->prn) ? 'checked' : '' }}> @lang('clinicCore::lang.prn')</label>
                                        <label style="font-size:11px;font-weight:400;margin:0;display:block;"><input type="checkbox" name="items[{{ $i }}][substitutions_allowed]" value="1" {{ ($item->substitutions_allowed ?? true) ? 'checked' : '' }}> @lang('clinicCore::lang.substitutions_allowed')</label>
                                        <input type="text" name="items[{{ $i }}][prn_reason]" class="form-control input-sm" value="{{ $item->prn_reason }}" placeholder="@lang('clinicCore::lang.prn_reason')" style="margin-top:4px;">
                                    </td>
                                    <td><button type="button" class="btn btn-danger btn-xs btn-remove-row"><i class="fa fa-trash"></i></button></td>
                                </tr>
                                @endforeach
                            @endif
                        </tbody>
                    </table>
                    <button type="button" class="btn btn-default btn-sm" id="btn_add_rx_row">
                        <i class="fa fa-plus"></i> Add Medicine
                    </button>
                    @if(\Modules\ClinicCore\Http\Controllers\ClcAiController::available())
                    <button type="button" class="btn btn-warning btn-sm" id="btn_rx_safety" style="margin-left:6px;">
                        <i class="fa fa-shield-alt"></i> AI safety check
                    </button>
                    <div id="rx_safety_result" style="margin-top:12px;"></div>
                    @endif
                    {{-- SIFA P3-T5 — deterministic safety gate (allergy / duplicate therapy) --}}
                    <div id="rx_safety_gate" style="margin-top:12px;display:none;"></div>
                @endcomponent
            </div>

            <div class="col-md-4">
                <div class="form-group" style="margin-top:20px;">
                    <button type="submit" class="btn btn-primary btn-block">
                        <i class="fa fa-save"></i>
                        {{ isset($prescription) ? __('clinicCore::lang.update') : __('clinicCore::lang.save') }}
                    </button>
                    <a href="{{ isset($prescription) ? route('clinic.prescriptions.show', $prescription->id) : route('clinic.prescriptions.index') }}"
                       class="btn btn-default btn-block">@lang('clinicCore::lang.cancel')</a>
                </div>
            </div>
        </div>
    </form>
</section>
@endsection

@section('javascript')
<script>
var rowIndex   = {{ isset($prescription) ? $prescription->items->count() : 0 }};
var freqOptions = [];   // populated on load from SOAP options

// Load frequency options from DB (same source as appointment plan section)
$.getJSON('{{ route('clinic.soap-options.data') }}', { section: 'frequency', species: 'all' }, function (data) {
    freqOptions = data.map(function (d) { return d.label; });
    // Populate existing selects (edit mode)
    $('.freq-select').each(function () {
        var $sel     = $(this);
        var selected = $sel.data('selected') || '';
        $sel.empty();
        $sel.append('<option value="">— Select —</option>');
        $.each(freqOptions, function (i, label) {
            $sel.append('<option value="' + label + '"' + (label === selected ? ' selected' : '') + '>' + label + '</option>');
        });
    });
});

function freqSelectHtml(name, selected) {
    selected = selected || '';
    var opts = '<option value="">— Select —</option>';
    $.each(freqOptions, function (i, label) {
        opts += '<option value="' + label + '"' + (label === selected ? ' selected' : '') + '>' + label + '</option>';
    });
    return '<select name="' + name + '" class="form-control freq-select">' + opts + '</select>';
}

function makeRow(idx) {
    return '<tr class="rx-item-row">'
        + '<td style="position:relative;">'
        +   '<input type="hidden" name="items[' + idx + '][medicine_id]" class="medicine-id-input" value="">'
        +   '<input type="text" class="form-control medicine-search" placeholder="Search medicine..." autocomplete="off">'
        +   '<input type="hidden" name="items[' + idx + '][medicine_name]" class="medicine-name-input" value="">'
        +   '<div class="medicine-suggestions" style="display:none;position:absolute;z-index:999;background:#fff;border:1px solid #ddd;max-height:150px;overflow-y:auto;width:200px;"></div>'
        + '</td>'
        + '<td><input type="text" name="items[' + idx + '][dosage]" class="form-control" placeholder="e.g. 250mg"></td>'
        + '<td>' + freqSelectHtml('items[' + idx + '][frequency]', '') + '</td>'
        + '<td><input type="number" name="items[' + idx + '][duration_days]" class="form-control" min="1"></td>'
        + '<td><input type="text" name="items[' + idx + '][instructions]" class="form-control" placeholder="Special instructions"></td>'
        + '<td>'
        +   '<input type="number" name="items[' + idx + '][refills_allowed]" class="form-control input-sm" value="0" min="0" title="{{ __('clinicCore::lang.refills_allowed') }}" style="margin-bottom:4px;">'
        +   '<label style="font-size:11px;font-weight:400;margin:0;display:block;"><input type="checkbox" name="items[' + idx + '][prn]" value="1"> {{ __('clinicCore::lang.prn') }}</label>'
        +   '<label style="font-size:11px;font-weight:400;margin:0;display:block;"><input type="checkbox" name="items[' + idx + '][substitutions_allowed]" value="1" checked> {{ __('clinicCore::lang.substitutions_allowed') }}</label>'
        +   '<input type="text" name="items[' + idx + '][prn_reason]" class="form-control input-sm" placeholder="{{ __('clinicCore::lang.prn_reason') }}" style="margin-top:4px;">'
        + '</td>'
        + '<td><button type="button" class="btn btn-danger btn-xs btn-remove-row"><i class="fa fa-trash"></i></button></td>'
        + '</tr>';
}

$('#btn_add_rx_row').on('click', function () {
    $('#rx_items_body').append(makeRow(rowIndex++));
});

$(document).on('click', '.btn-remove-row', function () {
    $(this).closest('tr').remove();
});

// ── AI prescription safety check ──────────────────────────────────────────
function rxSafetyColor(level) {
    return { none:'#16a34a', low:'#16a34a', moderate:'#d97706', high:'#dc2626' }[level] || '#64748b';
}
function rxRenderSafety(res) {
    var c = rxSafetyColor(res.risk);
    var esc = function (s) { return $('<div>').text(s == null ? '' : s).html(); };
    var h = '<div style="border:1px solid ' + c + ';border-left-width:4px;border-radius:8px;padding:10px 12px;background:#fff;">';
    h += '<div style="font-weight:700;color:' + c + ';"><i class="fa fa-shield-alt"></i> Risk: ' + esc((res.risk || 'unknown').toUpperCase()) + '</div>';
    if (res.summary) h += '<div style="margin:4px 0 6px;">' + esc(res.summary) + '</div>';
    if (res.flags && res.flags.length) {
        h += '<ul style="margin:0;padding-left:18px;">';
        res.flags.forEach(function (f) {
            h += '<li><strong style="color:' + rxSafetyColor(f.severity) + ';">[' + esc(f.type) + ' · ' + esc(f.severity) + ']</strong> ' + esc(f.detail) + '</li>';
        });
        h += '</ul>';
    } else {
        h += '<div class="text-muted">No significant issues flagged.</div>';
    }
    h += '<div class="text-muted" style="font-size:11px;margin-top:6px;">AI decision-support — the prescriber must verify against a current formulary.</div></div>';
    return h;
}
$('#btn_rx_safety').on('click', function () {
    var $btn = $(this);
    var drugs = [];
    $('#rx_items_body tr.rx-item-row').each(function () {
        var name = ($(this).find('.medicine-name-input').val() || $(this).find('.medicine-search').val() || '').trim();
        var dose = ($(this).find('input[name$="[dosage]"]').val() || '').trim();
        if (name) drugs.push({ name: name, dosage: dose });
    });
    if (!drugs.length) { (window.toastr ? toastr.warning('Add at least one medicine first.') : alert('Add at least one medicine first.')); return; }
    var patientId = $('#rx_patient_id').val() || '{{ request('patient_id') }}';
    $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Checking…');
    $('#rx_safety_result').html('');
    $.post('{{ route('clinic.prescriptions.check-safety') }}', { _token: '{{ csrf_token() }}', patient_id: patientId, drugs: drugs })
        .done(function (res) {
            if (!res.success) { (window.toastr ? toastr.error(res.msg || 'Check failed') : alert(res.msg || 'Check failed')); return; }
            $('#rx_safety_result').html(rxRenderSafety(res));
        })
        .fail(function (xhr) {
            var m = (xhr.responseJSON && xhr.responseJSON.msg) || 'Safety check failed';
            (window.toastr ? toastr.error(m) : alert(m));
        })
        .always(function () { $btn.prop('disabled', false).html('<i class="fa fa-shield-alt"></i> AI safety check'); });
});

// ── SIFA P3-T5 deterministic safety gate (runs before submit) ─────────────
var rxSafetyPassed = false;   // set true once the user confirms / no blockers
$('form').on('submit', function (e) {
    var $form = $(this);
    if (rxSafetyPassed) { return true; }  // already confirmed — allow through

    // Collect catalogue-linked medicine ids (free-text-only items can't be checked).
    var medIds = [];
    $('#rx_items_body tr.rx-item-row').each(function () {
        var id = parseInt($(this).find('.medicine-id-input').val() || '0', 10);
        if (id) medIds.push(id);
    });
    var patientId = $('#rx_patient_id').val() || '{{ isset($prescription) ? $prescription->patient_id : request('patient_id') }}';
    if (!medIds.length || !patientId) { return true; }  // nothing to screen

    e.preventDefault();
    $.post('{{ route('clinic.prescriptions.safety-check') }}', {
        _token: '{{ csrf_token() }}', patient_id: patientId, medicine_ids: medIds
    }).done(function (res) {
        if (!res.success || !res.warnings || !res.warnings.length) { rxSafetyPassed = true; $form.trigger('submit'); return; }
        var blocking = res.blocking;
        var esc = function (s) { return $('<div>').text(s == null ? '' : s).html(); };
        var h = '<div class="alert ' + (blocking ? 'alert-danger' : 'alert-warning') + '" style="border-left-width:4px;">';
        h += '<h4 style="margin-top:0;"><i class="fa fa-shield-alt"></i> {{ __('clinicCore::lang.rx_safety_warnings') }}</h4><ul style="margin-bottom:8px;">';
        res.warnings.forEach(function (w) {
            h += '<li><strong>[' + esc(w.type) + ' · ' + esc(w.severity) + ']</strong> ' + esc(w.message) + '</li>';
        });
        h += '</ul>';
        if (blocking) {
            h += '<label style="font-weight:600;"><input type="checkbox" id="rx_gate_confirm"> {{ __('clinicCore::lang.rx_safety_confirm') }}</label> ';
            h += '<button type="button" class="btn btn-danger btn-sm" id="rx_gate_proceed" disabled><i class="fa fa-check"></i> {{ __('clinicCore::lang.save') }}</button>';
        } else {
            h += '<button type="button" class="btn btn-warning btn-sm" id="rx_gate_proceed"><i class="fa fa-check"></i> {{ __('clinicCore::lang.save') }}</button>';
        }
        h += '</div>';
        $('#rx_safety_gate').html(h).show();
        if (blocking) {
            // Also carry the confirm flag to the server as a belt-and-braces guard.
            if (!$form.find('input[name="rx_safety_confirmed"]').length) {
                $form.append('<input type="hidden" name="rx_safety_confirmed" value="1">');
            }
        }
    }).fail(function () {
        // Fail-open on a screening error — the authoritative server-side guard still runs.
        rxSafetyPassed = true; $form.trigger('submit');
    });
    return false;
});
$(document).on('change', '#rx_gate_confirm', function () {
    $('#rx_gate_proceed').prop('disabled', !this.checked);
});
$(document).on('click', '#rx_gate_proceed', function () {
    rxSafetyPassed = true;
    $('form').first().trigger('submit');
});

// Medicine search autocomplete
$(document).on('input', '.medicine-search', function () {
    var q    = $(this).val();
    var $row = $(this).closest('tr');
    var $sug = $row.find('.medicine-suggestions');
    if (q.length < 2) { $sug.hide(); return; }
    $.get('{{ route('clinic.medicines.search') }}', { q: q }, function (data) {
        $sug.empty();
        if (!data.length) { $sug.hide(); return; }
        $.each(data, function (i, m) {
            $sug.append('<div class="sug-item" style="padding:6px 10px;cursor:pointer;" data-id="' + m.id + '" data-name="' + m.text + '">' + m.text + '</div>');
        });
        $sug.show();
    });
});

$(document).on('click', '.sug-item', function () {
    var $row = $(this).closest('tr');
    $row.find('.medicine-id-input').val($(this).data('id'));
    $row.find('.medicine-name-input').val($(this).data('name'));
    $row.find('.medicine-search').val($(this).data('name'));
    $(this).closest('.medicine-suggestions').hide();
});

$(document).on('click', function (e) {
    if (!$(e.target).hasClass('medicine-search') && !$(e.target).hasClass('sug-item')) {
        $('.medicine-suggestions').hide();
    }
});

// Doctor select
$('.select2').select2({ width: '100%' });

@if(!isset($prescription))
// Create mode: contact AJAX search + patient dynamic load
$('#rx_patient_id').select2({ width: '100%', placeholder: '— Select Patient —' });

$('#rx_contact_id').select2({
    width: '100%',
    minimumInputLength: 2,
    placeholder: 'Search contact by name / phone...',
    ajax: {
        url: '{{ route('clinic.patient-contacts.search') }}',
        dataType: 'json',
        delay: 300,
        data: function (p) { return { q: p.term }; },
        processResults: function (d) { return { results: d }; }
    }
}).on('select2:select', function (e) {
    var contactId = e.params.data.id;
    $('#rx_patient_id').empty().append('<option value="">Loading...</option>').trigger('change');
    $.get('{{ url('clinic/patients/by-owner') }}/' + contactId, function (data) {
        $('#rx_patient_id').empty().append('<option value="">— Select Patient —</option>');
        $.each(data, function (i, patient) {
            $('#rx_patient_id').append('<option value="' + pet.id + '">' + pet.text + '</option>');
        });
        $('#rx_patient_id').trigger('change');
    });
});

@if(request('contact_id') && request('patient_id'))
// Pre-populate from query-string (e.g., linked from appointment)
(function () {
    $.get('{{ url('clinic/patients/by-owner') }}/{{ request('contact_id') }}', function (data) {
        $('#rx_patient_id').empty().append('<option value="">— Select Patient —</option>');
        $.each(data, function (i, patient) {
            var sel = pet.id == '{{ request('patient_id') }}' ? ' selected' : '';
            $('#rx_patient_id').append('<option value="' + pet.id + '"' + sel + '>' + pet.text + '</option>');
        });
        $('#rx_patient_id').trigger('change');
    });
})();
@endif
@endif
</script>
@endsection
