@extends('layouts.app')

@section('title', isset($admission) ? 'Edit Admission' : __('vetAdmission::lang.new_admission'))

@section('content')
<section class="content-header">
    <h1><i class="fas fa-hospital-user"></i>
        {{ isset($admission) ? 'Edit Admission — ' . $admission->admission_no : __('vetAdmission::lang.new_admission') }}
    </h1>
</section>

<section class="content">
<form method="POST"
      action="{{ isset($admission) ? route('va.admissions.update', $admission->id) : route('va.admissions.store') }}">
    @csrf
    @php
        $edit = isset($admission);
        $pet  = $edit ? $admission->pet : ($preselectedPet ?? null);
        $ownerName = $pet ? optional($pet->owner)->name : null;
    @endphp

    <div class="row">
        <div class="col-md-8">
            @component('components.widget', ['class' => 'box-primary', 'title' => __('vetAdmission::lang.pet')])
                @if($edit || $pet)
                    <input type="hidden" name="contact_id" value="{{ $pet ? $pet->contact_id : '' }}">
                    <input type="hidden" name="pet_id" value="{{ $pet ? $pet->id : '' }}">
                    <div class="alert alert-info" style="margin-bottom:0;">
                        <i class="fa fa-paw"></i> <strong>{{ $pet->petname ?? '—' }}</strong>
                        @if($pet && $pet->species) ({{ $pet->species }}) @endif
                        @if($ownerName) &nbsp;·&nbsp; <i class="fa fa-user"></i> {{ $ownerName }} @endif
                    </div>
                @else
                    <div class="row">
                        <div class="col-md-6 form-group">
                            <label>@lang('vetAdmission::lang.owner') <span class="text-danger">*</span></label>
                            <select id="owner_select" class="form-control" style="width:100%"></select>
                            <input type="hidden" name="contact_id" id="contact_id">
                        </div>
                        <div class="col-md-6 form-group">
                            <label>@lang('vetAdmission::lang.pet') <span class="text-danger">*</span></label>
                            <select name="pet_id" id="pet_id" class="form-control" style="width:100%" required>
                                <option value="">— Select owner first —</option>
                            </select>
                        </div>
                    </div>
                @endif
            @endcomponent

            @component('components.widget', ['class' => 'box-primary', 'title' => __('vetAdmission::lang.admission')])
                <div class="row">
                    <div class="col-md-4 form-group">
                        <label>@lang('vetAdmission::lang.type') <span class="text-danger">*</span></label>
                        <select name="type" class="form-control">
                            @foreach(['hospitalization','boarding','surgery_recovery','observation','isolation'] as $t)
                                <option value="{{ $t }}" {{ $edit && $admission->type == $t ? 'selected' : '' }}>
                                    {{ ucfirst(str_replace('_',' ',$t)) }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-4 form-group">
                        <label>@lang('vetAdmission::lang.ward')</label>
                        <select name="ward_id" class="form-control">
                            <option value="">— Unassigned —</option>
                            @foreach($wards as $w)
                                <option value="{{ $w->id }}" {{ $edit && $admission->ward_id == $w->id ? 'selected' : '' }}>
                                    {{ $w->name }} ({{ ucfirst($w->type) }})
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-4 form-group">
                        <label>@lang('vetAdmission::lang.admitted_at') <span class="text-danger">*</span></label>
                        <input type="datetime-local" name="admitted_at" class="form-control" required
                            value="{{ $edit ? optional($admission->admitted_at)->format('Y-m-d\TH:i') : now()->format('Y-m-d\TH:i') }}">
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4 form-group">
                        <label>@lang('vetAdmission::lang.admitting_doctor')</label>
                        <select name="admitting_doctor_id" class="form-control">
                            <option value="">—</option>
                            @foreach($doctors as $d)
                                <option value="{{ $d->id }}" {{ $edit && $admission->admitting_doctor_id == $d->id ? 'selected' : '' }}>{{ $d->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-4 form-group">
                        <label>@lang('vetAdmission::lang.attending_doctor')</label>
                        <select name="attending_doctor_id" class="form-control">
                            <option value="">—</option>
                            @foreach($doctors as $d)
                                <option value="{{ $d->id }}" {{ $edit && $admission->attending_doctor_id == $d->id ? 'selected' : '' }}>{{ $d->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-4 form-group">
                        <label>@lang('vetAdmission::lang.expected_discharge')</label>
                        <input type="datetime-local" name="expected_discharge_at" class="form-control"
                            value="{{ $edit && $admission->expected_discharge_at ? $admission->expected_discharge_at->format('Y-m-d\TH:i') : '' }}">
                    </div>
                </div>
                <div class="form-group">
                    <label>@lang('vetAdmission::lang.reason')</label>
                    <input type="text" name="reason" class="form-control" value="{{ $edit ? $admission->reason : '' }}">
                </div>
                <div class="form-group">
                    <label>@lang('vetAdmission::lang.diagnosis')</label>
                    <textarea name="diagnosis" class="form-control" rows="2">{{ $edit ? $admission->diagnosis : '' }}</textarea>
                </div>
                <div class="row">
                    <div class="col-md-6 form-group">
                        <label>@lang('vetAdmission::lang.daily_rate')</label>
                        <input type="number" step="0.01" name="daily_rate" class="form-control" value="{{ $edit ? $admission->daily_rate : '' }}">
                    </div>
                    <div class="col-md-6 form-group">
                        <label>@lang('vetAdmission::lang.deposit')</label>
                        <input type="number" step="0.01" name="deposit_amount" class="form-control" value="{{ $edit ? $admission->deposit_amount : '' }}">
                    </div>
                </div>
            @endcomponent

            @unless($edit)
            @component('components.widget', ['class' => 'box-success', 'title' => __('vetAdmission::lang.care_plan')])
                <p class="text-muted" style="font-size:12px;">
                    Set the initial daily care routine. You can adjust it later from the patient chart.
                </p>
                <table class="table table-condensed" id="care_rows">
                    <thead><tr>
                        <th>@lang('vetAdmission::lang.care_task')</th>
                        <th style="width:120px;">@lang('vetAdmission::lang.times_per_day')</th>
                        <th>@lang('vetAdmission::lang.instructions')</th>
                        <th style="width:40px;"></th>
                    </tr></thead>
                    <tbody></tbody>
                </table>
                <button type="button" class="btn btn-sm btn-default" id="add_care_row">
                    <i class="fa fa-plus"></i> @lang('vetAdmission::lang.add_care_task')
                </button>
            @endcomponent
            @endunless
        </div>

        <div class="col-md-4">
            <div class="box box-default"><div class="box-body">
                <button type="submit" class="btn btn-primary btn-block">
                    <i class="fa fa-save"></i> {{ $edit ? 'Update' : __('vetAdmission::lang.admit_pet') }}
                </button>
                <a href="{{ route('va.admissions.index') }}" class="btn btn-default btn-block">Cancel</a>
            </div></div>
        </div>
    </div>
</form>
</section>
@endsection

@section('javascript')
<script>
$(function () {
    @unless(isset($admission) || ($preselectedPet ?? false))
    $('#owner_select').select2({
        width: '100%', placeholder: '— Search pet owner —', minimumInputLength: 1,
        ajax: {
            url: '{{ route('vc.pet-owners.search') }}', dataType: 'json', delay: 250,
            data: function (p) { return { q: p.term }; },
            processResults: function (d) { return { results: d }; }
        }
    }).on('select2:select', function (e) {
        var cid = e.params.data.id;
        $('#contact_id').val(cid);
        $('#pet_id').html('<option value="">— loading —</option>');
        $.getJSON('{{ url('vet-clinic/pets/by-owner') }}/' + cid, function (pets) {
            var html = '<option value="">— Select pet —</option>';
            pets.forEach(function (p) { html += '<option value="' + p.id + '">' + p.text + '</option>'; });
            $('#pet_id').html(html);
        });
    });
    $('#pet_id').select2({ width: '100%' });
    @endunless

    // Care plan dynamic rows
    var taskOptions = '<option value="">— Select task —</option>';
    @foreach($taskTypes as $t)
        taskOptions += '<option value="{{ $t->id }}">{{ addslashes($t->name) }}</option>';
    @endforeach

    function careRow() {
        return '<tr>' +
            '<td><select name="care_task_type_id[]" class="form-control input-sm">' + taskOptions + '</select></td>' +
            '<td><input type="number" name="times_per_day[]" class="form-control input-sm" value="2" min="1" max="24"></td>' +
            '<td><input type="text" name="care_instructions[]" class="form-control input-sm" placeholder="e.g. 1 cup dry food"></td>' +
            '<td><button type="button" class="btn btn-xs btn-danger rm-care-row"><i class="fa fa-times"></i></button></td>' +
            '</tr>';
    }
    $('#add_care_row').on('click', function () { $('#care_rows tbody').append(careRow()); });
    $(document).on('click', '.rm-care-row', function () { $(this).closest('tr').remove(); });
    @unless(isset($admission))
    $('#care_rows tbody').append(careRow()).append(careRow());
    @endunless
});
</script>
@endsection
